|
在本篇文章中,我们将主要介绍如何在Arduino Uno开发板上使用红外距离传感器。这种传感器还有很多名字:MH传感器系列、KY-033、TCRT5000等。此外,它经常被广告宣传为IR距离传感器、循迹传感器或巡线传感器等。 除了红外距离传感器(IR Distance Sensor)之外,本文还使用了一个“ LCM1602 IIC”的LCD模块,该模块用于显示传感器值。 LCM1602 IIC的主要优点是非常易于使用。例如,可以通过设置I2C连接来进行控制。
所需的材料清单: – Arduino Uno开发板 – 跳线 – 迷你面包板 – MH传感器系列 – LCM1602 IIC V1模块(LCD)
备注:红外距离传感器类型有很多样式,例如KY-033,只有三个引脚。通常,会却是A0引脚。此外,D0引脚通常标记为S。如果您使用这样的模块,本文仍然对您有用。只需忽略与A0引脚相关的部分即可。
连接方式: 红外传感器和LCM1602模块只有四个引脚。两个模块的GND引脚连接到Arduino的GND引脚。VCC引脚连接到Arduino的5V引脚。由于Arduino Uno只有一个5V引脚,因此使用了一个微型面包板来共有5V引脚。接下来,将红外传感器的A0和D0引脚连接到Arduino。 A0引脚是传感器与障碍物之间测得距离的原始模拟值(0-1023)。在本文中,A0连接到Arduino的A0引脚。 D0引脚是数字引脚,如果模拟值大于或等于特定阈值,它将变为高电平状态。该阈值可以通过红外距离传感器的蓝色电位器来调整。本文中,D0连接到Arduino的引脚8。 最后,将LCM1602模块的SDA和SCL引脚连接到Arduino Uno的相应SDA和SCL引脚。
将MH传感器系列和LCM1602 IIC V1连接到Arduino Uno。
示例源代码 - #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // initializes the LCM1602 IIC V1 (LCD module)
- // 0x27 is the I2C address. This address might be different.
- const int IN_A0 = A0; // analog input
- const int IN_D0 = 8; // digital input
- void setup() {
- pinMode (IN_A0, INPUT);
- pinMode (IN_D0, INPUT);
- lcd.begin(16, 2); // begins connection to the LCD module
- lcd.backlight(); // turns on the backlight
- }
- int value_A0;
- bool value_D0;
- void loop() {
- value_A0 = analogRead(IN_A0); // reads the analog input from the IR distance sensor
- value_D0 = digitalRead(IN_D0);// reads the digital input from the IR distance sensor
-
- lcd.setCursor(0, 0); // sets the cursor of the LCD module to the first line
- lcd.print("A0:");
- lcd.setCursor(3, 0); // sets the cursor of the LCD module to the fourth character
- lcd.print(value_A0); // prints analog value on the LCD module
-
- lcd.setCursor(0, 1); // sets the cursor of the LCD module to the first line
- lcd.print("D0:");
- lcd.setCursor(3, 1); // sets the cursor of the LCD module to the fourth character
- lcd.print(value_D0); // prints digital value on the LCD module
-
- delay(1000);
- }
复制代码
编译代码并上传到Arduino Uno开发板,然后LCD模块应显示红外距离传感器和障碍物之间的距离。请记住,距离是由0到1023之间的模拟值指示的。不幸的是,将模拟值转换为长度的公制单位非常困难。原因是所测量的模拟值受障碍物的影响很大。例如,黑色表面反射的光确实比白色表面少。结果,测量的模拟值将有所不同。有趣的是,可以使用此特性来将红外距离传感器用作“黑色或白色”检测器。这种应用通常可以在“小车套件”中找到,在该套件中,多个IR传感器安装在车底下。结果,小车能够循迹在白色地面上绘制的黑线。
下图显示了使用黑白材料进行的距离测量。尽管距离大致相同,但测量的模拟值(A0)仍存在很大差异:
红外距离传感器可测量黑色材料。 模拟传感器的值比测量白色材料时的值高得多(A0 = 949)。
红外距离传感器可测量白色材料。 模拟传感器的值比测量黑色材料时要低得多(A0 = 525)。
|