Advertisement
Guest User

Arduino Servo Control

a guest
Jul 31st, 2017
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. /*******************************************************
  2. * SerialServoControl Sketch
  3. * Written by Ryan Owens for SparkFun Electronics
  4. * 7/15/11
  5. *
  6. * This sketch listens to serial commands and uses the data
  7. * to set the position of two servos.
  8. *
  9. * Serial Command Structure: 2 bytes - [ID Byte][Servo Position byte]
  10. * ID byte should be 0 or 1.
  11. * Servo position should be a value between 0 and 180.
  12. * Invalid commands are ignored
  13. * The servo position is not error checked.
  14. *
  15. * Hardware Setup
  16. * Servos should be connected to pins 2 and 3 of the Arduino.
  17. * 9V DC Power supply is recommended as USB can't always handle powering two servos
  18. */
  19. #include <Servo.h>  //Used to control the Pan/Tilt Servos
  20.  
  21. //These are variables that hold the servo IDs.
  22. char tiltChannel=0, panChannel=1;
  23.  
  24. //These are the objects for each servo.
  25. Servo servoTilt, servoPan;
  26.  
  27. //This is a character that will hold data from the Serial port.
  28. char serialChar=0;
  29.  
  30. void setup(){
  31.   servoTilt.attach(2);  //The Tilt servo is attached to pin 2.
  32.   servoPan.attach(3);   //The Pan servo is attached to pin 3.
  33.   Serial.begin(57600);  //Set up a serial connection for 57600 bps.
  34. }
  35.  
  36. void loop(){
  37.   if(Serial.available() > 0){  //Wait for a character on the serial port.
  38.   serialChar = Serial.read();
  39.   }
  40.   if(serialChar == tiltChannel){
  41.     while(Serial.available() <=0){  
  42.     servoTilt.write(Serial.read());
  43.     }
  44.   }
  45.   else if(serialChar == panChannel){ //Check to see if the initial serial character was the servo ID for the pan servo.
  46.     if(Serial.available() <= 0){  //Wait for the second command byte from the serial port.
  47.     servoPan.write(Serial.read());
  48.     }
  49.   }
  50.   //If the character is not the pan or tilt servo ID, it is ignored.
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement