Serial Communication
Although I was not present during this week’s observation, I choose to use the serial communication workshop with Young as a baseline of learning. I choose this workshop because I wanted to use past examples my work to further understand how I can use serial communication in the future. Alongside the workshop slides by Eszter and Jessica, I found both workshops to be very helpful by scanning through their notes and slides online.
Example of Serial Communication Using the Map Function
Because there is not a specific exercise involved with this workshop, I’ve chosen to properly showcase the mapping skills I’ve used throughout this class through the image tint I previously worked on. The code for the image tinting is as follows:
My Code
Arduino
int a;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensor1 = analogRead(A0);
Serial.write(sensor1);
int a = map(sensor1, 0, 1023, 0 , 255);
Serial.write(a);
// Serial.print(sensor1);
// Serial.println();
// too fast communication might cause some latency in Processing
// this delay resolves the issue.
delay(10);
}
Processing
import processing.serial.*;
PImage img;
Serial myPort;
int valueFromArduino;
int sensor1;
void setup() {
size(600, 600);
img = loadImage("HK.jpeg");
imageMode(CENTER);
background(255);
printArray(Serial.list());
myPort = new Serial(this, Serial.list()[16], 9600);
}
void draw() {
if (img.width > 0) {
image(img, 300, 300, width, height);
//float a = map(sensor1, 0, 1023, 0, 600);
while ( myPort.available() > 0) {
valueFromArduino = myPort.read();
}
println(valueFromArduino);//This prints out the values from Arduino
}
if ( valueFromArduino > 150) {
tint(0, 0, 255, 150);
image(img, 250, 0);
}
else if (valueFromArduino < 149) {
tint(0, 255, 0);
}
}
Video example
Through this code, I created a mapping value in the Arduino code of “int a = map(sensor1, 0, 1023, 0 , 255)” and by doing so, I correlated the “int a” value with the values of sensor 1 (potentiometer). The reasoning for this was to create the lowest possible and highest possible values within the potentiometer in the second and third slots of the mapping. In the third and fourth slots I wrote in my lowest target value and highest target value. I also wrote in Sensor 1 so that all of the value in slots 1-4 would correlate with it. Through serial communication, these mapped out values were transferred to processing. The corresponding lines of code in processing were represented by “if ( valueFromArduino > 150) { tint(0, 0, 255, 150); image(img, 250, 0); } else if (valueFromArduino < 149) { tint(0, 255, 0);” These values of 0-255 were the original target values I created in my map on Arduino. And thus by printing “println(valueFromArduino)” it was then possible to correlate the two programs to work together.