Skip to content

Instantly share code, notes, and snippets.

@mikkoelo
Last active April 16, 2019 13:49
Show Gist options
  • Save mikkoelo/3c750bc7fead41f7d68c403a5030744e to your computer and use it in GitHub Desktop.
Save mikkoelo/3c750bc7fead41f7d68c403a5030744e to your computer and use it in GitHub Desktop.
/*
* This sketch is made for communicating between Arduino and Processing using Serial communication.
* Mikko Eloholma, Mehackit (CC BY-SA 4.0)
*
* 1. Connect a sensor to Arduino's analog port and print the values using Serial.
* 2. Run this program once Arduino is sending the data already.
* 3. The ellipse in the middle of the canvas should react to the sensor-data.
* 4. Change the colors of the sketch and use the data for some other purpose!
*/
// Import Serial-library to Procsesing
import processing.serial.*;
// Create a Serial-object 'myPort' and integer variable 'num'.
// myPort is the port for serial communication and num is the variable that will store the sensor value.
Serial myPort;
int num;
void setup() {
// Create a 600 x 600 canvas.
size(600, 600);
// Set the speed of the program. As a default, draw is executed 60 times in a second. Now it's 10 000 times in a second.
// With a lower framerate, Processing might react to sensor values toos slowly. You can try different values.
frameRate(10000);
// Create a String variable 'portName' and save the name of the available Serial port to it.
String portName = Serial.list()[0];
// Print the name of the serial port.
println(portName);
// Save the available Serial port to myPort. The speed is set to 9600 bits/second (same as in Arduino IDE).
myPort = new Serial(this, portName, 9600);
// Set the initial value of num to 0.
num = 0;
}
void draw() {
// Set the background color to black. You can edit the parameters!
background(0, 0, 0);
// Make sure that Serial port is available.
// If it is, read data until line break ("\n") and save this data as a String to a variable 'val'.
if (myPort.available() > 0) {
String val = myPort.readStringUntil('\n');
// If there is any data (the value is not null).
if (val != null) {
// try/catch-structure tries to transform the String to an integer.
// If that's not possible, the reason is probably that there's a space or some non-integer symbol in the String.
// In these cases, an error message is avoided beforehand in the catch-part.
try{
// Remove spaces from the String.
val = trim(val);
// Transform the String to an integer and save it to the variable 'num'.
num = Integer.parseInt(val);
}
catch(NumberFormatException npe){
}
}
// If the value is null, set it to 100.
else {
num = 100;
}
}
// Draw an ellipse to the center of the canvas.
// The width and height of the ellipse change according to the sensor value.
ellipse(width/2, height/2, num, num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment