Let's Make Robots!

ATtiny servo control


After a brief discussion with fellow LMR member Maxhirez, about his Hedwig robot,
it seems as though there isn't much support for servos in the ATtiny family of
microcontrollers. After fighting with the 8-bit servo library I found HERE that was
supposed to make it as easy as a standard Arduino to add servos to an ATTiny project,
I decided to start from scratch and create something that was user friendly and Arduino
IDE compatable. Eventually I hope to turn this code into a fully functional open source
library, but until then I wanted to share the code I used to sweep a 9g servo on an
ATtiny84. Here's some code I came up with last night to get a servo to sweep somewhat
accurately that should work out-of-the-box. Future updates should eliminate the delay()
function and support multiple servos. Comments and suggestions are welcome.

              // **** ATtiny Servo Sweep Example **** // const byte servo = 0; // Servo pin on ATtiny int tPulse = 4000; // Total pulse length on 1 Mhz clock int hPulse = 60; // High pulse time (60=0deg -> 280=180deg) bool Dir          =    1;         // Servo direction void setup() {   pinMode(servo, OUTPUT); } void loop() {   digitalWrite(servo, HIGH); // Set pin high to start pulse   delayMicroseconds(hPulse); // High pulse angle data   digitalWrite(servo,LOW); // Set low for the rest of pulse   delayMicroseconds(tPulse-hPulse);      if (hPulse < 280 && Dir == 1) hPulse+=10; // Rotate servo to 180 degrees   else if (hPulse >= 280 && Dir == 1){ // Servo hit upper limit     hPulse = 280;                           // Keep servo angle in bounds     Dir=!Dir;                               // Switch direction   }   if (hPulse > 60 && Dir == 0) hPulse-=10; // Rotate servo to 0 degrees   else if (hPulse <= 60 && Dir == 0){ // Servo hit lower limit     hPulse = 60;                            // Keep servo angle in bounds     Dir=!Dir;                               // switch direction   }   delayMicroseconds(500); // Give servo some time to move before giving it a new position }

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

See my article Servo Math and my programs to get full range out of your servos.

Nice work, but I don't think the ATTinies support 2 way serial communication, And I'm not sure your method supports a slower clock rate. I could have gotten a bit more range, but dialed it back so it didn't strip anyones servo. Collected for future reference though ;)