#define _CW 120
#define _CCW 180
#define DIR_PIN 2
#define STEP_PIN 3
uint8_t newByte = 0;
uint8_t lastByte = 0;
uint8_t checkByte = 0;
int16_t count = 0;
bool X10 = false;
void setup() {
Serial.begin(115200);
Serial.println("Click once on RE up or down");
Serial.println("Then use page up/down to operate");
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(4, INPUT_PULLUP);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
}
void loop() {
newByte = (digitalRead(11) << 1) | digitalRead(10);
if (newByte != lastByte) {
(checkByte <<= 2) += newByte;
lastByte = newByte;
newByte = 0;
}
if (checkByte == _CW) { //0b 01 11 10 00
digitalWrite(DIR_PIN, HIGH);
if (X10) {
count += 10;
for (int i = 0; i < 10; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000);
}
Serial.print(" CW ");
Serial.println(count);
} else {
count ++;
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000);
digitalWrite(STEP_PIN, LOW);
Serial.print(" CW ");
Serial.println(count);
}
checkByte = 0;
}
if (checkByte == _CCW) { //0b 10 11 01 00
digitalWrite(DIR_PIN, LOW);
if (X10) {
count -= 10;
for (int i = 0; i < 10; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000);
}
Serial.print("CCW ");
Serial.println(count);
} else {
count --;
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000);
digitalWrite(STEP_PIN, LOW);
Serial.print("CCW ");
Serial.println(count);
}
checkByte = 0;
}
if (digitalRead(4)) X10 = 1;
else X10 = 0;
}
START THE SIM.
CLICK ONCE ON R.ENC UP OR DOWN
THEN USE PAGE UP/DOWN KEYS TO OPERATE
LONG PRESS SPEEDS THE ENCODER
REPEAT IF x1/x10 SWITCH IS USED
x1 or x10