Ultrasonic Sensor

This chapter will show you how to connect a ultrasonic sensor to your Arduino board and read the distance of objects from p5.js / JavaScript.

What is a ultrasonic sensor?

In simple words, a typical ultrasonic sensor has a “loudspeaker” that can emit a signal in an ultrasonic frequency - and a “microphone” that can hear the signal. The sensor measures the time that the signal needs from the moment is was sent to the moment it was received.

The closer an object is to the sensor, the sooner the ultrasonic signal will reflect from it.

Using the utrasonic sensor in p5js

The basic syntax is:

let ultrasonic = connectSensor( SENSOR_ULTRASONIC, {echo:13, trig:12} );

By default, the distance is updated every 150 ms. You can change the update rate by passing the additional option iv when connecting the sensor. Here we are updating the distance every 1000 ms (= once every second).

let ultrasonic = connectSensor( SENSOR_ULTRASONIC, {echo:12, trig:13, iv:1000} );

Hardware

Wiring

Reading distance with an utrasonic sensor in p5js / Javascript

Code

let ultrasonic;

function setup () {
   createCanvas(400, 400);
   ultrasonic = connectSensor( SENSOR_ULTRASONIC, {echo:12, trig:13} );
}

function draw () {
   background( 255 );
   textSize(32);
   text( ultrasonic.value(), 200, 200);
}