/Rotary_Encoder.js Secret
Last active
January 22, 2024 04:07
Rotary_Encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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/ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
arduino nano 與 旋轉編碼器 的基本程式碼,能用serial monitor監測狀態變化