This is code to control a robot I made with the Lego WeDo kit. You can see a video of the robot in action here: https://vimeo.com/131129127 A pole rests on a wheel, and so moves left or right when the wheel turns. The robot moves the wheel until it finds the point where the pole balances exactly level. It then announces its success with a trumpet call. I have included several photos of the robot as backgrounds. Key to this model is the distance sensor, which looks down on the pole from above. When the pole is balanced, it will be exactly 46 units away. When it is tilted to the right, the it will be closer, and when tilted to the left further away. The robot can thus tell which direction to move the wheel, and get some idea of how far it needs to be moved. When the pole is far from level, the robot turns the wheel in bigger increments than when the pole is almost level. After each turn of the wheel, the robot stops and waits for the pole to stop rocking before continuing. If you change any aspect of the model, including the colour of the pole, you will need to adjust the balance distance to reflect the reading obtained when the pole is level. To help you with this, Scratch (the cat) continually reports this distance.
This project was inspired by the game Scratch and Sniff: https://scratch.mit.edu/projects/41321958/