Tutorial #7: Proximity Sensor

Proximity Sensor
(Arduino + Serial + Processing)

Here, we are using an Ultrasonic sensor, which sends out a “ping”, calculating the time it takes to hit an object and come back to the sensor, then converting this value to a distance. We will send this distance value through Serial, which is a way that we can communicate between different software on our computer. Arduino and Processing can’t communicate without signals being sent between one another. Serial will handle this. Processing reads the serial values and then, in our example code, changes the grey background of a square between a value of 0 and 255 based on distance.

Ultrasonic Sensor Ultrasonic Sensor


Here is a basic circuit:

Ultrasonic Sensor Circuit


Arduino Code:

*Note: You may need to install the “New Ping” library.

 * Posted on https://randomnerdtutorials.com
 * created by http://playground.arduino.cc/Code/NewPing

#include <NewPing.h>
#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define MAX_DISTANCE 200

// NewPing setup of pins and maximum distance
void setup() {
void loop() {
   unsigned int distance = sonar.ping_cm();
  // Serial.print(distance);

Processing Code:

// Example by Tom Igoe, edited by Victoria Bradbury

import processing.serial.*;

Serial myPort;  // The serial port

void setup() {
   size(700, 700);  // sets the size of your frame
  // List all the available serial ports
  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[1], 9600);  // change this [0] to the port your usb is connected to

void draw() {
  while (myPort.available() > 0) {
    int inByte = myPort.read();   // casts the byte value coming in through serial into an integer
    println(inByte);              // prints the integer read below
    background(255);             // Set background to white
     fill(inByte*3);                 // set fill to the value of the number of cm away the object is, the value is multiplied *3 to make the effect more obvious in terms of how fast it lightens
     rect(100, 100, 500, 500);   // sets the size and placement of the rectangle



Proximity sensors are useful for interactive installation because they allow you to calculate the distance that a viewer is standing from your work and to make something happen as they approach or walk away. Once this is implemented, the possibilities are endless! Also consider what else we can do with these values once they come into Processing. Here, we are using them to change a grey value, but they could also represent a time-code in an audio clip or a video.