Arduino开发之GP2Y0A21 Distance Sensor

时间:2024-04-02 17:20:56
环境搭建:
1. Arduino UNO R3开发板,
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
2. Arduino IDE。
我这里使用的是1.8.3。可以在https://www.arduino.cc/en/Main/Software下载并安装。
安装好之后,桌面会有如下图标。
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
示例开发:
1.连接设备。
本例中我们以GP2Y0A21 Distance Sensor并结合DFR0021-R为例,基于Arduino Uno R3和Arduino IDE开发。
DFR0021-R的引脚和Arduino Uno开发板的连接方式如下,
DFR0021-R
GP2Y0A21
Arduino Uno R3
VCC
VCC
3.3V
GND
GND
GND
信号引脚
信号引脚
DFR0021接数字引脚8,GP2Y0A21
接模拟引脚A0
2. 编码。
连接好之后,用数据线连接Arduino开发板和电脑。同时打开Arduino IDE。输入下述代码。
#define inPin A0
#define ledPin 8
#define IR_RANGE 250

void setup ()
{
Serial.begin (9600);

pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inPin, INPUT); // declare distance sensor as input
}

void loop ()
{
Serial.print("Reading the distance value...\n");
uint16_t value = analogRead (inPin);
Serial.print(value, DEC);
Serial.println(" \n");
uint16_t range = read_gp2y0a21 (value);
Serial.print("The distance value range is ...\n");
Serial.print(range);
Serial.println(" mm \n");
if (range > IR_RANGE) // check if the range is larger than defined range
{
digitalWrite(ledPin, HIGH); // turn LED ON
Serial.print("LED is On...\n");
}
else
{
digitalWrite(ledPin, LOW); // turn LED OFF
Serial.print("LED is Off...\n");
}
Serial.println ();
delay (1000);
}

//return distance (mm)
uint16_t read_gp2y0a21 (uint16_t value)
{
if (value < 20)
value = 20;
return ((67870.0 / (value - 3.0)) - 40.0);
}
然后保存文件。
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
选择Arduino Uno开发板。
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
编译上传大到开发板。
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
3.运行。
选择COM口信息,
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
然后选择端口监视工具,查看程序运行信息。
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
串口监视信息,
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
备注:上面的数据就是当前Distance Sensor的值和Red LED 的当前状态(ON表示开,OFF表示关)。此例中,当测到的值大于2.5厘米时,LED灯就会亮。

整体运行界面:
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor
实际效果图:
Arduino开发之GP2Y0A21 Distance Sensor
Arduino开发之GP2Y0A21 Distance Sensor