Hi there,
I'm trying to adapt an existing Etch-a-Sketch project which takes input from 2 potentiometers and draws in Processing. There is also some code for clearing the screen on a shake (using a tilt sensor), and that is where my issue lies.
Arduino code:
int x;
int y;
int pushButton = 2;//originally was a pushbutton but now is a tilt sensor
void setup()
{
Serial.begin(9600);
pinMode(2,INPUT);
}
void loop()
{
int buttonState = digitalRead(pushButton);
x = analogRead(A0);
y = analogRead(A1);
Serial.print(x);
Serial.print(",");
Serial.print(y);
Serial.print(",");
Serial.println(buttonState);
delay(50);
}
Processing code:
import processing.serial.*;
Serial port;
String serialInterface = "/dev/ttyUSB0";
int lastX = -1;
int lastY = -1;
void setup() {
size(1024, 920);
background(205);
port = new Serial(this, serialInterface, 9600);
}
void handleData(int x, int y) {
if (lastX >= 0 && lastY >= 0) {
line(x, y, lastX, lastY);
}
lastX = x;
lastY = y;
}
void draw() {
readSerial();
}
void mouseClicked() {
saveFrame();
// added to save the drawing
}
void readSerial() {
int x; int y; int z;
String s;
while ((s = port.readStringUntil('\n')) != null) {
String[] parts = s.substring(0, s.length()-2).split(",");
if (parts.length == 3) {
x = int(parts[0]);
y = int(parts[1]);
z = int(parts[2]);
if (z==0) {
background(205);//clears the screen when shaken
}
handleData(x, y);
}
}
}
The problem is that with the code as written above, the image constantly clears itself. If I change the if loop towards the bottom to read:
if (z!=0) {
background(205);//clears the screen when shaken
}
then the image persists, but if I invert the sensor, the line drawing darts to the top right, then back to the current x,y position, rather than clearing the screen.
Alternately, if I comment out any mention of the z variable, I can draw but I have no way to erase.
I'm a complete novice, and I've been banging my head on this for hours. Can anyone point me to my almost certainly obvious mistake?
Edit: I've made a bit of headway in that I can now get the image to clear (by changing the above if statement to z==1, but the cursor still moved to the top right when you invert the sensor to make it read ON. The serial monitor indicates that the input on x and y go to 1023 and 0, respectively, but I have no idea why that would be. I attempted to pin the potentiometers off the breadboard, but this resulted in more volatility, as the x and y inputs jump all over the place when the potentiometers aren't anchored in place.
From the datasheet, it doesn't seem like it should matter how the potentiometers are oriented. Perhaps there is a fault in the breadboard of the leads on the potentiometer? Any ideas are welcome.