This is the code I can get to work.
Rotary encoder part:
// Rotary encoder variables
const byte inputCLK = 3; // Arduino pin the rotary encoder CLK pin is connected to.
const byte inputDT = 2; // Arduino pin the rotary encoder DT pin is connected to.
int currentStateCLK; // Current state of rotary encoder pin CLK. Used to identify rotation.
int previousStateCLK; // Current state of rotary encoder pin CLK. Used to identify rotation.
boolean encCCW; // Flag that the encoder has been rotated counter-clockwise one step.
boolean encCW; // Flag that the encoder has been rotated clockwise one step.
void setup() {
// Set encoder and push button pins as inputs.
pinMode (inputCLK, INPUT);
pinMode (inputDT, INPUT);
encCCW = 0; // Initial state for rotation flag not rotated.
encCW = 0; // Initial state for rotation flag not rotated.
// Read initial state of rotary encoder CLK pin. Assign to previousStateCLK so we can check for state changes when the loop begins.
previousStateCLK = digitalRead(inputCLK);
// Setup Serial Monitor
Serial.begin (9600);
}
void loop() {
//This code must go at the start of the loop.
// Read the current state of inputCLK so we can compare it.
currentStateCLK = digitalRead(inputCLK);
// Rotary encoder code.
if (currentStateCLK != previousStateCLK) { // If the previous and the current state of inputCLK are different, then the encoder and been rotated.
if (currentStateCLK != digitalRead(inputDT)) { // If the inputCLK state is different than the inputDT state then the rotation is counterclockwise.
encCCW = 1; // set rotation flag high.
}
else {
// Encoder is not rotating CCW
encCW = 1;
}
}
//This is the middle of the loop. Do stuff with encCCW and encCW here.
// Serial print that the encoder has been rotated.
if (encCCW == 1) {
Serial.println("Counter-clockwise");
}
if (encCW == 1) {
Serial.println("Clockwise");
}
//This code must go at the end of the loop to reset the encoder variables for the next time around.
previousStateCLK = currentStateCLK; // Update previousStateCLK with the current state
encCCW = 0; // Reset encCCW.
encCW = 0; // Reset encCW.
}
I just tested my basic button code and it's not working
I must have screwed something up, as it was working before! I'll get back to you!