Advertisement
Guest User

SerialServo

a guest
May 5th, 2016
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. // Sweep
  2. // by BARRAGAN <http://barraganstudio.com>
  3. // This example code is in the public domain.
  4.  
  5.  
  6. #include <Servo.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #define NUM_SERVOS 1
  10. #define MAX_SERVOS 6
  11. #define OUTBUF_SIZE 100
  12. char outbuf[OUTBUF_SIZE];
  13. const int pins[] = { 3, 5, 6, 9, 10, 11 }; //all the PWM pins on the arduino platform minus the serial console
  14. static Servo * servos[NUM_SERVOS]; // create servo object to control a servo
  15. static Servo * ServoPointer;     // a maximum of eight servo objects can be created
  16.  
  17.  
  18. void setup()
  19. {
  20.   for (int i = 0; i < NUM_SERVOS && i < MAX_SERVOS; i++)  //Initializes the servo objects
  21.   {
  22.     ServoPointer = new Servo;
  23.     servos[i] = ServoPointer;
  24.     servos[i]->attach(pins[i]); //actually attach them (in order of the arduino numbering of the PWM pins)
  25.   }
  26.   Serial.begin(115200);
  27.  
  28. }
  29.  
  30. void loop()
  31. {
  32. #define INPUT_SIZE 30
  33.  
  34.  
  35. // Get next command from Serial (add 1 for final 0)
  36. char input[INPUT_SIZE + 1];
  37. byte size = Serial.readBytes(input, INPUT_SIZE);
  38. // Add the final 0 to end the C string
  39. input[size] = 0;
  40.  
  41. // Read each command pair
  42. char* command = strtok(input, "&");
  43. while (command != 0)
  44. {
  45.     // Split the command in two values
  46.     char* separator = strchr(command, ':');
  47.     if (separator != 0)
  48.     {
  49.         // Actually split the string in 2: replace ':' with 0
  50.         *separator = 0;
  51.         int servoId = atoi(command); //Parsing code credit to https://arduino.stackexchange.com/questions/1013
  52.         ++separator;
  53.         int position = atoi(separator);
  54.        
  55.         if ((servoId <= NUM_SERVOS) && !(servoId <1))
  56.         {
  57.           servos[servoId]->write(position);
  58.           sprintf(outbuf, "Moving Servo ID %d to position %d", servoId, position);
  59.           Serial.println(outbuf);
  60.         }else {
  61.           sprintf(outbuf, "Servo ID %d is out of bounds, please make it between 1 and %d", servoId, NUM_SERVOS);
  62.           Serial.println(outbuf);
  63.         }
  64.     }
  65.     // Find the next command in input string
  66.     command = strtok(0, "&");
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement