This week we are going to try to send our sensor data to Processing by using “Serial Communication”.
To download and learn more about processing, visit www.processing.cc
Below code will print “Hello World” in your serial monitor every 1000ms.
void setup() { Serial.begin(9600); //declare serial port } void loop() { Serial.println("Hello World!"); //send "Hello World!" message to serial port delay(1000); //wait for 1000 ms. }
Use the code below for Processing. This code will print “Hello World” in Processing message panel.
import processing.serial.*; //import serial library Serial myPort; // create object from Serial class String val; // string received from the serial port void setup() { // I know my port is #3 // On Windows machines, this generally opens COM1. // Open whatever port is the one you're using. //You can print out available port list by doing this: printArray(Serial.list()); String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port myPort = new Serial(this, portName, 9600); } void draw() { if ( myPort.available() > 0) { // If data is available, val = myPort.readStringUntil('\n'); // read it until end of the line and store it in val } println(val); //print it out in the console }
Use this code to send binary values to Processing
void setup() { Serial.begin(9600); } void loop() { int analogValue = analogRead(A0); // read the sensor value analogValue = map(analogValue, 0, 1023, 0, 255); // map sensor values to between 0 - 255 Serial.write(analogValue); // send the value serially as a binary value }
Use this code to draw your sensor values as a chart on Processing
import processing.serial.*; Serial myPort; // at the top of the program: float xPos = 0; // horizontal position of the graph float yPos = 0; // vertical position of the graph void setup () { size(800, 600); // window size // List all the available serial ports printArray(Serial.list()); // change the number below to match your port: String portName = Serial.list()[3]; myPort = new Serial(this, portName, 9600); background(#081640); } void serialEvent (Serial myPort) { // get the byte: int inByte = myPort.read(); // print it: println(inByte); yPos = height - inByte; } void draw () { // draw the line in a pretty color: stroke(#A8D9A7); line(xPos, height, xPos, yPos); // at the edge of the screen, go back to the beginning: if (xPos >= width) { xPos = 0; // clear the screen by resetting the background: background(#081640); } else { // increment the horizontal position for the next reading: xPos++; } }