Experiment 6 : Object Detection using IR Sensor
Description :
IR sensor can be used for obstacle sensing, color detection(between basic contrasting colors), fire detection, line sensing, etc and also as an encoder sensor. In this experiment we use it to detect objects with both Arduino and ESP32.
Contents :
With Arduino
Components Used :
- Arduino UNO
- USB cable A to B
- IR Sensor
- LED Red x 1
- 220Ω resistor x 1
- Breadboard
- Breadboard jumper wires
Circut:
Connections are made according to the Circuit given
Code :
int IRSensor = 7;
int LED = 4;
void setup()
{
pinMode (IRSensor, INPUT); // sensor pin INPUT
pinMode(LED,OUTPUT);
Serial.begin(9600); // open the serial port at 9600 bps:
}
void loop()
{
int statusSensor = digitalRead (IRSensor);
if (statusSensor == 1)
{
Serial.print("No Obstacle/Black Surface\n");
digitalWrite(LED,LOW);
}
else
{
Serial.print("Obstacle Detected/White Surface\n");
digitalWrite(LED,HIGH);
}
}
Video :
The output of this experiment would be like this :
Serial Monitor Output :
With ESP32
Components Used :
- ESP32 board
- USB cable
- IR Sensor
- LED Red x 1
- 220Ω resistor x 1
- Breadboard
- Breadboard jumper wires
Steps :
1 : Create a variable
- Click on Add Variable and create a variable named IR, make it as String.
2 : Code
- In the Sketch section, enter the code and upload it to the ESP32.
#include "thingProperties.h"
#define IRSensor 34
#define LED 4
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
pinMode(IRSensor, INPUT); // sensor pin INPUT
pinMode(LED,OUTPUT);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
ArduinoCloud.update();
int status = digitalRead(IRSensor);
if(status == 1)
{
iR = "No Obstacle/Black Surface";
digitalWrite(LED,LOW);
}
else
{
iR = "Obstacle Detected/White Surface";
digitalWrite(LED,HIGH);
}
}
void onIRChange() {
// Add your code here to act upon IR change
}
3 : Dashboard
- Add a messenger widget to the dashboard with variable as IR.
Circuit :
Working :
For a detailed instruction visit :