notes on using infrared (IR) break-beam sensors with Arduino

Infrared (IR) break-beam sensors are widely used in various applications, including object detection and counting systems. These sensors operate by emitting an infrared beam from a transmitter to a receiver; when an object interrupts this beam, the sensor detects the obstruction. Integrating IR break-beam sensors with microcontrollers like Arduino enhances their functionality, enabling real-time monitoring and control. This post provides a guide on interfacing IR break-beam sensors with an Arduino board. A sample Arduino sketch that demonstrates how to set up the sensor and utilize its readings to control an LED and output status messages via the serial monitor is exemplified. The code initializes the sensor pin with an internal pull-up resistor and continuously monitors the sensor's state to detect beam interruptions.

Example


Materials

- Arduino UNO
- USB cable
- infrared (IR) break-beam sensors
- breadboard
- wires

Setup


Sketch

/*
IR Breakbeam sensor demo!
*/
#define LEDPIN 13
#define SENSORPIN 4
// variables will change:
int sensorState = 0, lastState=0;//variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(LEDPIN, OUTPUT);
// initialize the sensor pin as an input:
pinMode(SENSORPIN, INPUT_PULLUP);
digitalWrite(SENSORPIN, HIGH); // turn on the pullup
Serial.begin(9600);
}

void loop(){
// read the state of the pushbutton value:
sensorState = digitalRead(SENSORPIN);
// check if the sensor beam is broken
// if it is, the sensorState is LOW:
if (sensorState == LOW) {
// turn LED on:
digitalWrite(LEDPIN, HIGH);
}
else {
// turn LED off:
digitalWrite(LEDPIN, LOW);
}
if (sensorState && !lastState) {
Serial.println("Unbroken");
}
if (!sensorState && lastState) {
Serial.println("Broken");
}
lastState = sensorState;
}

Comments