Skip to main content

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

Wiring up buttons and switches is simple:

  1. Power (VCC to 5V)
  2. Ground (GND to GND)
  3. Echo to digital pin 8
  4. Trigger to digital pin 7

hcsr04.png

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.h>

#define trigPin  7
#define echoPin 8
#define maxDistance 400

NewPing sonar( trigPin, echoPin, maxDistance);

void setup() {
  Serial.begin( 9600 );
}

void loop() {
  Serial.println( sonar.ping_cm() );
  delay( 100 );
}

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);
  
  String portName = Serial.list()[0];//0
  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 NewPing Library.

We have a tutorial on how to install a library here.