Driving a servo with a butterfly.

Go To Last Post
2 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I just got this working and since I couldn't find any simple source code when I started I'm posting it. Comments about possible problems or just suggestions for improvements are very welcome. (including suggestions about formatting code for posting - it's definitely indented properly in my editor)

#include
#include
#include

#define SERVO_PORT PORTD
#define SERVO_PORT_DIR DDRD
#define SERVO_PIN (1 << PD0)
#define SERVO_PIN_ON (SERVO_PORT |= SERVO_PIN)
#define SERVO_PIN_OFF (SERVO_PORT &= ~SERVO_PIN)
#define SERVO_PIN_TOGGLE (SERVO_PORT ^= SERVO_PIN)

#define SERVO_MIN 75
#define SERVO_CENTER 90
#define SERVO_MAX 105

int main(void)
{
CLKPR = (1 << CLKPCE);
CLKPR = 0; // no prescale on system clock

SERVO_PORT_DIR = 0xFF;
SERVO_PIN_OFF;

TCCR0A = 0 | (1 << WGM01) | (0 << WGM00) // CTC
| (1 << CS02) | (0 << CS01) | (1 << CS00); // prescaler 1024
TIMSK0 = (1 << OCIE0A); // compare interrupt enabled
OCR0A = 156; // compare value for 20ms frames

sei();

while(1)
_delay_loop_2(20000);
}

SIGNAL(SIG_OUTPUT_COMPARE0)
{
SERVO_PIN_ON; // pulse begins
ASSR = 0; // want to use system clock NOT watch crystal as input here!
TCCR2A = 0 | (1 << WGM21) | (0 << WGM20) // CTC
| (1 << CS22) | (0 << CS21) | (0 << CS20); // prescaler 64
TIMSK2 = (1 << OCIE2A); // compare interrupt enabled

OCR2A = SERVO_CENTER;
}

SIGNAL(SIG_OUTPUT_COMPARE2) // pulse is finished, turn it off
{
TCNT2 = 0;
TIMSK2 = 0;
TCCR2A = 0;
SERVO_PIN_OFF;
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
Including suggestions about formatting code for posting

Use the Code button.

Quote:
Comments about possible problems or just suggestions for improvements are very welcome

Controlling a servo is just Pulse Width Modulation. The AVR timers have modes that do just that. You code could be simplified to a few lines of code for initialization and virtually no code to keep it running. You only need code to change the pulse width when necessary. With the Butterfly this is a little more difficult since the pins dedicated to PWM output are used by other things, but if you don't mind giving up one of the joystick pins, or don't mind hearing the speaker whine while controlling your servo, it can be done. If not, you have to do a little more work and toggle the pin manually, but you can still do it with one timer instead of two.

Regards,
Steve A.

The Board helps those that help themselves.