Hi Cai,
It can be quite tricky to communicate with an arduino. I spent 2 days figuring out how to do it for my project: A universal ambilight
I adapted the basic Serial example form processing. The idea stays the same: when the mouse is over the rectangle then then an LED connected to the pin number 4 light up.
The processing code:
import processing.serial.*;
Serial myPort;
void setup()
{
size(300, 300);
myPort = new Serial(this, Serial.list()[0], 9600);
delay(5000);
}
void draw() {
background(20);
myPort.write(mouseX + ";" + mouseY + ";");
if (mouseOverRect()) {
fill(220, 20, 20);
} else {
fill(200);
}
rect(100, 100, 100, 100);
}
boolean mouseOverRect() { // Test if mouse is over square
return ((mouseX >= 100) && (mouseX <= 200) && (mouseY >= 100) && (mouseY <= 200));
}
The arduino code:
const long BAUD_RATE = 9600;
int x, y;
void setup() {
Serial.begin(BAUD_RATE);
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
newData = false;
x = 0;
y = 0;
}
void loop() {
receiveData();
if (x >= 100 && x <= 200 && y >= 100 && y <= 200) {
digitalWrite(4, HIGH);
} else {
digitalWrite(4, LOW);
}
}
void receiveData() {
if (Serial.available() > 0) {
x = Serial.parseInt();
y = Serial.parseInt();
Serial.read();
}
}
Two things are worth noticing:
- The
delay(5000)
is used to let the time to the arduino mode to correctly make the connection with the computer. - Be careful at the baud rate, it can be the reason why you can’t read some data. In my project, I had to set the baud rate to 500000 to make it works.