Recitation 8: Serial Communication by Nathalie White

During the recitation, I was only able to complete the first exercise. I will attempt the second in my own time. 

Here is the code I used in Processing:

// For receiving multiple values from Arduino to Processing
int previousx;
int previousy;

import processing.serial.*;

String myString = null;
Serial myPort;


int NUM_OF_VALUES = 2;   
int[] sensorValues;     

void setup() {
  size(500, 500);
  background(255);
  setupSerial();
}


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

 //ellipse (sensorValues[0],sensorValues[1],100,100);
 
 stroke(0);
 line(previousx,previousy, sensorValues[0],sensorValues[1]);
 
 previousx= sensorValues[0];
 previousy= sensorValues[1];
 
}

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 setupSerial() {
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[ 2 ], 9600);
  
  myPort.clear();
  
  myString = myPort.readStringUntil( 10 );  // 10 = '\n'  Linefeed in ASCII
  myString = null;

  sensorValues = new int[NUM_OF_VALUES];
}

Here is the code I used in Arduino:

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);

// print out the value you read:
Serial.print(map(sensorValue1,0, 1023, 0,500));
Serial.print(“,”);
Serial.print(map(sensorValue2,0,1023,0,500));
Serial.println();

delay(1); // delay in between reads for stability
}

This is the result:

It was not very precise. Very hard to draw with. 

Leave a Reply