rotary encoder increment value by one

This seems like it should be really simple (and maybe it is)!

I’m trying to use a rotary encoder to set a value, and I need to be able to increment it by 1.

I realise an rotary encoder has 4 state changes for every ‘notch’, but surely this is still possible?

I’ve tried a few variations of checking to see if newPosition is equal to oldPosition+4 before incrementing another value, but i just cant get it to work.

I’m using the Encoder Library as it seems simple and efficient.

#include <Encoder.h>

Encoder myEnc(0, 2);
// avoid using pins with LEDs attached

void setup() {
Serial.begin(115200);
Serial.println(“Basic Encoder Test:”);
}

long oldPosition = -999;

void loop() {
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
Serial.println(newPosition);
}
}

You can divide the number of increments by 4.

Of course! thank you.

So here is the final code.

I want to use the rotary to set a value that begins at 55, and to update the LCD quickly.

Is there anything wrong with this?

(it seems to work, but I’m not sure if I’ve done anything ‘bad’ here)

#include <Encoder.h>
#include <LiquidCrystal_I2C.h>

#define D1 5 // LCD SCL
#define D2 4 // LCD SDA
#define D3 0 // Encoder CLK
#define D4 2 // Encoder DT

int oldPosition;
int newPosition;
int Setpoint=55;
long runtime = 0;

Encoder myEnc(D3, D4);
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
lcd.begin(20,4);
lcd.init();
lcd.backlight();
attachInterrupt(2, encoder, CHANGE);
}

void loop()
{

}

void encoder()
{
newPosition = (myEnc.read()/4);
if (newPosition > oldPosition)
{
oldPosition = newPosition;
Setpoint++;
updateLCDencoder()
}
else if (newPosition < oldPosition)
{
oldPosition = newPosition;
Setpoint–;
updateLCDencoder()
}
}

void updateLCDencoder()
{
if ((runtime+250) < millis()) // only print every 250ms
{
runtime = millis();
lcd.setCursor(0,2);
lcd.print("Set: "); lcd.print(Setpoint,1);lcd.print((char)223);lcd.print(“C”);
}
}