Arduino Serial返回未知值

时间:2015-12-29 06:12:05

标签: arduino serial-communication

所以现在这是我的代码,它试图读取我的LED灯条的不同RGB值

然而,当我到达我要求绿色值的位置时,会有一个未知的字节经过,它会自动直接进入green()中的else部分;

我没有输入任何东西但是Serial说那里有东西。它是什么?

  #define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  Serial.begin(9600);
  Serial.println("Starting Program....");
  start();

}

  int g = 0;

char val = 0;
String valstr = "";

 void loop(){  
      if(Serial.available() > 0){
      val = Serial.read();

       if(val != '\n'){
      valstr += val;
       }
       else{
        Serial.println(valstr);

        if (valstr != "Yes"){
          valstr = "";
        start();
                }
                else{
                  Serial.print("Now Asking for RGB values: \n");
                  Serial.println("What is green value: ");
                 green();
               //
               //
                valstr = "";
            //    start();   
                }
      valstr = "";
//    green();

     }
      }
 }




void start(){
  Serial.print("Do you want a new color? Enter Yes/No:  ");  
}


 char gbyte = 0;
 String gstr = "";
 boolean not_number;

 int gnum = 256;


void green(){

    if(Serial.available() > 0)
      gbyte = Serial.read();

      if ((gbyte >= '0') && (gbyte <= '9')) {
      gstr += gbyte;
      }
    else if(gbyte == ' '){
      Serial.println("This is not a number! \n");
      Serial.println("Enter a valid number!");
      gstr = "";

      gbyte = Serial.read();


    }
    else{
      Serial.println(gstr);
      Serial.println("This is a number");

    }

      gstr += gbyte;

 //     gnum = gstr.toInt();

 //     if((gnum >= 0) && (gnum <= 255))

1 个答案:

答案 0 :(得分:0)

我认为问题在于解析串口的整数。 Arduino具有内置功能:

https://www.arduino.cc/en/Reference/ParseInt