arduino - Arduino 中的串行可用始终返回 0

标签 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 bit/s
}

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 ");
}

最佳答案

你的程序在我的 Arduino 上运行良好,尽管你需要一些延迟来阻止快速发出的“我什么也没收到”消息。我会更改“我什么也没收到” block 以包括几秒钟的延迟,例如延迟(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;
    }
  }
}

关于arduino - Arduino 中的串行可用始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474172/

相关文章:

go - 在 Arduino Yún 上执行 Go 程序

visual-studio - 如何在 Visual Studio 类资源管理器中查看 Arduino 库?

arduino - 没有以太网的 mqtt 串行消息

arduino - 我已将伺服和 PIR 与 NodeMCU 连接,但伺服无法正常工作

c++ - Tinkercad 编写 Arduino C++ 代码时出现无用的错误

c++ - 在 Arduino 上拆分字符串

c++ - 如何为 Arduino IDE 安装 openCV 库?

c - Arduino C 不进入循环?

python - pySerial发送和接收多个数据

python - Python 中的温度转换 : How to convert int (0 - 255) which is a byte object to degrees Celsius in Python