Sunday, July 29, 2007

Arduino + Servos



Since I received my brand new Arduino boards I´ve been migrating my electronics projects from PICAXE to Arduinio. The first step was to be able to control a servo using the Arduino board.
There are two options:
  • Use delays and digital outputs to create the typical PWM that servos expect: I discarded this option because I need to manage serial communications while the servo signal is been created.
  • There is an Arduino library that take advantage of the Atmega 168 hardware: This is definitely the solution for my problem.
Installing the ServoTimer1 library

  • Get the library from Arduino web.
  • Copy the content of the .zip file to the following folder lib\targets\libraries\ServoTimer1, relative to the Arduino development environment installation path.
  • Using the last development environment, Arduino 0008, and the WinAVR-20070525 I found that a symbol used in the ServoTimer1.cpp was undefined, removing it from the code solved the problem. So, remove _BV(TICIE1).
  • This library has a little drawback, it can only manages 2 servos. But that's enough for me.
Arduino test code
I used the sample code placed in the Arduino web page just modifying the serial speed to 115200. Program Arduino with this code.

// Example code for using ServoTimer1 library
// hardware control of up to two servos, on Arduino pins 9 & 10

#include 

ServoTimer1 servo1;
ServoTimer1 servo2;

void setup()
{
   pinMode(1,OUTPUT);
   servo1.attach(9);
   servo2.attach(10);
   Serial.begin(115200);
   Serial.print("Ready");
}

void loop()
{
  static int v = 0;

  if ( Serial.available()) {
    char ch = Serial.read();

    switch(ch) {
    case '0'...'9':
      v = v * 10 + ch - '0';
      break;
    case 's':
      servo1.write(v);
      v = 0;
      break;
    case 'w':
      servo2.write(v);
      v = 0;
      break;
    case 'd':
      servo2.detach();
      break;
    case 'a':
      servo2.attach(15);
      break;
    }
  }

  ServoTimer1::refresh(); // not needed, for compatibility with the software servo library
}

Using python to control the servo from the PC
  • There is a nice module for python, pySerial, that allows you to access the serial port of your PC
  • Using this module I coded a simple script to test it all

# Test code that sends commands to move a servo from 0 degrees to 180 five times
# to an Arduino board connected a serial port.
import serial
import time

def TestServo():
    #open first serial port
    serialPort = serial.Serial(4, 115200)

    #check which port was really used
    print serialPort.portstr

    for i in range(5):
        serialPort.write("0s")
        time.sleep(1)
        print "Step"
        serialPort.write("180s")
        time.sleep(1)
        print "Step"

    serialPort.close()



def main():
    TestServo()
    print "Done"

if __name__ == '__main__':
    main()



No comments:

Post a Comment