Saturday, January 8, 2011


Today I wanted to check out how the Arduino Uno handles a servo. Since I wanted to create a similar setup as with the SunsPOT, I had to connect switches to the Arduino first.

Handling switches is pretty easy. All you need to do is to connect one connection of the switch to a digital port and the other connection of the switch to GND. In the software later on, you can use the boards integrated pull up resistors to set the digital port to high. Now if the switch is pressed, you have a connection to GND and the signal on the port changes to low. This setup had to be done for two switches.

Now the only thing left to do was to connect the servo to the Arduino. The Vin connector of the servo has to be connected to the 5V port of the Arduino. The GND connector has to be connected to a GND port of the Arduino and the signal connector to a port with PWM (pulse-width modulation). They are marked with a ~ sign.

Here is a simple schematic of the setup:

The source code is pretty straight forward. You only need to include the servo library.

#include <Servo.h>
Servo servo;
int pos;
int switchLeft = 4;
int switchRight = 2;
int switchValueLeft;
int switchValueRight;

void setup() {
  //assign pin 9 to the servo
  pinMode(13, OUTPUT);
  //assign the two switches
  pinMode(switchLeft, INPUT);
  pinMode(switchRight, INPUT);
  //set both digital ports to high
  digitalWrite(switchLeft, HIGH);
  digitalWrite(switchRight, HIGH);
  //just shows a LED signal that the arduino is ready
  digitalWrite(13, HIGH);  
  digitalWrite(13, LOW);

void loop() {
  //read current value on the port
  switchValueLeft = digitalRead(switchLeft);
  switchValueRight = digitalRead(switchRight);
  if(switchValueLeft == LOW) {
    //if left button is pressed, move left
  } else if(switchValueRight == LOW) {
    //if right button is pressed, move right
  //keeps the servo value in its range
  if(pos > 180) {
  } else if(pos < 0){
  //move servo
This is a demonstration of the Arduino controlled servo:

No comments:

Post a Comment