Example Code for Arduino-Detect Object Presence
Detect the status of IO4 and print it in serial port. Users will learn how to interface the Digital IR Proximity Sensor with Arduino, read its digital output, and use serial communication for status monitoring.
Hardware Preparation
| Name | Model/SKU | Quantity | Purchase Link |
|---|---|---|---|
| DFRduino UNO R3 (or similar) | DFR0009 | 1 | DFRduino UNO R3 |
| Digital IR Proximity Sensor(0-200cm) | SEN0381 | 1 | Digital IR Proximity Sensor(0-200cm) |
Software Preparation
Wiring Diagram

Sensor Detection Distance Adjustment
The sensor will start to work when powered on. Place an object of size 80x60cm at the 80cm(or smaller) in front of the sensor, adjust its detection distance as shown below:
Press down the button, the red LED indicator begins to flash, then it enters auto detection distance adjustment mode.

Sample Code
/*!
* @File infraredApproachSensor.ino
* @brief Detect the status of IO4 and print it in serial port
* @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
* @licence The MIT License (MIT)
* @author [liunian]([email protected])
* @version V1.0
* @date 2020-08-20
*/
int OUT = 4;
int i = 0;
void setup()
{
Serial.begin(9600);
pinMode(OUT, INPUT);
}
void loop()
{
i = digitalRead (OUT);
Serial.println(i);
delay(5);
}
Result
Read the status of IO4. When the sensor detected an object, serial print 1, otherwise, print 0.

Was this article helpful?
