在逐步调试方面做得很好,例如仔细检查电子侧的接线并单独使用 Arduino 测试闪烁代码以隔离问题。
如果 Blink 草图是您上传到开发板的唯一 Arduino 代码,这还不够。处理确实会向 Arduino 发送消息(这就是您看到 RX LED 亮起的原因),但 Arduino 代码中没有初始化 Serial communication
正如您在该示例中看到的,在setup() 中,串行通信初始化为 9600 波特率(通信速度,每秒 9600 字节/字符):
Serial.begin(9600);
然后在 draw() 中,如果有可用数据,则读取每个字符,然后一次打印一个并带有前缀消息:
// 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);
}
如果您上传链接的示例,如果您有一个串行端口,那么当您运行处理程序草图时,您应该会在 TX LED 闪烁之后看到两个 RX。如果您关闭该草图,在 Arduino 中打开串行监视器并输入一些内容,然后按 Enter,您将看到从 Arduino 读回的调试消息。
使用这些概念,您可以像这样编写基本草图:
int incomingByte = 0; // for incoming serial data
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
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);
// if we received ASCII character '1', turn LED on
if(incomingByte == '1'){
digitalWrite(9,HIGH);
}
// if we received ASCII character '0', turn LED off
if(incomingByte == '0'){
digitalWrite(9,LOW);
}
}
}
将此草图上传到您的 Arduino 应该允许您在串行监视器中输入 1,然后按 Enter 键打开 LED 或按 0 将其关闭。
唯一剩下的就是从处理中发送相同的数据:
import processing.serial.*;
Serial arduino;
void setup(){
try{
arduino = new Serial(this, Serial.list()[0], 9600);
}catch(Exception e){
println("error connecting to serial port, double chek USB connection, serial port and close other programs using Serial");
e.printStackTrace();
}
}
void draw(){
}
void keyPressed(){
if(key == '1'){
if(arduino != null){
arduino.write('1');
}else{
println("arduino serial connection wasn't initialised");
}
background(255);
}
if(key == '0'){
if(arduino != null){
arduino.write('0');
}else{
println("arduino serial connection wasn't initialised");
}
background(0);
}
}
小注:注意我没有在处理中使用delay(),我推荐using millis(),因为它不会像delay()那样阻止代码的执行。
所以上面的代码看起来有点像只是为了让 LED 闪烁,但关键是要了解串行通信的基础知识,从长远来看这将是有用的:
- 初始化与 Arduino 的串行通信(了解波特率)
- 串行字节的基本读/写
- 从处理和发送数据初始化串行通信
回到您最初的问题,您错过了有关您在 Processing 中使用的 Arduino 库的一个重要细节:它依赖于一个名为 Firmata 的特殊 Arduino 草图(固件)。您将能够在此 Arduino and Processing 教程中阅读更多关于此内容以及如何使用该库的信息。
正如教程中提到的,您需要先从 Arduino > Examples > Firmata > StandardFirmata 上传此草图。还要记住波特率设置为57600,而不是9600,因此您需要像这样更新您的代码:
arduino = new Arduino(this, Arduino.list()[0], 57600);