Exercise 18 - Connecting an ultrasonic sensor

1.      INTRODUCTION

This module has two ultrasonic transducers, which work together. The sensor has three terminals, two to energize (Vcc and GND) and two to control the digital interface:

·         Trigger: Receive a pulse from Arduino. This pulse indicates to sensor that the measure can start.

·         Echo: The module shows to Arduino a proportional pulse which width is proportional to the sound travel time measure.


To obtain the distance in distance units (cm), the sound travel time (in microseconds) must be divided between a constant 58.


2.      HOW TO CONNECT?

Materials:

·         Arduino UNO board

·         Protoboard

·         Some wire Jumpers

·         Ultrasonic sensor

Connect this sensor is simple. Vcc and GND go to 5V and GND pins respectively. Trigger and echo are connected to pin12 and pin11.

EXERCISE_A (Testing the sensor) 




3.      PROGRAMMING

This program tests the ultrasonic sensor and show distances Serial monitor. To use this module is necessary to install NewPing library you can install the library like in CONNECTING_A_LCD_(I2C)_SCREEN.

#include <NewPing.h>//Include newping library in this sketch

 

/*CONFIGURE SENSOR PINS*/

#define TRIGGER_PIN  12

#define ECHO_PIN     11

#define MAX_DISTANCE 200

 

//Creates class NewPing object

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 

void setup(){

  Serial.begin(9600);

}

 

Loop part obtains the pulse value and calculate the distance in cm with a constant, also print it in serial monitor.

 

void loop(){

  // Waits 1 second to do measures

  delay(1000);

  // obtains sound travel time measure and store the value in uS

  int uS=sonar.ping_median();

  // Print "distance" to serial monitor

  Serial.print("Distancia: ");

  // Calculate the distance with a constant base

  Serial.print(uS/US_ROUNDTRIP_CM);

  Serial.println("cm");

}


Last modified: Tuesday, 21 January 2020, 10:30 AM