Naren,
This is a common problem with the gyro. We got the following solution from
http://www.droidsrobotics.org, and in turn have contributed some of our code to their great site. I encourage other teams to help these guys build a useful repository of foundational code, they're doing it the right way.
Anyway - here is the code that will cure your gyro woes:
I'm not sure how well the photo will come through, but here's a brief explanation - this all goes into a 'reset gyro' myBlock that you can call when you need to reset it.
1) play a tone to signify the start of calibration
2) read the angle and rate
start a loop
3) read the angle only - apparently switching from angle+rate to angle mode causes it to go into reset mode
4) check to see if the angle is >= 0 OR < 0, more on that in a moment
end the loop when step 4 evaluates to true
5) play a tone to signify that calibration has finished.
So, what the heck is going on here? It appears that when you switch from reading angles/rates, to just angles, it causes the gyro to reset itself. While it is resetting, it will return 'NaN', which stands for 'Not a Number'. NaN's have caused me more headaches than I care to admit as a professional software engineer... they're hard to detect. The property that is being exploited here is that NaN returns 'false' when compared to any other number. It's not >, =, or < anything, because it's Not a Number. What the loop is doing is just reading the angle from the gyro (after it has been put into reset mode) until it starts returning actual numbers.
Finally - Once I found this, I tried it out and simply explained it to the team. I strongly believe that you don't have to re-invent everything. If someone else has published a good solution, then it's perfectly fine to understand it and use it. It gave us a great opportunity to discuss how computers represent things like NaN (which can happen when you divide a number by zero). They all understood it and we have a robot that turns :)
Hope this helps you or anyone else that is suffering from the dizzy robot syndrome..
-Frank Levine
Coach, "The Construction Mavericks"