Hey guys,
I was taking a look at the Servo() lib, wondering why it was limited to only 12 servos per timer, and though I'm not certain, it seems like there may be room for improvement. (And that is an understatement.)
First, let's discuss how servos work, and why 12 servos per timer is the magic number here.
Servos work by keeping track of the length of time between pulses on their signal line. To keep them in a particular position, every 20 milliseconds, you need to set their signal pin high for between 1 and 2ms. A pulse of 1.5ms, with a low period of 18.5ms, will keep the servo centered. These pulses need to be sent constantly or the servo will stop trying to center itself and move freely instead.
So how does the Servo() lib send these pulses? Well, it looks like it uses the interrupt to time the pulse for only one servo at a time. So, for servo one, it sets the servo's signal pin high, then sets the interrupt to trigger when it should go low again... up to 2ms later. It then moves on to the next servo and does the same thing. The limit on the number of servos comes from the amount of time you have between when you need to send pulses. And the Servo() lib seems to play fast and loose with the standards, allowing up to 24 milliseconds between pulses instead of the usual 20, which give enough time for 12 pulses up up to 2ms each before it needs to repeat the first.
This seems really inefficient to me however.
It seems to me that every 20ms, one could toggle all the servo pins high at once and then turn them off one by one as needed when a particular servo's time is up. Using some sorted arrays could make deciding on how long to wait to trigger the next interrupt very fast. In this way, one could control as many servos as they wanted from a single interrupt. I see no reason why you shouldn't be able to control 64 of them in this manner with just one timer interrupt.
Anyway I'm interested in hearing your thoughts on this. I'm not going to have time myself to test this theory out for a while, and I don't really need more than 12 servos myself, but if one were developing a spider-bot or something and one didn't want to waste their precious timers or use a MEGA, then the ability to control 20 on a standard Arduino might come in handy.