Example Code for Arduino-IR Sensor
Last revision 2025/12/31
Use this code to read the IR sensor distance.
The codes of the IR sensors should be used in Mega ADK.
Hardware Preparation
- Main controller: Arduino Mega ADK/2560
- Five Sharp GP2D12 infrared sensors
- GMR board
- Switch system
Software Preparation
- Development tool: Arduino IDE 1.0.x or higher
Wiring Diagram


Other Preparation Work
-
Insert the Mega and Nano on the GMR board, connect the output of the switch system to the power supply of the motor controller and the GMR board.

-
Turn off the switch.
-
Connect the circuits as the connection diagram , connect the IR sensors.
-
You may test it use another microcontroller (Arduino Uno), then move the codes to the Mega ADK.
-
The codes of the IR sensors should be used in Mega ADK. The communication between Nano and Mega ADK is I2C.
Sample Code
/********************** IR sensor ***********************/
void IRreader()//detect distance on both sides
{
static float IRdata[IrNumber] = {
80,80,80,80,80 };
for(int h=0;h<IrNumber-2;h++)
{
float volts = analogRead(h + 1);
_iR[h] = (6787 / (volts - 3)) - 4;
if(_iR[h]<10) _iR[h] = 80;
_iR[h] = min(_iR[h],80);
_iR[h] = max(_iR[h],12);
}
for(int h=5;h<7;h++)
{
float volts = analogRead(h-4);
_iR[h] = (6787 / (volts - 3)) - 4;
if(_iR[h]<10) _iR[h] = 80;
_iR[h] = min(_iR[h],80);
_iR[h] = max(_iR[h],12);
}
for(int h = 0 ; h < 5 ; h++)
{
_iR[h] = smooth(_iR[h],0.9,IRdata[h]);
IRdata[h] = _iR[h];
}
}
float smooth(float newdata, float filterVal, float smoothedVal)
{
if (filterVal > 1)
filterVal = .99;
else if (filterVal <= 0)
filterVal = 0;
smoothedVal = (newdata * (1 - filterVal)) + (smoothedVal * filterVal);
return smoothedVal;
}
Result
Test the IR sensors using the example code.
Was this article helpful?
