ESP32 With Ultrasonic Sensor
by Fernando Koyanagi in Circuits > Microcontrollers
36586 Views, 10 Favorites, 0 Comments
ESP32 With Ultrasonic Sensor
Today, we are going to create a reverse sensor simulator, the kind that is used in cars. For this, we will make an assembly that uses the ESP32, a buzzer, four indicator LEDs, and an ultrasonic sensor, plus a 4-digit display (with 7 segments).
So, let's read the ultrasonic sensor and play with the distance on the display. As the distance reaches a "dangerous" space, the LEDs gradually light up from blue to green, yellow, and finally red, according to the shortening of the distance. An alarm goes off when reaching the space limit.
WiFi NodeMCU-32S ESP-WROOM-32
Display
As for the display, in this assembly, we show how to use the I2C, which enables the sending of vast information by only two wires.
Ultrasonic Sensor
We explained that the HC-SR04, the most common ultrasonic sensor and widely used with Arduino, is cheap and easy to find. Remember the minimum distance that it can measure is from 2 inches away, and the maximum is 4 meters. Another detail is that 5 volts power it.
Continuous Buzzer
LEDs
There are 4 colored LEDs with 220 ohms resistors.
Assembly
The principal details of the HC-SR 04 is that it has power and uses two pins, the trigger and the Echo, which appear in the source code.
Libraries
In this assembly, we used two libraries: TM1637Display and Ultrasonic. The PDF file contains the links to download both, on: http://www.fernandok.com/2017/12/sensor-ultrassonico-com-esp32.html
Source Code
In this part, you can see a demonstration about the operation of the project. Already in the code, we declare TM1637Display and Ultrasonic, with a reading range of 250 milliseconds. This was the chosen time to avoid extremely fast number changes. Next, we define the pins used for the LEDs and the buzzer. I declare yet another variable, the "unsigned int", which will save the distance of the device.
//Biblioteca responsável para comunicação com o display de 7 segmentos
#include <tm1637display.h> //Carrega a biblioteca do sensor ultrassonico #include < ultrasonic.h> #define INTERVALO_LEITURA 250 //(ms) //definição dos PINOS que utilizaremos para os LEDS e o BUZZER #define PIN_BLUE_LED 16 #define PIN_GREEN_LED 17 #define PIN_YELLOW_LED 18 #define PIN_RED_LED 19 #define PIN_BUZZER 21 //variável responsável por armazenar a distância lida pelo sensor ultrassônico unsigned int distancia = 0;
Sensor and Display
In this step, we define the pins and the constructors of the objects that we use to control the ultrasonic sensor and the display.
//conexão dos pinos para o sensor ultrasonico
#define PIN_TRIGGER 4 #define PIN_ECHO 5 //Inicializa o sensor nos pinos definidos acima Ultrasonic ultrasonic(PIN_TRIGGER, PIN_ECHO); // Module connection pins (Digital Pins) #define CLK 14 #define DIO 13 //Inicializa o display nos pinos definidos acima TM1637Display display(CLK, DIO);
Setup
In this function, we initialize the serial with a speed of 9600, configure the pins, and then configure the brightness for the display.
void setup()
{ Serial.begin(9600); configurarPinos(); //configura o brilho do display com valor máximo display.setBrightness(0x0a); Serial.println("Setup..."); }
Pin Configuration
Here, we set both the four LEDs and the buzzer as pinMode, all OUTPUT, because they are outputs.
/*
CONFIGURA O MODOS DE CADA UM DOS PINOS QUE UTILIZAREMOS COMO SAIDA */ void configurarPinos() { pinMode(PIN_BLUE_LED, OUTPUT); pinMode(PIN_GREEN_LED, OUTPUT); pinMode(PIN_YELLOW_LED, OUTPUT); pinMode(PIN_RED_LED, OUTPUT); pinMode(PIN_BUZZER, OUTPUT); }
Loop
In the Loop function, we have the distance and delay check, that is, the reading interval.
void loop()
{ verificarDistancia(); delay(INTERVALO_LEITURA); }
Get Distance
Now, we are going to read the current distance calculated by the sensor.
/*
FAZ A LEITURA DA DISTANCIA ATUAL CALCULADA PELO SENSOR */ int getDistance() { //faz a leitura das informacoes do sensor (em cm) int distanciaCM; long microsec = ultrasonic.timing(); // pode ser um float ex: 20,42 cm se declarar a var float distanciaCM = ultrasonic.convert(microsec, Ultrasonic::CM); return distanciaCM; }
Check Distance
We check the distance that will be shown on the 4-digit display. Then, we erase the 4 LEDs and silence the buzzer. This type of situation can be used in many applications.
/*
VERIFICA A DISTANCIA ATUAL QUE O SENSOR ULTRASONIC ESTA LENDO E EM SEGUIDA, IMPRIME O VALOR NO DISPLAY, E ACENDE O LED CORRESPONDENTE */ void verificarDistancia() { //recupera a distância atual lida pelo sensor distancia = getDistance(); //imprime no display o valor lido display.showNumberDec(distancia); //esse FOR tem como objetivo apagar todos os LEDS que estejam acesos. for(int i=PIN_BLUE_LED; i<=PIN_RED_LED; i++) { digitalWrite(i, LOW); } //desliga o BUZZER digitalWrite(PIN_BUZZER, LOW); //caso a distancia lida seja menor ou igual a 5, tomaremos como uma distância de perigo //então acenderemos o LED VERMELHO e ligaremos o BUZZER if( distancia <= 5 ) { digitalWrite(PIN_RED_LED, HIGH); digitalWrite(PIN_BUZZER, HIGH); } //caso a distancia seja maior que 5 e menor ou igual a 20, //tomaremos como uma distância de atenção, e ligaremos o LED AMARELO else if(distancia <=20) { digitalWrite(PIN_YELLOW_LED, HIGH); } //caso a distancia seja maior que 20 e menor ou igual a 40, //tomaremos como uma distância segura, e ligaremos o LED VERDE else if(distancia <= 40) { digitalWrite(PIN_GREEN_LED, HIGH); } //para distâncias maiores que 40, tomaremos como uma distância sem perigo //acenderemos o LED AZUL para indicar else { digitalWrite(PIN_BLUE_LED, HIGH); } }