I'm having trouble sending a byte array to an Arduino using Processing.
I'm using a modified version of the standard PhysicalPixel example.
When you mouseover the square I set the first byte to 255.
It seems to be setting it correctly.
But when it gets to the Arduino I'm having a hard time figuring out how to read the value.
I tried printing using Serial.print but it's hard to understand what it's saying.
Arduino code:
const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
#define MAX_MILLIS_TO_WAIT 1000 //or whatever
unsigned long starttime;
byte bytes[512];
void setup() {
// initialize serial communication:
Serial.begin(115200);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
starttime = millis();
while ( (Serial.available() < 512) && ((millis() - starttime) < MAX_MILLIS_TO_WAIT) ) {
// hang in this loop until we either get 9 bytes of data or 1 second
// has gone by
}
if (Serial.available() < 512) {
// the data didn't come in - handle that problem here
Serial.println("ERROR - Didn't get 512 bytes of data!");
Serial.flush();
}
else {
for(int n=0; n < 512; n++) {
bytes[n] = Serial.read(); // Then: Get them.
}
//Serial.println(bytes[0]);
if (bytes[0] == 255) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
}
Processing code:
import processing.serial.*;
float boxX;
float boxY;
int boxSize = 20;
boolean mouseOverBox = false;
Serial port;
byte[] bytes = new byte[512];
void setup() {
size(200, 200);
boxX = width/2.0;
boxY = height/2.0;
rectMode(RADIUS);
// List all the available serial ports in the output pane.
// You will need to choose the port that the Arduino board is
// connected to from this list. The first port in the list is
// port #0 and the third port in the list is port #2.
println(Serial.list());
// Open the port that the Arduino board is connected to (in this case #0)
// Make sure to open the port at the same speed Arduino is using (9600bps)
port = new Serial(this, Serial.list()[0], 115200);
for (int i=0; i<512; i++) {
bytes[i] = byte(0);
}
}
void draw()
{
background(0);
// Test if the cursor is over the box
if (mouseX > boxX-boxSize && mouseX < boxX+boxSize &&
mouseY > boxY-boxSize && mouseY < boxY+boxSize) {
mouseOverBox = true;
// draw a line around the box and change its color:
stroke(255);
fill(153);
// send an 'H' to indicate mouse is over square:
//port.write('H');
bytes[0] = byte(255);
//print(bytes);
port.write(bytes);
}
else {
// return the box to it's inactive state:
stroke(153);
fill(153);
// send an 'L' to turn the LED off:
port.write('L');
mouseOverBox = false;
}
// Draw the box
rect(boxX, boxY, boxSize, boxSize);
}
What am I doing wrong here?