So this is part of a larger project but I can't seem to get the basics working. The arduino sends a message (1 or 0) which adds or subtracts from the variable 'num'. Num determines the position of a rect. Everything works fine, but for some reason it doesn't subtract from num when the rect is in the middle third. It is hard to explain but if you run the code it will be a lot easier to understand.
Arduino code:
void setup()
{
Serial.begin(9600);
pinMode(13,INPUT); //Move left
pinMode(10,INPUT); //Move right
}
void loop()
{
if(digitalRead(13)==HIGH) //Send message to move left
{
Serial.write(2);
delay(200);
}
if(digitalRead(10)==HIGH) //Sent message to move right
{
Serial.write(1);
delay(200);
}
}
Processing code:
import processing.serial.*;
Serial myPort;
int num = 1;
void setup() {
size(500,500);
myPort = new Serial(this, Serial.list()[4], 9600);
rectMode(CENTER);
}
void draw() {
background(0);
if(num>=1&&num<=2&&myPort.read()==1) //Add 1 if rect is in the first or second third
{
num++;
}
else if(num>=2&&num<=3&&myPort.read()==2) ////Subtract 1 if rect is in the second or third third
{
num--;
}
rect(num*width/3-(width/6),height/2,width/3,height); //Display rect
}
if(num>=1&&num<=2&&myPort.read()==1) //Add 1 if rect is in the first or second third
Serial port data arrives slowly. The draw() function is not called as fast as the loop() function in Arduino, but it is still called a lot.
Now, suppose that draw is called a dozen times between bytes arriving. On each pass, myPort.read() will not equal 1 (or 2). Now, further, suppose that a 2 arrives. myPort.read() will not return a 1, so the 2 is discarded.
else if(num>=2&&num<=3&&myPort.read()==2) ////Subtract 1 if rect is in the second or third third
And, the next character hasn't arrived, yet, so this will not be true, either.
You should read a value from the port, and store it in a variable. Then, if the variable contains something other than -1, use the value that it does contiain:
if(num>=1&&num<=2&&myPort.read()==1) //Add 1 if rect is in the first or second third
Serial port data arrives slowly. The draw() function is not called as fast as the loop() function in Arduino, but it is still called a lot.
Now, suppose that draw is called a dozen times between bytes arriving. On each pass, myPort.read() will not equal 1 (or 2). Now, further, suppose that a 2 arrives. myPort.read() will not return a 1, so the 2 is discarded.
else if(num>=2&&num<=3&&myPort.read()==2) ////Subtract 1 if rect is in the second or third third
And, the next character hasn't arrived, yet, so this will not be true, either.
You should read a value from the port, and store it in a variable. Then, if the variable contains something other than -1, use the value that it does contiain: