串口读带处理,找不到字符串
Serial Port Reading with Processing, cannot find the string
我正在尝试从 Processing 中读取串口。为此,我正在尝试基本的 hello world 示例。我写你好世界!来自 Arduino 并尝试使用 Processing 捕获它。以下是代码:
这是 Arduino Uno 的代码:
void setup()
{
//initialize serial communications at a 9600 baud rate
Serial.begin(9600);
}
void loop()
{
//send 'Hello, world!' over the serial port
Serial.println("Hello, world!");
//wait 100 milliseconds so we don't drive ourselves crazy
delay(100);
}
这里是处理代码:
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
String check = "Hello, world!";
String portName = Serial.list()[1]; //COM4
void setup() {
myPort = new Serial(this, portName, 9600);
println("Starting Serial Read Operation");
}
void draw()
{
if ( myPort.available() > 0) { // If data is available,
val = myPort.readStringUntil('\n');
println(val);
if (val != null && val.equals("Hello, world!") == true) {
println("Found the starting Point");
}
}
}
我无法捕捉到校验字符串。
处理的输出:
null
Hello, world!
null
Hello, world!
null
Hello, world!
Hello, world!
根据输出,我可以成功读取串口。 (但是有很多null,我不知道为什么。)但是我无法捕获指定的字符串。
您知道问题出在哪里吗?
此致
Arduino 在使用 println 时发送 \r\n
。
当您比较时,比较失败,因为您正在比较 "Hello, world!\r"
和 "Hello, world!"
。
您可以通过使用 Serial.print()
并手动向字符串添加 \n
或在文本后发送 Serial.write('\n');
来解决此问题(重复可以用辅助函数代替)。
我正在尝试从 Processing 中读取串口。为此,我正在尝试基本的 hello world 示例。我写你好世界!来自 Arduino 并尝试使用 Processing 捕获它。以下是代码:
这是 Arduino Uno 的代码:
void setup()
{
//initialize serial communications at a 9600 baud rate
Serial.begin(9600);
}
void loop()
{
//send 'Hello, world!' over the serial port
Serial.println("Hello, world!");
//wait 100 milliseconds so we don't drive ourselves crazy
delay(100);
}
这里是处理代码:
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
String check = "Hello, world!";
String portName = Serial.list()[1]; //COM4
void setup() {
myPort = new Serial(this, portName, 9600);
println("Starting Serial Read Operation");
}
void draw()
{
if ( myPort.available() > 0) { // If data is available,
val = myPort.readStringUntil('\n');
println(val);
if (val != null && val.equals("Hello, world!") == true) {
println("Found the starting Point");
}
}
}
我无法捕捉到校验字符串。
处理的输出:
null
Hello, world!
null
Hello, world!
null
Hello, world!
Hello, world!
根据输出,我可以成功读取串口。 (但是有很多null,我不知道为什么。)但是我无法捕获指定的字符串。
您知道问题出在哪里吗?
此致
Arduino 在使用 println 时发送 \r\n
。
当您比较时,比较失败,因为您正在比较 "Hello, world!\r"
和 "Hello, world!"
。
您可以通过使用 Serial.print()
并手动向字符串添加 \n
或在文本后发送 Serial.write('\n');
来解决此问题(重复可以用辅助函数代替)。