2024年1月21日 星期日

ARDUINO nano + 旋轉編碼器控制

材料清單

  • Arduino Nano/Uno
  • 旋轉編碼器
  • 麵包板和連接線

硬件連接

將旋轉編碼器連接到Arduino Nano:
  • CLK接到PIN2
  • DT接到PIN3
  • SW接到PIN4
  • 正極(+)接到VCC
  • 負極(GND)接到GND

程式編寫

#define SERIAL_BAUDRATE 9600
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define interruptA 0 // nano腳位2是interrupt 0,其他板子請見官方網頁
int count = 0;
int lastCLK = 0; //lastCLK 為旋轉編碼器 CLK 預設狀態 =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
int clkValue = digitalRead(CLK_PIN);
int dtValue = digitalRead(DT_PIN);
if (lastCLK != clkValue)
{
lastCLK = clkValue;
count += (clkValue != dtValue ? 1 : -1); //旋轉編碼器順時針旋轉時,count +1;逆時針旋轉時, count -1
Serial.print("count:");
Serial.println(count);
}
}
/*
參考資料:
1.葉難 https://yehnan.blogspot.com/2014/02/arduino.html
2.Ray https://sites.google.com/view/rayarduino/rotary-encoder
3.CH.Tseng https://chtseng.wordpress.com/2015/12/25/
*/

在程式編寫部分,我們參考了葉難(*1) 和Ray (*2) 的網站。葉難的旋轉編碼器在按鈕功能上表現良好,但在旋轉時數值變動較不穩定。相比之下,Ray的旋轉編碼器數值變動較為穩定,但其按鈕操作較為不順暢。因此,我們結合了兩者的優點,改寫了一段基本的程式碼。這段程式碼能夠在串行監視器(serial monitor)中監測到旋轉編碼器的順時針與逆時針旋轉數值變化,以及按鈕按下時count歸零的現象。

應用展望

若程式能夠順利運作,我們就可以將此功能擴展應用於需要同時監測數值變化和按鈕操作的其他儀器上。

參考資料

  1. 葉難. "Arduino練習:旋轉編碼器" https://yehnan.blogspot.com/, 2014年2月.
  2. Ray. "旋轉編碼器." https://sites.google.com/view/rayarduino/,  2023年3月.
  3. CH.Tseng. "Arduino – 中斷功能" https://chtseng.wordpress.com/, 2015年12月25日.


沒有留言:

張貼留言