No one really knows, and I find that fascinating. Though there are some theories, such as a lack of oxygen, or a warning to stay alert (which may explain why it's contagious), but it's not known for sure. It's just something weird we do :D
One is that when we are bored or tired, we just don't breathe as deeply as we usually do. As this theory goes, our bodies take in less oxygen because our breathing has slowed. Therefore, yawning helps us bring more oxygen into the blood and move more carbon dioxide out of the blood.