对于我正在进行的项目,我需要将旋转编码器连接到我的Arduino Mega(2560)板。旋转编码器将作为一种非常精确的滚轮来定位我的python代码中的对象。我发现这个Arduino代码非常适合我想要的东西。但是,为了在python中实现编码器读出,我需要“连接”我的输入,我从Arduino板接收到我的Python代码。我试图以某种方式将Arduino代码“转换”为Python代码,并且遇到了 pySerial 和 pyfirmata 的概念,这看起来很有希望。但是,Arduino中的某些函数并未被Python模仿,例如attachInterrupt()
函数或volatile unsigned int
。
我希望有人能指出我将旋转编码器的以下Arduino代码转换为Python代码的正确方向。
// Encoder connect to digitalpin 2 and 3 on the Arduino.
volatile unsigned int counter = 0; //This variable will increase or decrease depending on the rotation of encoder
void setup() {
Serial.begin (9600);
//Setting up interrupt
//A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
attachInterrupt(0, ai0, RISING);
//B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
attachInterrupt(1, ai1, RISING);
}
void loop() {
// Send the value of counter
Serial.println (counter);
}
void ai0() {
// ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
// Check pin 3 to determine the direction
if(digitalRead(3)==LOW) {
counter++;
}else{
counter--;
}
}
void ai1() {
// ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
// Check with pin 2 to determine the direction
if(digitalRead(2)==LOW) {
counter--;
}else{
counter++;
}
}
创建了2014年 作者:Ben-Tommy Eriksen https://github.com/BenTommyE/BenRotaryEncoder
谢谢