|
本帖最后由 pww999 于 2014-3-14 21:53 编辑
跟据 supercctv 也谈Arduino与旋转编码器的两种连接方式(中断方式,普通D口)
http://www.geek-workshop.com/thread-595-1-1.html
这种方式为 使用1个中断口和1个普通D口 实现 中断 计数 ,(中断A相,用D端口 读取B相 +或—,同时计数),测试通过,
在某种场合时或许能用上
#include "Wire.h"
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); //set the LCD address to 0x27 for a 16 chars and 2 line display
// -----------
#define PinA 2 //中断0
const int encoderPinB = 5; //用D5 读取B相 +或—,同时计数
unsigned long time = 0;
long count = 0; //计数值
long num = 0;
//初始化
void setup()
{
lcd.init();
lcd.backlight();
delay(20);
lcd.setCursor(0, 0);
lcd.print("pww999");
// -----------
pinMode(PinA,INPUT); //D2脚为输入
attachInterrupt(0, blinkA, LOW); //注册中断0调用函数blinkA
pinMode(encoderPinB, INPUT);
digitalWrite(encoderPinB, HIGH);
time = millis(); //时间初值
}
void loop()
{
while (num != count)
{
num = count;
// Serial.println(num);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("pww999");
lcd.setCursor(0, 1);
lcd.print(num);
}
}
//中断0调用函数
void blinkA()
{
if ((millis() - time) > 3) //防抖动处理
{
if (digitalRead(encoderPinB) == HIGH) //读取D5
{
count ++;
}
else
{
count --;
}
}
time = millis();
} |
|