我发现了一个问题:port = new Serial(this, 9600); 应该是 port = new Serial(this, Serial.list()[0], 9600);。您在 Serial 构造函数中遗漏了一个(重要的)参数。始终检查处理控制台中的错误(在您的代码下方),特别是如果代码不起作用:)
我将从 Processing 附带的 SimpleWrite 示例开始,这样您就可以先了解 Processing/Arduino 之间的通信是如何工作的,然后继续使用您的项目中获得的知识。
基本设置是这样的:
在 Processing 中,您在 setup() 中初始化 Serial 实例,在 draw 中,您使用 Serial 的 write() 方法发送值。
在 Arduino 中,在 setup() 中初始化 Serial (Serial.begin(yourBaudRate)) 并在 loop() 中检查是否有可用数据和 read() 值。
在 Processing 和 Arduino 中使用相同的波特率非常很重要,否则您将无法识别传输的大部分数据。
此外,您不必拘泥于发送字符串,您还可以发送整数、字节等。
如果要显示这些,不要忘记将类型添加为 Serial.print() 或 Serial.println() 的第二个参数(例如 Serial.println(myByte,BYTE); 或 Serial.println(myInt ,DEC));
我已经在 Arduino 中设置了一个非常基本的草图,当你的方块被切换时闪烁一次 LED
否则什么也不做。此外,传入的数据会打印在串行监视器中:
int incoming = 0;//这将存储来自 Serial 的值
void setup(){
pinMode(13,OUTPUT);//add an LED on PIN 13 for kicks
Serial.begin(9600);//init Serial library (make sure Processing is sending data at the same baud rate)
}
void loop(){
if(Serial.available() > 0){//look for Serial data
incoming = Serial.read();//read and store teh value
Serial.print(incoming,DEC);//print it to the Serial monitor, change DEC to the type of variable you're using
if(incoming == 1){//if it's a 1 blink once
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
}
}
我已经稍微调整了你正在处理的草图:
boolean squareVisible = true;
int x = 50;
int y = 50;
int w = 100;
int h = 100;
import processing.serial.*;
Serial port;
int val;
void setup() {
size(200, 200);
noStroke();
fill(255, 0, 0);
rect(x, y, w, h);
String portName = Serial.list()[0];
port = new Serial(this, portName, 9600);
}
void draw() {
background(255);
if (squareVisible) {
fill(40, 80, 90);
} else {
fill(255, 0, 0);
}
rect(x, y, w, h); // Draw a square
}
void mousePressed() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
// if mouse clicked inside square
squareVisible = !squareVisible; // toggle square visibility
if(squareVisible) port.write(0);
else port.write(1);
}
}
/*
void mouseMoved() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
port.write(2);
}
}*/
祝你好运!