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 12
  4. Trigger to digital pin 13

HCSR04.png

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

// Initialize sensor that uses digital pins 13 and 12.
UltraSonicDistanceSensor distanceSensor(13, 12);  

void setup () {
    Serial.begin(9600);  // We initialize serial connection so that we could print values from sensor.
}

void loop () {
    // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters.
    Serial.println(distanceSensor.measureDistanceCm());
    delay(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 HCSR04 Library by Martin Sosic.

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