Recitation 8: Serial Communication by Min Jee (Lisa) Moon

Exercise 1: Make a Processing Etch A Sketch

For exercise 1, we were asked to build an Etch A Sketch. 

Circuit Diagram for Potentiometer

Using above design, I built circuit and adjusted the code according to the sample code from the class. The resulting code is below:

Arduino:

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

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

float sensor1Map = map(sensor1, 0, 1023, 0, 450);
float sensor2Map = map(sensor2, 0, 1023, 0, 450);

// keep this format
Serial.print(sensor1Map);
Serial.print(“,”); // put comma between sensor values
Serial.print(sensor2Map);
Serial.println(); // add linefeed after sending the last sensor value

// too fast communication might cause some latency in Processing
// this delay resolves the issue.
delay(100);
}

Processing:

// IMA NYU Shanghai
// Interaction Lab
// For receiving multiple values from Arduino to Processing

/*
 * Based on the readStringUntil() example by Tom Igoe
 * https://processing.org/reference/libraries/serial/Serial_readStringUntil_.html
 */

import processing.serial.*;

String myString = null;
Serial myPort;


int NUM_OF_VALUES = 2;   /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/
int[] sensorValues;      /** this array stores values from Arduino **/

float pointerSize = 3;

int amtDigit = 0;
float[] xPos = new float[amtDigit];
float[] yPos = new float[amtDigit];

float curXPos;
float curYPos;

void setup() {
  size(500, 500);
  background(0);
  setupSerial();
  
  curXPos = 25 + sensorValues[0];
  curYPos = 25 + sensorValues[1];
  
  xPos = append(xPos, curXPos);
  yPos = append(yPos, curYPos);
}


void draw() {
  updateSerial();
  //printArray(sensorValues);
  printArray(curXPos);
  background(#C9C8C5);
  
  curXPos = 25 + sensorValues[0];
  curYPos = 25 + sensorValues[1];
  
  // pointer
  noStroke();
  fill(0);
  ellipse(curXPos, curYPos, pointerSize, pointerSize);

  checkAndAppend();
  
  if (amtDigit > 1){
    for(int i = 0; i < amtDigit; i++){
      stroke(0);
      strokeWeight(pointerSize-2);
      line(xPos[i], yPos[i], xPos[i+1], yPos[i+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
  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), ",");
      if (serialInArray.length == NUM_OF_VALUES) {
        for (int i=0; i<serialInArray.length; i++) {
          sensorValues[i] = int(serialInArray[i]);
        }
      }
    }
  }
}

void checkAndAppend(){
  if (xPos[amtDigit] != curXPos || yPos[amtDigit] != curYPos){
    xPos = append(xPos, curXPos);
    yPos = append(yPos, curYPos);
    amtDigit++;
  }
}

As a result of the above code:

Exercise 2: Make a musical instrument with Arduino

For exercise 2, we were asked to build an instrument with processing and Arduino.

Circuit Diagram for Buzzer

Using above design, I built circuit and adjusted the code according to the sample code from the class. The resulting code is below:

Arduino:

// IMA NYU Shanghai
// Interaction Lab
/*************************************************
* Public Constants
*************************************************/
/**
This example is to send multiple values from Processing to Arduino.
You can find the Processing example file in the same folder which works with this Arduino file.
Please note that the echo case (when char c is ‘e’ in the getSerialData function below)
checks if Arduino is receiving the correct bytes from the Processing sketch
by sending the values array back to the Processing sketch.
**/

#define NUM_OF_VALUES 2 /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/
//#include “pitches.h”

// notes in the melody:
int melody[] = {
262, 294, 330, 349, 392, 440, 494, 523
};
/*
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
*/

/** 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);
for (int thisNote = 0; thisNote < 8; thisNote++) {

// to calculate the note duration, take one second divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
// stop the tone playing:
noTone(8);
}
}

void loop() {
getSerialData();

// add your code here
// use elements in the values array
// values[0] // values[1] int freq = melody[int(map(values[0], 0, 500, 0, 8))];

if(values[1]){
tone(8, freq);
} else {
noTone(8);
}
}

//recieve serial data from Processing
void getSerialData() {
if (Serial.available()) {
char c = Serial.read();
//switch – case checks the value of the variable in the switch function
//in this case, the char c, then runs one of the cases that fit the value of the variable
//for more information, visit the reference page: https://www.arduino.cc/en/Reference/SwitchCase
switch (c) {
//if the char c from Processing is a number between 0 and 9
case ‘0’…’9′:
//save the value of char c to tempValue
//but simultaneously rearrange the existing values saved in tempValue
//for the digits received through char c to remain coherent
//if this does not make sense and would like to know more, send an email to me!
tempValue = tempValue * 10 + c – ‘0’;
break;
//if the char c from Processing is a comma
//indicating that the following values of char c is for the next element in the values array
case ‘,’:
values[valueIndex] = tempValue;
//reset tempValue value
tempValue = 0;
//increment valuesIndex by 1
valueIndex++;
break;
//if the char c from Processing is character ‘n’
//which signals that it is the end of data
case ‘n’:
//save the tempValue
//this will b the last element in the values array
values[valueIndex] = tempValue;
//reset tempValue and valueIndex values
//to clear out the values array for the next round of readings from Processing
tempValue = 0;
valueIndex = 0;
break;
//if the char c from Processing is character ‘e’
//it is signalling for the Arduino to send Processing the elements saved in the values array
//this case is triggered and processed by the echoSerialData function in the Processing sketch
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;
}
}
}

Processing:

// IMA NYU Shanghai
// Interaction Lab


/**
 * This example is to send multiple values from Processing to Arduino.
 * You can find the arduino example file in the same folder which works with this Processing file.
 * Please note that the echoSerialData function asks Arduino to send the data saved in the values array
 * to check if it is receiving the correct bytes.
 **/


import processing.serial.*;

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


Serial myPort;
String myString;

// This is the array of values you might want to send to Arduino.
int values[] = new int[NUM_OF_VALUES]; // [freq, duration]

int duration = 1;

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

  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[ 5 ], 9600);
  // check the list of the ports,
  // find the port "/dev/cu.usbmodem----" or "/dev/tty.usbmodem----" 
  // and replace PORT_INDEX above with the index 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
  myString = null;
}


void draw() {
  background(0);
  
  //divider
  int x = 0;
  int space = width/8;
  stroke(255);
  strokeWeight(3);
  for(int i = 0; i < 8; i++){
    line(x, 0, x, height);
    x += space;
  }

  // changes the values
  values[0] = pmouseX;
  
  if(mousePressed){
    values[1] = 1;
  } else {
    values[1] = 0;
  }
  
  
  // sends the values to Arduino.
  sendSerialData();

  // This causess the communication to become slow and unstable.
  // You might want to comment this out when everything is ready.
  // The parameter 200 is the frequency of echoing. 
  // The higher this number, the slower the program will be
  // but the higher this number, the more stable it will be.
  echoSerialData(200);
  printArray(values);
}

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) {
  //write character 'e' at the given frequency
  //to request Arduino to send back the values array
  if (frameCount % frequency == 0) myPort.write('e');

  String incomingBytes = "";
  while (myPort.available() > 0) {
    //add on all the characters received from the Arduino to the incomingBytes string
    incomingBytes += char(myPort.read());
  }
  //print what Arduino sent back to Processing
  print( incomingBytes );
}

void keyPressed(){
  if (key == CODED){
    if (keyCode == UP){
      duration++;
    } else if (keyCode == DOWN){
      duration--;
    }
  }
}

As a result of the above code:

Leave a Reply