Sharp GP2Y0A21是一颗红外线测距传感器,易于使用,价钱廉宜,且低功耗。 规格如下:
- 距离测量范围:10至80cm(4“到32”)
- 工作电压:4.5V至5.5V
- 输出类型:模拟电压
- 平均功耗:35mA
- 峰值功耗:约200mA
- 允许的最大角度:> 40°
- 更新频率/周期:25 Hz/40毫秒
Sharp GP2Y0A21是一颗非线性(nonlinear)测距传感器,且是非连续性(non-continuity)输出,当距离小于8厘米,传感器将不能正常工作。其测距特性如图所示。
减少噪音
Sharp GP2Y0A21 传感器的输出很不稳定,容易被干扰,最简单的解决方法是将两颗电容并联(100nF的10-100μF)连接VCC和GND之间。 电容必须尽可能靠近电源,如图:
使用Arduino读取Sharp GP2Y0A21的传感值
GP2Y0A21传感器只有三个接脚,VCC、GND和模拟输出(Analog output)。只要将其输出连接至微控制器的模拟输入(Analog input),就能读取传感器读取的值了。这里使用了一个Arduino读取Sharp GP2Y0A21的传感值。
/*
Read values from Sharp GP2Y0A21 distance sensor and output to serial
Sharp Distance Sensor GP2Y0A21 (10-80cm)
3.1V at 10cm to 0.3V at 80cm
*/
int ir_sensor = A0;
void setup() {
//initialize serial communications at 9600 bps
Serial.begin(9600);
}
void loop() {
int sensor_value = analogRead(ir_sensor); //read the sensor value
Serial.println(sensor_value); //print the sensor vlue
delay(500); //delay 500ms (0.5 second)
}
上面提到Sharp GP2Y0A21 传感器的输出很不稳定,在相同情况下读取传感器,你不可能取得全部相同的值,因此必须多次读取传感器,然后取得其平均数。
int ir_sensor = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(value_average(10)); //loop 10 times and get its average
delay(500);
}
int value_average(int average_count) {
int sum = 0;
for (int i=0; i<average_count; i++) {
int sensor_value = analogRead(ir_sensor);
sum = sum + sensor_value;
}
return(sum/average_count);
} Code
Arduino有6个模拟输入,标记为A0到A5,每个模拟输入提供10位的分辨率(即1024个不同的值)。 5V为默认值, 因此读取5V将是1023,2.5V为512,依此类推。以下代码应用了Map函数把传感值转换成电压voltage
int ir_sensor = A0;
void setup() {
//initialize serial communications at 9600 bps
Serial.begin(9600);
}
void loop() {
int sensor_value = analogRead(ir_sensor); //read the sensor value
//convert to voltage ranged from 0V to 5V
int voltage = map(sensor_value, 0, 1023, 0, 5); //0V=0, 2.5V=512, 5V=1023
Serial.println(voltage); //print the sensor vlue
delay(500); //delay 500ms (0.5 second)
}
上面的例子只能显示四组不同的值(电压),即0V,1V,2V,3V。实际情况,你应该Map更大的值,比如 map(sensor_value,0,1023,0,255)
将传感值转换成厘米(cm)
以下方程式是根据Sharp GP2Y0A21 传感器的特性而取得的方程式
int ir_sensor = A0;
void setup() {
//initialize serial communications at 9600 bps
Serial.begin(9600);
}
void loop() {
int sensor_value = analogRead(ir_sensor); //read the sensor value
int distance_cm = pow(3027.4/sensor_value, 1.2134); //convert readings to distance(cm)
Serial.println(distance_cm); //print the sensor value
delay(500); //delay 500ms (0.5 second)
} Code
以下代码读取100次的传感值,然后取得其平均电压
int ir_sensor = A0;
void setup() {
//initialize serial communications at 9600 bps
Serial.begin(9600);
}
void loop() {
int distance = average_value(100); //loop 100 times and get its average
Serial.println(distance); //print the sensor value
delay(500); //delay 500ms (0.5 second)
}
int average_value(int average_count) {
int sum = 0;
for (int i=0; i<average_count; i++) {
int sensor_value = analogRead(ir_sensor); //read the sensor value
int distance_cm = pow(3027.4/sensor_value, 1.2134); //convert readings to distance(cm)
sum = sum + distance_cm;
}
return(sum/average_count);
}