Hardware Servo: Example Code

Sebastian,

I had been trying to generate a 24MHz clock for an image sensor and this post got me there. Thank you. I had tried poking around with some code you had put up in a thread on timer interrupts (which seemed to me the most obvious solution) but getting an output faster than about 200KHz seemed over my head. I believe I was limited by the speed of "write," even with the faster "port manipulation" method.

I also tried modifying some code from stimmer who's been working on VGA output. Unfortunately his code seemed to highjack every clock on the chip; I was getting 24MHz on the SCL pin, which is way to fast for an I2C bus. I couldn't use the serial port, either. Regardless, I'm up and running thanks to this Servo example. I hope this can help someone else heading down a similar path. In that vein, I'll share what I've discovered.

The timing for a square wave can be set by manipulating three factors in the example code: PWM_CLOCK, PWM_PERIOD, and dutyCycle. PWM_CLOCK is set to 1 000 000, let's say one million "ticks." PWM_PERIOD is set to 20 000, so our pin will go high every 20 000 "ticks." The dutyCycle variable is initially set at 1200, so the pin will remain high for 1200 "ticks" then go low. It will go high again after the end of the period; after 18800 more "ticks." (1200 + 18800 = 20 000 = PWM_PERIOD)

Obviously, the dutyCycle must be less than or equal to PWM_PERIOD, and PWM_PERIOD must be less than or equal to PWM_CLOCK. I'm not certain about the top speed of PWM_CLOCK, but it's somewhere between 48 000 000 and 100 000 000. (If I had to make a bet, I'd guess 84MHz is the magic number.) Outputting a 24MHz wave the squareness appears much more sine, though this may be a result of my low bandwidth scope that hasn't been calibrated since 1989. Eh, the image sensor eats it up and runs just fine, so I don't worry.