You should know that yawning is the body's response to the insufficiency of oxygen for the brain. When we fall asleep, the frequency of breathing is going down gradually, that's why we need less energy while sleeping. If you feel sleepy but you don't sleep, the brain wants more oxygen. As a solution for this, the brain finds it useful that you yawn. When you yawn, the quantity of oxygen you breathe in is increasing.
Yawning is one of the non-verbal communication signal between people. That's the reason why yawning is "contagious". You probably noticed that when one begins to yawn, the people surrounding him usually yawn as well.