/
main.cpp
90 lines (69 loc) · 1.95 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Rotary Encoder Demo
Demonstrates operation of Rotary Encoder
Displays results on Serial Monitor
Modified for Bodnar BBI-32 encoders by cahamo from DroneBot Workshop 2019 code: https://dronebotworkshop.com
*/
#include <Arduino.h>
// Rotary Encoder Inputs
#define inputS1 4
#define inputS2 5
#define inputKEY 3
// LED Outputs
#define ledCW 8
#define ledCCW 9
#define ledKEY 10
int counter = 0;
int currentStateS1;
int previousStateS1;
String encdir ="";
void setup() {
// Set encoder pins as inputs
pinMode(inputS1,INPUT);
pinMode(inputS2,INPUT);
pinMode(inputKEY,INPUT);
// Set LED pins as outputs
pinMode(ledCW,OUTPUT);
pinMode(ledCCW,OUTPUT);
pinMode(ledKEY, OUTPUT);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of inputS1
// Assign to previousStateS1 variable
previousStateS1 = digitalRead(inputS1);
}
void loop() {
// Check for switch being pressed: switch goes LOW when pressed
if (digitalRead(inputKEY) == LOW) {
Serial.println("Switch pressed");
digitalWrite(ledKEY, HIGH);
}
else {
digitalWrite(ledKEY, LOW);
}
// Read the current state of inputS1
currentStateS1 = digitalRead(inputS1);
// If the previous and the current state of the inputS1 are different then a pulse has occured
if (currentStateS1 != previousStateS1) {
// If the inputS2 state is different than the inputS1 state then
// the encoder is rotating counterclockwise
if (digitalRead(inputS2) != currentStateS1) {
counter --;
encdir ="CCW";
digitalWrite(ledCW, LOW);
digitalWrite(ledCCW, HIGH);
} else {
// Encoder is rotating clockwise
counter ++;
encdir ="CW";
digitalWrite(ledCW, HIGH);
digitalWrite(ledCCW, LOW);
}
Serial.print("Direction: ");
Serial.print(encdir);
Serial.print(" -- Value: ");
Serial.println(counter);
}
// Update previousStateS1 with the current state
previousStateS1 = currentStateS1;
}