刚刚领导丢给我一个光栅尺,说这个好用,驱动一下......
第一次见啊,不知道怎么用,先找淘宝商家要资料,就给了产品尺寸图和安装方式,对我一点用处没有,又逛 B 站看了眼工作原理,什么莫尔条纹啥的,还是不知道怎么用,最后查到其实和旋转编码器一样驱动。
随笔记录一下 esp32 驱动增量旋转编码器。
最开始直接摘了一段代码是循环识别判断 AB 相的 IO 来判断的,烧录进去不好用,很丢步,修改了一下把循环判断改成 IO 端口改变的中断触发,效果不错:
#include <Arduino.h>
int aPin = 12;
int bPin = 14;
int buttonPin = 27;
int longPeriod = 0;
// return -1,0,or +1
void IRAM_ATTR getEncoderTurn()
{
static int oldA = LOW;
static int oldB = LOW;
int result = 0;
int newA = digitalRead(aPin);
int newB = digitalRead(bPin);
// int key = digitalRead(buttonPin);
if (newA != oldA || newB != oldB)
{
// something has changed
if (oldA == LOW && newA == HIGH)
result = -(oldB * 2 - 1);
}
// if (!key)
// {
// longPeriod