IR Sensor

ir_sensor.png

A necessary component for any challenge that utilizes walls, analog IR sensors are a staple of Robotathon. This particular sensor is the GP2Y0A21YK0F model.

How it Works

IR distance sensors emit bursts of infrared light towards a surface. The light bounces off objects it hits, and then enters a proximity sensor. The output is then transformed into a voltage (see graph below) that can be read by the ESP32. See this link for more information.

ir_sensor_functionality.png ir_sensor_graph.png

Notice that the sensor will output garbage if the sensor is too close to an object.

Interfacing

There are 3 pins (red, black, white) to the device as seen in the picture, associated to Power, Ground, and Output Signal, respectively. For testing the distance sensor, let’s use pin 12, as the signal pin. Hook up the circuit as follows:

ir_sensor_wiring.png

Note that our IR sensors have reversed cable adapters with incorrect color coding (red actually corresponds to GND, and black actually corresponds to +5V). If you plug the power in backwards, you will fry the sensor!

IR Sensor Pin ESP32 Pin
VIN (cable adapter BLACK) 5V
GND (cable adapter RED) GND
Signal Any ADC Capable Pin

If you’re not sure about the ESP32 pinout, then check out the diagram in this page!

Programming

The following program will allow you to read values from the IR sensor in a loop. After you build and flash the program, you should see the values in your terminal change as you move it towards and away from an object.

#include "sdkconfig.h"
#include <Arduino.h>

#include <ESP32SharpIR.h>

ESP32SharpIR IRSensorName(ESP32SharpIR::GP2Y0A21YK0F, 12);

void setup() {
    Serial.begin(115200);
    IRSensorName.setFilterRate(1.0f);
}
    
void loop() {
    Serial.println(IRSensorName.getDistanceFloat()); 
    delay(100);
}

Extensions

You received values from the sensor, but do they mean anything? The next step for the IR sensor is translating and thresholding it. Take a look at the above graph. There is a strong linear relationship between your signal value and the distance away from the object. It’s your job now to code a function that returns an accurate distance given a voltage input value. After that, your team needs to threshold the data. When do the values become inconsistent (too close or too far)? What do you do with your robot when that happens?