Recitation 11: Serial Communication Workshop by Shina Chang

I attended professor Young’s Serial Communication workshop with the hopes to improve my serial communication skills. The course was catered towards the student’s final projects, so we mainly worked with circuits that go from Arduino to Processing but we also covered Processing to Arduino. I chose to document the Processing to Arduino circuit. Hopefully, I can try to incorporate some type of feedback for my projects user when they play my final project game. Maybe when players touch a sensor lights will flash or turn on to indicate to the player that they are using the game correctly. 

Code:

Processing:

import processing.serial.*;

int NUM_OF_VALUES = 2; /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/

Serial myPort;
String myString;

int values[] = new int[NUM_OF_VALUES];

void setup() {
size(500, 500);
background(0);

printArray(Serial.list());
myPort = new Serial(this, Serial.list()[ 3 ], 9600);

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

void draw() {
background(0);

values[0] = mouseX;
values[1] = mouseY;

// sends the values to Arduino.
sendSerialData();

echoSerialData(200);
}

void sendSerialData() {
String data = “”;
for (int i=0; i<values.length; i++) {
data += values[i];
//if i is less than the index number of the last element in the values array
if (i < values.length-1) {
data += “,”; // add splitter character “,” between each values element
}
//if it is the last element in the values array
else {
data += “n”; // add the end of data character “n”
}
}
//write to Arduino
myPort.write(data);
}

void echoSerialData(int frequency) {

if (frameCount % frequency == 0) myPort.write(‘e’);

String incomingBytes = “”;
while (myPort.available() > 0) {

incomingBytes += char(myPort.read());
}

print( incomingBytes );
}

Arduino:

#define NUM_OF_VALUES 2 /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/

/** DO NOT REMOVE THESE **/
int tempValue = 0;
int valueIndex = 0;

/* This is the array of values storing the data from Processing. */
int values[NUM_OF_VALUES];

void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(11, OUTPUT);
}

void loop() {
getSerialData();

int brightness1 = map(values[0], 0, 500, 0, 255);
int bightness2 = map(values[1], 0, 500, 0, 255);

analogWrite(9, values[0]);
analogWrite(11, values[1]);

}

//recieve serial data from Processing
void getSerialData() {
if (Serial.available()) {
char c = Serial.read();

switch (c) {

case ‘0’…’9′:

tempValue = tempValue * 10 + c – ‘0’;
break;

case ‘,’:
values[valueIndex] = tempValue;

tempValue = 0;

valueIndex++;
break;

case ‘n’:

values[valueIndex] = tempValue;

tempValue = 0;
valueIndex = 0;
break;

case ‘e’: // to echo
for (int i = 0; i < NUM_OF_VALUES; i++) {
Serial.print(values[i]);
if (i < NUM_OF_VALUES – 1) {
Serial.print(‘,’);
}
else {
Serial.println();
}
}
break;
}
}
}

Leave a Reply