#include <Arduino.h>
#include <LiquidCrystal_I2C.h>
#define outputA 6
#define outputB 5
LiquidCrystal_I2C lcd(0x27, 20, 4);
int aState;
int aLastState;
// -----------------------------------------------------------------------------
// constants
long pwm = 11;
const int PinCLK = 2 ; // Used for generating interrupts using CLK signal
const int PinDT = 35; // Used for reading DT signal
const int PinSW = 33; // Used for the push button switch
//MULTIPLEXER
int s0 = 7;
int s1 = 8;
int s2 = 9;
int s3 = 10;
int muxCh = 0;
// -----------------------------------------------------------------------------
// global vars
volatile int virtualPosition = 0;
// -----------------------------------------------------------------------------
// forward decls
// -----------------------------------------------------------------------------
// Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK
void isr () {
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 > 5) {
if (!digitalRead(PinDT))
virtualPosition = (virtualPosition + 1);
else
virtualPosition = virtualPosition - 1;
}
lastInterruptTime = interruptTime;
} // ISR
// -----------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
aLastState = digitalRead(outputA);
attachInterrupt(0, isr, FALLING); // interrupt 0 is always connected to pin 2 on Arduino UNO
Serial.println("Start");
pinMode(pwm, OUTPUT);
pinMode(PinCLK,INPUT);
pinMode(PinDT, INPUT);
pinMode(PinSW, INPUT);
pinMode(outputA, INPUT);
pinMode(outputB, INPUT);
pinMode(s0, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);
digitalWrite(s0, HIGH);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
digitalWrite(s3, HIGH);
} // setup
// -----------------------------------------------------------------------------
void loop() {
int lastCount = 0;
aState = digitalRead(outputA);
if (aState != aLastState){
if (digitalRead(outputB) != aState) {
virtualPosition ++;
} else {
virtualPosition --;
}
while (true) {
if(virtualPosition < 0) {virtualPosition = 0;}
if(virtualPosition > 100) {virtualPosition = 100;}
if (!(digitalRead(PinSW))) { // check if pushbutton is pressed
virtualPosition = 0; // if YES, then reset counter to ZERO
while (!digitalRead(PinSW)) {} // wait til switch is released
delay(10); // debounce
Serial.println("Reset"); // Using the word RESET instead of COUNT here to find out a buggy encoder
}
if (virtualPosition != lastCount) {
lastCount = virtualPosition;
Serial.print("Count = ");
Serial.println(virtualPosition);
lcd.setCursor(0, 0);
lcd.print("DutyCycle = ");
lcd.print(virtualPosition);
lcd.print("% (");
}
} // while
} //loop
}Loading
cd74hc4067
cd74hc4067