Advertisement
Guest User

Projeto 26

a guest
Apr 17th, 2012
1,640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. // Project 26
  2. #include <Servo.h>
  3.  
  4. char buffer[10];
  5. Servo servo1;  // Create a servo object
  6. Servo servo2;  // Create a second servo object  
  7.  
  8. void setup()
  9. {
  10.     servo1.attach(5);  // attaches the servo on pin 5 to the servo1 object
  11.     servo2.attach(6);  // attaches the servo on pin 6 to the servo2 object
  12.     Serial.begin(9600);
  13.     Serial.flush();
  14.     servo1.write(90);  // put servo1 at home position
  15.     servo2.write(90);  // put servo2 at home postion
  16.     Serial.println("STARTING...");
  17. }
  18.  
  19. void loop()
  20. {
  21.     if (Serial.available() > 0) { // check if data has been entered
  22.         int index=0;
  23.         delay(100); // let the buffer fill up
  24.         int numChar = Serial.available(); // find the string length
  25.         if (numChar>10) {
  26.         numChar=10;
  27.         }
  28.         while (numChar--) {
  29.            // fill the buffer with the string
  30.                    buffer[index++] = Serial.read();    
  31.                 }
  32.         splitString(buffer); // run splitString function
  33.     }
  34. }
  35.  
  36. void splitString(char* data) {
  37.     Serial.print("Data entered: ");
  38.     Serial.println(data);
  39.     char* parameter;
  40.     parameter = strtok (data, " ,"); //string to token
  41.   while (parameter != NULL) { // if we haven't reached the end of the string...
  42.         setServo(parameter); // ...run the setServo function
  43.         parameter = strtok (NULL, " ,");
  44.     }
  45.     // Clear the text and serial buffers
  46.     for (int x=0; x<9; x++) {
  47.         buffer[x]='\0';
  48.     }
  49.     Serial.flush();
  50. }
  51.  
  52.  
  53. void setServo(char* data) {
  54.     if ((data[0] == 'L') || (data[0] == 'l')) {
  55.         int firstVal = strtol(data+1, NULL, 10); // string to long integer
  56.         firstVal = constrain(firstVal,0,180); // constrain values
  57.         servo1.write(firstVal);
  58.         Serial.print("Servo1 is set to: ");
  59.         Serial.println(firstVal);
  60.     }
  61.     if ((data[0] == 'R') || (data[0] == 'r')) {
  62.         int secondVal = strtol(data+1, NULL, 10); // string to long integer
  63.         secondVal = constrain(secondVal,0,255); // constrain the values
  64.         servo2.write(secondVal);
  65.         Serial.print("Servo2 is set to: ");
  66.         Serial.println(secondVal);
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement