一、安裝驅動
二、旋轉編碼器
接法如下:
程式碼:#define SERIAL_BAUDRATE 115200
#define CLK_PIN 2 // 定義連接腳位
#define DT_PIN 3
#define SW_PIN 4
#define interruptA 0 // UNO腳位2是interrupt 0,其他板子請見官方網頁
volatile long count = 0;
unsigned long t = 0;
void setup() {
Serial.begin(SERIAL_BAUDRATE);
// 當狀態下降時,代表旋轉編碼器被轉動了
attachInterrupt(interruptA, rotaryEncoderChanged, FALLING);
pinMode(CLK_PIN, INPUT_PULLUP); // 輸入模式並啟用內建上拉電阻
pinMode(DT_PIN, INPUT_PULLUP);
pinMode(SW_PIN, INPUT_PULLUP);
}
void loop() {
if(digitalRead(SW_PIN) == LOW){ // 按下開關,歸零
count = 0;
Serial.println("count reset to 0");
delay(300);
}
}
void rotaryEncoderChanged(){ // when CLK_PIN is FALLING
unsigned long temp = millis();
if(temp - t < 200) // 去彈跳
return;
t = temp;
// DT_PIN的狀態代表正轉或逆轉
count += digitalRead(DT_PIN) == HIGH ? 1 : -1;
Serial.println(count);
}
結果:
import processing.serial.*;
Serial myPort;
void setup()
{size(500, 500);
myPort = new Serial(this,"COM7", 115200);
}
int x=0;
int lf=10;//new line,line feed
void draw()
{background(0);
if (myPort.available() >0) {
String now =myPort.readStringUntil(lf);
x=int(split(now,'\r')[0]);
println(now);
}
ellipse(width/2+x*20,height/2,100,100);
}
沒有留言:
張貼留言