#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define ENCODER_A_PIN 2
#define ENCODER_B_PIN 3
#define ENCODER_Z_PIN 5
#define ZLED_PIN 4
#define INC_PIN 6
#define LATCH_PIN 10
#define INVLATCH_PIN 11
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust I2C address as necessary
volatile int counter = 0;
volatile bool updateCounter = false;
void setup()
{
pinMode(ENCODER_A_PIN, INPUT_PULLUP);
pinMode(ENCODER_B_PIN, INPUT_PULLUP);
pinMode(ENCODER_Z_PIN, INPUT_PULLUP);//
pinMode(ZLED_PIN, OUTPUT);
pinMode(INC_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
pinMode(INVLATCH_PIN, OUTPUT);
lcd.begin(0,10,8);
lcd.backlight();
lcd.print("ENCODER POSITION ");
attachInterrupt(digitalPinToInterrupt(ENCODER_A_PIN), encoderA, RISING);
attachInterrupt(digitalPinToInterrupt(ENCODER_B_PIN), encoderB, RISING);
attachInterrupt(digitalPinToInterrupt(ENCODER_Z_PIN), encoderZ, RISING);
}
void loop()
{
if (updateCounter)
{
updateCounter = false;
// Display the counter value
lcd.setCursor(6, 1);
lcd.print(" "); // Clear previous value
lcd.setCursor(6, 1);
lcd.print(counter);
// Set output pins based on counter
// if (counter == 358) {
if (counter == 10)
{
digitalWrite(LATCH_PIN, HIGH);
digitalWrite(INVLATCH_PIN, LOW);
delay(104); // Pulse width
digitalWrite(LATCH_PIN, LOW);
digitalWrite(INVLATCH_PIN, HIGH);
}
else
{
digitalWrite(LATCH_PIN, LOW);
digitalWrite(INVLATCH_PIN, HIGH);
}
}
}
void encoderA()
{
// A leads B
if (digitalRead(ENCODER_B_PIN) == HIGH)
{
counter++;
// if (counter > 360) counter = 360; // Limit to maximum
if (counter > 15) counter = 15; // Limit to maximum
updateCounter = true;
}
}
void encoderB()
{
// B leads A
if (digitalRead(ENCODER_A_PIN) == HIGH)
{
counter--;
if (counter < 0) counter = 0; // Limit to minimum
updateCounter = true;
}
}
void encoderZ()
{
//if (digitalRead(ENCODER_Z_PIN) == HIGH)
//if (digitalRead(ENCODER_Z_PIN) == LOW )
{
// Reset counter on Z pulse
// counter = 0; // Reset counter
digitalWrite(ZLED_PIN, HIGH);
digitalWrite(INC_PIN, HIGH);
delay(104); // Pulse width
digitalWrite(ZLED_PIN, LOW);
digitalWrite(INC_PIN, LOW);
counter = 0; // Reset counter
updateCounter = true;
}
}