Advertisement
Guest User

3 Servos e Serial

a guest
Jul 20th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. String comandoBt, id, valorSerial;
  4.  
  5. int valorServo = 0;
  6.  
  7. Servo servo1;
  8. Servo servo2;
  9. Servo servo3;
  10.  
  11. void setup(){
  12.   Serial.begin(9600);
  13.  
  14.   servo1.attach(9);
  15.   servo2.attach(10);
  16.   servo3.attach(11);
  17. }
  18.  
  19. void loop() {
  20.  
  21.   if (Serial.available()) {
  22.  
  23.     while (Serial.available()>0){
  24.       char serial = Serial.read();      
  25.       comandoBt += serial;  
  26.       delay(10);
  27.     }
  28.  
  29.     verificaComando();
  30.     /**
  31.     * // para depuração na Serial
  32.     Serial.print("Geral: ");
  33.     Serial.println(comandoBt);
  34.    
  35.     Serial.print("ID: ");
  36.     Serial.println(id);
  37.    
  38.     Serial.print("Valor: ");
  39.     Serial.println(valorSerial);
  40.     */
  41.    
  42.     if(id == "s1") {
  43.       //Serial.println("Servo1 sera acionado");
  44.       servo1.write(valorServo);  
  45.     }
  46.    
  47.     if(id == "s2") {
  48.       //Serial.println("Servo2 sera acionado");
  49.       servo2.write(valorServo);  
  50.     }
  51.    
  52.     if(id == "s3") {
  53.       //Serial.println("Servo3 sera acionado");
  54.       servo3.write(valorServo);  
  55.     }
  56.    
  57.     // limpa as Strings para próxima leitura
  58.     comandoBt = "";
  59.     id = "";
  60.     valorSerial = "";
  61.   }
  62. }
  63.  
  64. void verificaComando()
  65. {
  66.   // Primeiro, vamos olhar para o separador que é ',' (vírgula)
  67.   if(comandoBt.indexOf(",")>=0)
  68.   {
  69.     // Se for encontrado, temos a primeira sequencia até o separador
  70.     // vamos salvar na String id para identificar qual servo acionar
  71.     id = comandoBt.substring(0,(comandoBt.indexOf(",")));
  72.    
  73.     // Em seguida, temos os caracteres a partir do separador de espaço até
  74.     // o fim da string e vamos salvar na string valorSerial
  75.     valorSerial = comandoBt.substring(comandoBt.indexOf(",")+1);
  76.    
  77.     // transforma a String valorSerial em um inteiro para aplicar no servo
  78.     valorServo = valorSerial.toInt();
  79.  
  80.   }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement