Recitation 9: Serial Communication (Leon)

Recitation 9: Serial Communication

Date: 12/16/2018

Instructor: Leon & Yang

In today’s recitation, we were asked to use Arduino to send two values to Processing via serial communication. To build a sketch that works like¬†Etch A Sketch.

For this exercise, I built a circuit with two potentiometers first. And wrote a very simple code in Arduino to read the two analog values from potentiometers. My code in Arduino looks like this:

void setup() {
Serial.begin(9600);
}

void loop() {
int sensor1 = analogRead(A0);
int sensor2 = analogRead(A1);

Serial.print(sensor1);
Serial.print(“,”);
Serial.print(sensor2);
Serial.println();

 

}

Then I built a sketch in Processing. Firstly I imported the values from Arduino. And then I created the ellipses which change positions according to the values from Arduino. My code looks like this:

 

import processing.serial.*;

String myString = null;
Serial myPort;

 

int Val = 2;
int[] sensorValues;
int[] oldValues;

 

void setup() {
size(1000, 1000);
background(0);
noStroke();
frameRate(30);
setupSerial();
}

 

void draw() {
updateSerial();
printArray(sensorValues);

 

 

fill(255);
ellipse(sensorValues[0],sensorValues[1],10,10);

//
}

 

void setupSerial() {
printArray(Serial.list());
myPort = new Serial(this, Serial.list()[ 7 ], 9600);

myPort.clear();

myString = myPort.readStringUntil( 10 ); // 10 = ‘\n’ Linefeed in ASCII
myString = null;

sensorValues = new int[Val];
}

 

void updateSerial() {
while (myPort.available() > 0) {
myString = myPort.readStringUntil( 10 ); // 10 = ‘\n’ Linefeed in ASCII
if (myString != null) {
String[] serialInArray = split(trim(myString), “,”);
if (serialInArray.length ==Val) {
for (int i=0; i<serialInArray.length; i++) {
sensorValues[i] = int(serialInArray[i]);
}
}
}
}
}

 

And the sketch works like this:

 

I didn’t get to the second exercise.

Leave a Reply