/*
Forum: https://forum.arduino.cc/t/help-with-using-1-encoder-to-set-2-values/1227169/4
Wokwi: https://wokwi.com/projects/390444791965276161
*/
// -----
// SimplePollRotatorLCD.ino - Example for the RotaryEncoder library.
// This class is implemented for use with the Arduino environment.
// Copyright (c) by Matthias Hertel, http://www.mathertel.de
// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
// More information on: http://www.mathertel.de/Arduino
// -----
// 18.01.2014 created by Matthias Hertel
// -----
// This example checks the state of the rotary encoder in the loop() function.
// The current position is printed on output when changed.
// Hardware setup:
// Attach a rotary encoder with output pins to A2 and A3.
// The common contact should be attached to ground.
#include <Wire.h>
#include <LiquidCrystal.h>
#include <RotaryEncoder.h>
LiquidCrystal lcd(12, 13, 7, 6, 5, 8);
RotaryEncoder encoder(A2, A3);
#define selectSW1 9
int currentStateSW1;
static int pos = 0;
int newPos = 0;
static int pos1 = 0;
int newPos1 = 0;
// setPos changes between 1 and 2 depending on whether line1() or line2() is called
byte setPos = 0;
void setup() {
pinMode(selectSW1, INPUT_PULLUP);
lcd.begin(16, 2);
lcd.print("Dual Value 1Enc");
delay(2000);
lcd.clear();
printPos(pos,0);
printPos(pos1,1);
// You may have to modify the next 2 lines if using other pins than A2 and A3
PCICR |= (1 << PCIE1); // This enables Pin Change Interrupt 1 that covers the Analog input pins or Port C.
PCMSK1 |= (1 << PCINT10) | (1 << PCINT11); // This enables the interrupt for pin 2 and 3 of Port C.
} // setup()
// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3: exactly where we need to check.
ISR(PCINT1_vect) {
encoder.tick(); // just call tick() to check the state.
} // ISR
// Read the current position of the encoder and print out when changed.
void loop() {
currentStateSW1 = digitalRead(selectSW1);
if (currentStateSW1 == 1) {
lcd.setCursor(15, 1);
lcd.print(" ");
lcd.setCursor(15, 0);
lcd.print((char)127); // (char)127 = ASCII <-
Line1();
}
else {
lcd.setCursor(15, 0);
lcd.print(" ");
lcd.setCursor(15, 1);
lcd.print((char)127); // (char)127 = ASCII <-
Line2();
}
} // loop ()
/**** Print 1st setting on Line1 ***/
void Line1() {
if (setPos != 1){
setPos = 1;
encoder.setPosition(pos);
}
newPos = encoder.getPosition();
if (pos != newPos) {
printPos(newPos,0);
pos = newPos;
}
} //Line1 ()
/**** Print 2nd setting on Line2 ***/
void Line2() {
if (setPos != 2){
setPos = 2;
encoder.setPosition(pos1);
}
newPos1 = encoder.getPosition();
if (pos1 != newPos1) {
printPos(newPos1,1);
pos1 = newPos1;
}
} //Line2 ()
void printPos(int aPos, byte Row){
lcd.setCursor(0, Row);
lcd.print(" ");
lcd.setCursor(0, Row);
lcd.print(aPos);
}