STAC-Board/EncoderTester/EncoderTester.ino

77 lines
1.5 KiB
Arduino
Raw Normal View History

2023-04-07 01:51:23 +00:00
// define the pins for the rotary encoder
const int pinA = 2;
const int pinB = 3;
const int sw = 4;
// define the current and previous state of the rotary encoder pins
int currA = 0;
int currB = 0;
int prevA = 0;
int prevB = 0;
int prevButton = 1;
int currButton = 0;
// define the current and previous positions of the rotary encoder
int position = 0;
int prevPosition = 0;
void setup() {
// set the pin modes for the rotary encoder
pinMode(pinA, INPUT_PULLUP);
pinMode(pinB, INPUT_PULLUP);
pinMode(sw, INPUT_PULLUP);
// enable pull-up resistors on the rotary encoder pins
// digitalWrite(pinA, HIGH);
// digitalWrite(pinB, HIGH);
// initialize the serial communication
Serial.begin(9600);
}
void loop() {
// read the current state of the rotary encoder
currA = digitalRead(pinA);
currB = digitalRead(pinB);
//read state of button
currButton = digitalRead(sw);
// check if the state of pin A has changed
if (currA != prevA) {
// if pin A has changed, check the state of pin B to determine direction
if (currA == currB) {
// clockwise rotation
position++;
} else {
// counter-clockwise rotation
position--;
}
delay(50);
Serial.println(position);
}
if(currButton == 0 && prevButton == 1){
Serial.println("button press");
delay(20);
}
prevButton = currButton;
// update the previous state and position of the rotary encoder
prevA = currA;
prevB = currB;
prevPosition = position;
}