风筝
发表于: 2020-4-14 21:27:57 | 显示全部楼层

在本篇文章中,我们将学习如何在Arduino开发板上使用旋转编码器。我们将以带符号的数字同时显示顺时针和逆时针方向的编码值。

Rotary-Enccoder-Arduino-LCD.jpg


所需的组件

●    Arduino UNO开发板

●    旋转编码器

●    1602 LCD显示屏

●    连接电线

●    面包板


旋转编码器

旋转编码器(Rotary Encoder),也称为轴编码器,是一种机电设备,可将轴或轴的角位置或运动转换为模拟或数字输出信号。旋转编码器有两种主要类型:绝对式和增量式。绝对值编码器的输出指示当前轴位置,从而使其成为角度传感器。增量编码器的输出提供有关轴运动的信息,通常将其所在位置处理为位置、速度和距离等信息。

Rotary-Encoder.png


连接电路图

下面的电路图简单演示了如何在Arduino上使用旋转编码器。在面包板或PCB上组装电路。

Circuit-Diagram-Rotary-Encoder-with-Arduino.jpg


旋转编码器如何工作?

编码器具有一个磁盘,该磁盘具有均匀分布的接触区,这些接触区连接到公共引脚C和两个其他单独的接触引脚A和B,如下所示。

Rotary-Encoder-Working.png


当磁盘逐步开始旋转时,引脚A和B将开始与公共引脚接触,因此将产生两个方波输出信号。


如果仅对信号的脉冲进行计数,则可以使用两个输出中的任何一个来确定旋转位置。但是,如果我们也要确定旋转方向,则需要同时考虑两个信号。

Rotary-Encoder-Pulse-Waveform.png


我们可以注意到,两个输出信号彼此之间相差90度。如果编码器顺时针旋转,则输出A将在输出B之前。


因此,如果我们每次计算信号从高到低或从低到高变化的步数,我们就会注意到两个输出信号的值相反。反之亦然,如果编码器逆时针旋转,则输出信号具有相等的值。因此,考虑到这一点,我们可以轻松地对控制器进行编程以读取编码器的位置和旋转方向。


源代码/程序

  1. #include <LiquidCrystal.h>
  2. LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
  3. #define outputA 6
  4. #define outputB 7

  5. int counter = 0;
  6. int aState;
  7. int aLastState;

  8. void setup() {
  9. pinMode (outputA,INPUT);
  10. pinMode (outputB,INPUT);

  11. Serial.begin (9600);
  12. lcd.begin(16,2);
  13. // Reads the initial state of the outputA
  14. aLastState = digitalRead(outputA);

  15. }

  16. void loop() {
  17. aState = digitalRead(outputA); // Reads the "current" state of the outputA
  18. // If the previous and the current state of the outputA are different, that means a Pulse has occured
  19. if (aState != aLastState){
  20. // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
  21. if (digitalRead(outputB) != aState) {
  22. counter ++;
  23. lcd.clear();
  24. } else {
  25. counter --;
  26. lcd.clear();
  27. }
  28. Serial.print("Position: ");
  29. Serial.println(counter);
  30. lcd.setCursor(0, 0);
  31. lcd.print("Position: ");
  32. lcd.setCursor(10, 0);
  33. lcd.print(counter);

  34. }
  35. aLastState = aState; // Updates the previous state of the outputA with the current state

  36. }
复制代码

跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1479



手机版|

GMT+8, 2024-3-29 17:17 , Processed in 0.166881 second(s), 7 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表