1
2
3
4
5
6
7
8
9
10int volume = 0;
11int currentStateCLK;
12int lastStateCLK;
13unsigned long lastButtonPress = 0;
14
15void setup() {
16
17 pinMode(CLK,INPUT);
18 pinMode(DT,INPUT);
19 pinMode(SW, INPUT_PULLUP);
20
21
22 lastStateCLK = digitalRead(CLK); //CLK value
23}
24
25void loop() {
26
27 currentStateCLK = digitalRead(CLK); //CLK current value
28
29 if (currentStateCLK != lastStateCLK && currentStateCLK == 1){ //CLK change && CLK only 1state change
30
31 if (digitalRead(DT) != currentStateCLK) { //Encoder CCW Rotation
32 Consumer.write(MEDIA_VOLUME_UP); //Volume Up
33 volume++;
34 delay(2);
35
36 } else { // Encoder CW Rotation
37 Consumer.write(MEDIA_VOLUME_DOWN); //Volume Down
38 volume--
39
40 delay(2);
41 }
42
43 }
44
45 lastStateCLK = currentStateCLK; // Last CLK Value
46
47 int btnState = digitalRead(SW); // Button Value
48
49 if (btnState == LOW) { // Switch pushed
50
51 if (millis() - lastButtonPress > 50) { // Over 50ms
52 Consumer.write(MEDIA_VOLUME_MUTE);
53 }
54 lastButtonPress = millis();
55 }
56
57 delay(1); // Push swithc delay
58}