|
在本篇文章中,我们将学习如何在Arduino开发板上使用旋转编码器。我们将以带符号的数字同时显示顺时针和逆时针方向的编码值。
所需的组件 ● Arduino UNO开发板 ● 旋转编码器 ● 1602 LCD显示屏 ● 连接电线 ● 面包板
旋转编码器 旋转编码器(Rotary Encoder),也称为轴编码器,是一种机电设备,可将轴或轴的角位置或运动转换为模拟或数字输出信号。旋转编码器有两种主要类型:绝对式和增量式。绝对值编码器的输出指示当前轴位置,从而使其成为角度传感器。增量编码器的输出提供有关轴运动的信息,通常将其所在位置处理为位置、速度和距离等信息。
连接电路图 下面的电路图简单演示了如何在Arduino上使用旋转编码器。在面包板或PCB上组装电路。
旋转编码器如何工作? 编码器具有一个磁盘,该磁盘具有均匀分布的接触区,这些接触区连接到公共引脚C和两个其他单独的接触引脚A和B,如下所示。
当磁盘逐步开始旋转时,引脚A和B将开始与公共引脚接触,因此将产生两个方波输出信号。
如果仅对信号的脉冲进行计数,则可以使用两个输出中的任何一个来确定旋转位置。但是,如果我们也要确定旋转方向,则需要同时考虑两个信号。
我们可以注意到,两个输出信号彼此之间相差90度。如果编码器顺时针旋转,则输出A将在输出B之前。
因此,如果我们每次计算信号从高到低或从低到高变化的步数,我们就会注意到两个输出信号的值相反。反之亦然,如果编码器逆时针旋转,则输出信号具有相等的值。因此,考虑到这一点,我们可以轻松地对控制器进行编程以读取编码器的位置和旋转方向。
源代码/程序 - #include <LiquidCrystal.h>
- LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
- #define outputA 6
- #define outputB 7
- int counter = 0;
- int aState;
- int aLastState;
- void setup() {
- pinMode (outputA,INPUT);
- pinMode (outputB,INPUT);
- Serial.begin (9600);
- lcd.begin(16,2);
- // Reads the initial state of the outputA
- aLastState = digitalRead(outputA);
- }
- void loop() {
- aState = digitalRead(outputA); // Reads the "current" state of the outputA
- // If the previous and the current state of the outputA are different, that means a Pulse has occured
- if (aState != aLastState){
- // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
- if (digitalRead(outputB) != aState) {
- counter ++;
- lcd.clear();
- } else {
- counter --;
- lcd.clear();
- }
- Serial.print("Position: ");
- Serial.println(counter);
- lcd.setCursor(0, 0);
- lcd.print("Position: ");
- lcd.setCursor(10, 0);
- lcd.print(counter);
- }
- aLastState = aState; // Updates the previous state of the outputA with the current state
- }
复制代码
|