Part One: Etch A Sketch
For this exercise, use Arduino to send two analog values to Processing via serial communication. To do this, build a circuit with two potentiometers and write an Arduino sketch that reads their values and sends them serially. Then write a Processing sketch that draws an ellipse and reads those two analog values from Arduino. This sketch should modify the ellipseās x and y values based on the input from Arduino. Just like an Etch A Sketch, one potentiometer should control the ellipseās x-axis movement, and the other should control the ellipseās y-axis movement. To see how an Etch A Sketch works, you can watch the video here.
Once you have it working with an ellipse, modify the code to use a line instead (like a real Etch A Sketch). To do this, you will need to keep track of the previous x and y values so that you can draw a line from there to the new x and y positions.
Arduino Sketch
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int mappedvalue1 = map(sensorValue1, 0, 1023, 0, 600);
int mappedvalue2 = map(sensorValue2, 0, 1023, 0, 600);
Serial.print(mappedvalue1);
Serial.print(“,”);
Serial.print(mappedvalue2);
Serial.println();
delay(1);
}
Processing Sketch
import processing.serial.*;
String myString = null;
Serial myPort;
int x;
int y;
int NUM_OF_VALUES = 2;
int[] sensorValues;
void setup(){
size(600,600);
background(210,237,254);
setupSerial();
}
void draw(){
updateSerial();
stroke(random(100),random(100),0);
strokeWeight(3);
line(x,y,sensorValues[0],sensorValues[1]);
x = sensorValues[0];
y = sensorValues[1];
}
void setupSerial() {
printArray(Serial.list());
myPort = new Serial(this, Serial.list()[ 5 ], 9600);
// WARNING!
// You will definitely get an error here.
// Change the PORT_INDEX to 0 and try running it again.
// And then, check the list of the ports,
// find the port "/dev/cu.usbmodem----" or "/dev/tty.usbmodem----"
// and replace PORT_INDEX above with the index number of the port.
myPort.clear();
// Throw out the first reading,
// in case we started reading in the middle of a string from the sender.
myString = myPort.readStringUntil( 10 ); // 10 = '\n' Linefeed in ASCII; 10 means linebreak in ASCII code
myString = null;
sensorValues = new int[NUM_OF_VALUES];
}
void updateSerial() {
while (myPort.available() > 0) {
myString = myPort.readStringUntil( 10 ); // 10 = '\n' Linefeed in ASCII
if (myString != null) {
String[] serialInArray = split(trim(myString), ",");
//put them in the array in this way. remember to put a coma between so that the computer understands
if (serialInArray.length == NUM_OF_VALUES) {
for (int i=0; i<serialInArray.length; i++) {
sensorValues[i] = int(serialInArray[i]);
}
}
}
}
}