我正在使用Processing和Arduino Uno使用两个电位计控制屏幕上圆圈的位置。 Arduino和计算机通过蓝牙进行通信。以下是Processing sketch的代码:
import processing.serial.*;
Serial myPort;
int x, y;
void setup() {
size(400, 400);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 115200);
myPort.bufferUntil('\n');
background(255);
noStroke();
}
void draw() {
}
void serialEvent(Serial myPort) {
println("here");
String inString = myPort.readStringUntil('\n');
if (inString != null) {
inString = trim(inString);
String items[] = split(inString, ',');
if (items.length > 1) {
float a = float(items[0]);
float b= float(items[1]);
x = (int) map(a, 0, 1023, 0, width);
y = (int) map(b, 0, 1023, 0, height);
background(255);
fill(255, 0, 0);
ellipse(x, y, 10, 10);
}
}
//myPort.write('\r');
}
以下是Arduino的代码:
const int left_pot = A2;
const int right_pot = A3;
int x;
int y;
void setup(){
Serial.begin(115200);
/* while (Serial.available()<=0){
Serial.println("hello?");
}*/
}
void loop(){
//if (Serial.available() > 0) {
int inByte = Serial.read();
x = analogRead(left_pot);
y = analogRead(right_pot);
Serial.print(x);
Serial.print(", ");
Serial.println(y);
delay(2);
//}
}
发布后,代码可以正常工作,但屏幕上的点非常紧张。所以我尝试实施一个基于“How Things Talk”的握手协议(Igoe,第62页)。注释掉的行应该是这样做的。但是当它们被取消注释时,红点不再显示,处理草图永远不会到达命令println(“here”)。
我正在使用32位Processing 2.0.1。
答案 0 :(得分:2)
您的Arduino草图会一直等到它在发送数据之前收到一些数据。因此,您的Processing sketch必须首先通过序列发送一些内容到Arduino。目前它没有。尝试添加一些东西来打印它:
void setup() {
size(400, 400);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 115200);
myPort.bufferUntil('\n');
background(255);
noStroke();
myPort.write('\r'); //Get the arduino to reply
}