To control the servos used for the Pi-Bug robot, we require a special control signal that will determine the angle that the servo is required to move to. We will send the servo a PWM signal, where the duration of the on time will allow us to control the angle of the servo arm (and thereby, allow us to control the Pi-Bug robot's legs). The following diagram shows how a PWM signal can be used to control the angle of the servo:
Most servos will have an angular range of approximately 180 degrees and a mid-position of 90 degrees. A PWM frequency of 50 Hz will have a period of 20 ms, and the mid-position of 90 degrees typically corresponds to an Up Time of 1.5 ms, with a range of +/- 0.5 ms to 0.4 ms for near 0 degrees and near 180 degrees. Each type of servo will be slightly different, but you should be able to adjust the code to suit if required. The following diagram shows how you can control the servo angle using different PWM Up Times:
Although it is theoretically possible to generate these signals using software, you will find that any tiny interruption by other processes on the system will interfere with the signal timing; this, in turn, will produce an erratic response from the servo. This is why we use a hardware PWM controller, which only needs to be set with a specific up and down time, to then automatically generate the required signal for us.