Skip to content

Instantly share code, notes, and snippets.

@mitchtech
Created July 1, 2012 19:26
Show Gist options
  • Save mitchtech/3029316 to your computer and use it in GitHub Desktop.
Save mitchtech/3029316 to your computer and use it in GitHub Desktop.
Arduino Serial Servo Control
/*******************************************************
* SerialServoControl Sketch
* Written by Ryan Owens for SparkFun Electronics
* 7/15/11
*
* This sketch listens to serial commands and uses the data
* to set the position of two servos.
*
* Serial Command Structure: 2 bytes - [ID Byte][Servo Position byte]
* ID byte should be 0 or 1.
* Servo position should be a value between 0 and 180.
* Invalid commands are ignored
* The servo position is not error checked.
*
* Hardware Setup
* Servos should be connected to pins 5 and 6 of the Arduino.
* 9V DC Power supply is recommended as USB can't always handle powering two servos
*/
#include <Servo.h> //Used to control the Pan/Tilt Servos
//These are variables that hold the servo IDs.
char tiltChannel=0, panChannel=1;
//These are the objects for each servo.
Servo servoTilt, servoPan;
//This is a character that will hold data from the Serial port.
char serialChar=0;
void setup(){
servoTilt.attach(5); //The Tilt servo is attached to pin 5.
servoPan.attach(6); //The Pan servo is attached to pin 6.
servoTilt.write(90); //Initially put the servos both
servoPan.write(90); //at 90 degress.
Serial.begin(9600); //Set up a serial connection for 9600 bps.
}
void loop(){
while(Serial.available() <=0); //Wait for a character on the serial port.
serialChar = Serial.read(); //Copy the character from the serial port to the variable
if(serialChar == tiltChannel){ //Check to see if the character is the servo ID for the tilt servo
while(Serial.available() <=0); //Wait for the second command byte from the serial port.
servoTilt.write(Serial.read()); //Set the tilt servo position to the value of the second command byte received on the serial port
}
else if(serialChar == panChannel){ //Check to see if the initial serial character was the servo ID for the pan servo.
while(Serial.available() <= 0); //Wait for the second command byte from the serial port.
servoPan.write(Serial.read()); //Set the pan servo position to the value of the second command byte received from the serial port.
}
//If the character is not the pan or tilt servo ID, it is ignored.
}
@therealmax
Copy link

I can't get this to work on my sparkfun ardupilot atmega328, when I print serialChar to the serial monitor it prints to a separate line for each character for example i type 1 10 it prints
1

1
0
is this why it's not working?

@salmanfarisvp
Copy link

try Serial.parseInt insted of Serial.read.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment