ClarkeRubber

Arduino - Serial Servo Control

Dec 14th, 2012
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. Servo myservo;
  4. int servo_output;
  5. int servo_pin = 3;
  6. int message;
  7. String temp;
  8. char ascii_table[] = {' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*',
  9.                     '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5',
  10.                     '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@',
  11.                     'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'I', 'J', 'K', 'L',
  12.                     'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  13.                     'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd',
  14.                     'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  15.                     'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{',
  16.                     '|', '}', '~'};
  17.  
  18. char ascii_to_char(int ascii){
  19.   return ascii_table[ascii - 32];
  20. }
  21.  
  22. String capture_stream(){
  23.   int input;
  24.   String output;
  25.   boolean flag = false;
  26.   while((input = Serial.read()) != -1){
  27.     output += String(ascii_to_char(input));
  28.     flag = true;
  29.   }
  30.   if(flag){
  31.     Serial.println(String(output));
  32.     return output;
  33.   }else{
  34.     Serial.println(String("-1"));
  35.     return "-1";
  36.   }
  37. }
  38.  
  39. void setup(){
  40.   Serial.begin(9600);
  41.   Serial.println("starting up");
  42.   myservo.attach(servo_pin);
  43.  
  44. }
  45.  
  46. void loop(){
  47.   temp = capture_stream();
  48.   servo_output = temp.toInt();
  49.   if(servo_output != -1){
  50.     if(servo_output > 180){
  51.       servo_output = 180;
  52.     }else if(servo_output < 0){
  53.       servo_output = 0;
  54.     }
  55.     myservo.write(servo_output);
  56.   }
  57.   delay(1000);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment