How to send data to Processing from Arduino
What is the Serial Communication?
Serial communication is the process of sending data one bit at a time, sequentially, over a communication channel or computer bus. Simply put, serial communication is the communication between two or more computers with binary data.
In this tutorial, we will use serial communication protocol to send data to Processing from Arduino. The Processing sketch will be controlled by the physical component, the ultrasonic sensor, which can be replaced with other sensors, button and etc.
Wiring
- Power (VCC to 5V)
- Ground (GND to GND)
- Echo to digital pin
812 - Trigger to digital pin
713
Additionally in this diagram there is a LED attached to digital pin 13 for the getting started example code, however this isn't required for other projects.
Arduino Code
This example sends the distance measured from Arduino to Processing via the serial port, you can read the data from the serial monitor.
#include <NewPing.HCSR04.h>
#define// trigPinInitialize 7sensor #definethat echoPinuses 8digital #definepins maxDistance13 400and NewPing12.
sonar(UltraSonicDistanceSensor trigPin,distanceSensor(13, echoPin, maxDistance)12);
void setup(setup () {
Serial.begin(9600); 9600// );We initialize serial connection so that we could print values from sensor.
}
void loop(loop () {
// Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters.
Serial.println( sonar.ping_cm(distanceSensor.measureDistanceCm() );
delay( 100 )500);
}
Processing Code
This example used the data received from Arduino to control the degrees of rotation of a rectangle in Processing.
import processing.serial.*;
Serial myPort;
String val;
int datanum = 0; //number of data receiving from Arduino
int value1;
//int value2; //multiple data from arduino if needed
void setup() {
size(800, 800);
printArray(Serial.list()); //show all ports
String portName = Serial.list()[0];//choose the correct port
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void draw() {
background(0);
pushMatrix();
rotate(map(value1,0, 400, 0, PI/2 ));
rect(120, 80, 220, 220);
popMatrix();
}
void serialEvent( Serial myPort){
val = myPort.readStringUntil('\n');
if (val != null)
{
val = trim(val);
int[] vals = int(splitTokens(val, ","));
if(vals.length >= datanum){
value1 = vals[0];
//multiple data from arduino if needed
//value2 = vals[1] ;
print(value1);
}
}
}
To use this code you will need the NewPingHCSR04 Library. by Martin Sosic.
We have a tutorial on how to install a library here.