gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:52:05 24 4
gpt4 key购买 nike

为什么我总是得到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com