串行可用始终在arduino中返回0

时间:2015-04-06 15:21:54

标签: arduino

为什么我一直0?我尝试了几种方法然后我在arduino网站上获取了示例代码,但这也没有用。我总是得到Serial.available()=0

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
        else Serial.print("I received nothing ");
}

4 个答案:

答案 0 :(得分:2)

你的程序在我的Arduino上工作正常,尽管你需要一些延迟来阻止快速射击"我什么都没收到"消息。我会改变"我没有收到任何"阻止包括几秒钟的延迟,例如延迟(3000)延迟3秒。

另外,请考虑更改代码以使用SerialEvent()过程,如下所示:SerialEvent example

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

答案 1 :(得分:0)

我遇到了类似的问题并通过包含简短的delay()语句解决了这个问题。似乎Arduino读取第一个字节并被以下内容中断...

答案 2 :(得分:0)

怎么了?没有。代码正常,硬件正常。 Serial.available()返回缓冲区中等待读取的字符数,因此,如果不发送任何内容,它将始终返回零/ false。

int incomingByte = 0;

void setup() {Serial.begin(9600);}

void loop() {
        if (Serial.available() > 0) {
                incomingByte = Serial.read();
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
        else Serial.print("I received nothing\n");
        delay(1000);

}

上传此代码并将“ ss”发送到串行缓冲区将产生:

0:00:00.000 -> I received:115 //s
0:00:00.000 -> I received:115 //s
0:00:00.000 -> I received:10  //newline

答案 3 :(得分:0)

启动串行连接后,某些板会重新启动。这样,当您进行echo smth > /dev/serial/xxxx板重置时,不会收到smth并且Serial.available()永远不会发生。可以忽略此行为,也可以与cat > /dev/serial/xxxx进行通信。

请我花点时间弄清楚,希望它对某人有帮助。