For last week’s recitation, i attended the serial communication and map workshop. Both sessions was really helpful in helping me further understand how those functions work. In the map workshop, the instructor explained how the map function works. It has 5 items, the name of the value that you want to change, the bottom limit of the original value, the top limit of the original value, the bottom limit of the mapped value, and the top limit of the mapped value. They also provide examples of how to use it.
For serial communications, the instructor showed some examples of how to send values from processing to Arduino and vice versa. As an excercise, we made a circle in which the color of the circle is determined by the value that we got from arduino. The fill itself will be randomized. The position of the X coordinate will also be affected by the value from processing. The whole code looks like this:
// 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 **/
void setup() {
size(500, 500);
background(0);
setupSerial();
}
void draw() {
updateSerial();
printArray(sensorValues);
background(0);
float posx= map (sensorValues[0],0,1023,0,255);
ellipse(posx,mouseY,50,50);
if (sensorValues[1]==1){
fill(random(255));
}
// use the values like this!
// sensorValues[0]
// add your code
//
}
void setupSerial() {
printArray(Serial.list());
myPort = new Serial(this, Serial.list()[ 3], 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]);
}
}
}
}
}