I found this (I think) brilliant bit of code for a rotary encoder by John Main.
#define CLK_PIN 2
#define DATA_PIN 7
#define YLED A1
////////////////////////////////////////////////////
void setup() {
pinMode(CLK_PIN,INPUT);
pinMode(DATA_PIN,INPUT);
pinMode(YLED,OUTPUT);
Serial.begin(9600);
Serial.println("Rotary Encoder KY-040");
}
////////////////////////////////////////////////////
void loop() {
static uint16_t state=0,counter=0;
delayMicroseconds(100); // Simulate doing somehing else as well.
state=(state<<1) | digitalRead(CLK_PIN) | 0xe000;
if (state==0xf000){
state=0x0000;
if(digitalRead(DATA_PIN))
counter++;
else
counter--;
Serial.println(counter);
}
}
I modified it a little for my use.
#define CLK_PIN 2
#define DATA_PIN 3
#define SWITCH_PIN 4
int rpm = 0;
//Setup
void setup() {
pinMode(CLK_PIN, INPUT);
pinMode(DATA_PIN, INPUT);
pinMode(SWITCH_PIN, OUTPUT);
Serial.begin(9600);
Serial.println("READY");
}
//
void loop() {
static uint16_t state = 0, counter = 0;
delayMicroseconds(100); // Simulate doing something else as well.
state = (state << 1) | digitalRead(CLK_PIN) | 0xe000; //Digital Debounce Filter
if (state == 0xf000) { //61440
state = 0x0000; //0
if (digitalRead(DATA_PIN))
counter++;
else
counter--;
rpm = counter * 25;
if (rpm > 6000)
rpm = 0;
if (rpm > 500)
rpm = 500;
Serial.println(rpm);
}
}
Lines 31 - 34 are an attempt to constrain the value of 'rpm' to between 0 and 500.
It doesn't work. Well, it sort of works but I need better than 'sort of'.
If I dial it down to 0 and keep going, it does indeed stay on zero. But, it saves those zeros up so if I want to increase the value I have to dial out all of those zeros before the value starts increasing again. ![]()
At the top end, it does the same thing in the opposite direction.
Suggestions please. ![]()