// Used for generating interrupts using CLK signal
const int PinA = 6;
// Used for reading DT signal
const int PinB = 7;
// Used for the push button switch
const int PinSW = 5;
// Simple PWM LED pin
//#define PinLED 11
// Keep track of last rotary value
int lastCount = 50;
// Updated by the ISR (Interrupt Service Routine)
volatile static int virtualPosition = 50;
volatile unsigned long lastInterruptTime = 0;
// ------------------------------------------------------------------
// INTERRUPT INTERRUPT INTERRUPT INTERRUPT INTERRUPT
// ------------------------------------------------------------------
void isrPinA()
{
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
// If interrupts come faster than 5ms, assume it's a bounce and ignore
if (interruptTime - lastInterruptTime > 20)
{
if (digitalRead(PinA) == LOW)
{
virtualPosition++;
Serial.println("A low");
if (digitalRead(PinB) == LOW)
{
Serial.println("B low");
}
else
{
Serial.println("B high");
}
}
else
{
virtualPosition--;
Serial.println("A high");
if (digitalRead(PinB) == LOW)
{
Serial.println("B low");
}
else
{
Serial.println("B high");
}
}
// Restrict value from 0 to +100
//virtualPosition = min(100, max(0, virtualPosition));
}
// Keep track of when we were here last (no more than every 5ms)
lastInterruptTime = interruptTime;
}
// ------------------------------------------------------------------
// SETUP SETUP SETUP SETUP SETUP SETUP SETUP
// ------------------------------------------------------------------
void setup()
{
// Just whilst we debug, view output on serial monitor
//Serial.begin(9600);
//Serial.begin(38400);
Serial.begin(115200);
// Rotary pulses are INPUTs
pinMode(PinA, INPUT_PULLUP);
pinMode(PinB, INPUT_PULLUP);
// Switch is floating so use the in-built PULLUP so we don't need a resistor
pinMode(PinSW, INPUT_PULLUP);
// Attach the routine to service the interrupts
attachInterrupt(digitalPinToInterrupt(PinA), isrPinA, CHANGE);
// Ready to go!
Serial.println("Start");
}
// ------------------------------------------------------------------
// MAIN LOOP MAIN LOOP MAIN LOOP MAIN LOOP MAIN LOOP
// ------------------------------------------------------------------
void loop()
{
// Is someone pressing the rotary switch?
if ((!digitalRead(PinSW)))
{
virtualPosition = 50;
while (!digitalRead(PinSW))
{
delayMicroseconds(10000);
}
Serial.println("Reset");
}
// If the current rotary switch position has changed then update everything
if (virtualPosition != lastCount)
{
// Our LED gets brighter or dimmer
//analogWrite(PinLED, virtualPosition);
// Write out to serial monitor the value and direction
//Serial.print(virtualPosition > lastCount ? "Up :" : "Down:");
//Serial.println(virtualPosition);
Serial.println("----one cw click ----");
// Keep track of this new value
lastCount = virtualPosition ;
}
}