Robotics 2012-12-09

And now for something closer to the real deal, using one of the AVR’s timers to implement and steer a Pulse Width Modulated signal that swings one of the robot’s leg pairs gently backward and forward…

#include <avr/io.h>
#define F_CPU 8000000
#include <util/delay.h>

int sleep() {
  int i = 0;

  for (i = 0; i < 2; ++i)

  return 1;

int main(void)
  int i = 0;

  DDRB = (1 << PB4); // configure port PB4 as an output port
  ICR1 = 20000;      // place the desired TOP value in the register whence it will be sourced
  OCR1B = 1500;      // set the initial width of the pulse

  // tell the micro-controller the wave generation mode of interest, the pre-scaler, and how to output the signal
  TCCR1A = (1<<COM1A1)| (1<<COM1B1) | (1<<WGM11);
  TCCR1B = (1<<WGM13) | (1<<WGM12)  | (1<<CS11);

  while (1) {
    // gradually widen the pulse
    while (OCR1B < 1800) {
      OCR1B += 10;

    // gradually narrow the pulse
    while (OCR1B > 1200) {
      OCR1B -= 10;

In other words, we want the servo to be given a PWM signal with a frequency of 50Hz, so we match a pre-scaler of 8 with our 8MHz processor to yield 1M ticks per second, we carve those million ticks up into chunks of 20K ticks to yield a 50Hz signal, and we invert the output signal from high to low somewhere between 1200 and 1800 ticks into a chunk to yield a pulse width between 1.2ms and 1.8ms… Voila!

Now we just have to control all three leg pairs, do it in concert, and somehow hook everything together so when the robot actually moves it doesn’t unplug itself…

Leave a Reply