Totally hashed together proof of concept using parts I have that probably won’t do you any good
Using the simple three pin rotary encoder on my Diyode CodeShield that is mounted to my Arduino Mega testbench. It is using two analog pins as if they were normal GPIO becasue all the other pins on the shield are used.
This is NOT the complete sketch, but just what I added to an existing testbench to see how it worked… A bit imprecise in motion detection, but otherwise not to bad considering the low end encoder and how many other tasks are running at same time on my testbench.
You will get better results Googling for a proper library to read your encoder with.
/*
Diyode Codeshield Rotary Encoder - Uses Port Manipulation
ENCODER_A 54 (A0) for MEGA - Use 14 (A0) for Uno
ENCODER_B 55 (A1) for MEGA - Use 15 (A1) for Uno
ENCODER_PORT PINF - use PINC for Uno
*/
#define ENCODER_A 54
#define ENCODER_B 55
#define ENCODER_PORT PINF
static uint8_t rotCounter = 128; // Start in the middle of the slider - This variable will be changed by encoder input
int lastRotValue;
In setup…
/* Setup encoder pins as inputs */
pinMode(ENCODER_A, INPUT);
digitalWrite(ENCODER_A, HIGH);
pinMode(ENCODER_B, INPUT);
digitalWrite(ENCODER_B, HIGH);
timer.setInterval(10L, RotEncoder); // Scan rotary encoder pins
Main code…
void RotEncoder()
{
int8_t tmpdata;
tmpdata = read_encoder();
if (tmpdata) {
rotCounter += tmpdata;
Blynk.virtualWrite(vPin, rotCounter); // Sync to Slider Widget
Blynk.syncVirtual(vPin); // Process Slider state change
}
}
/* returns change in encoder state (-1,0,1) */
int8_t read_encoder()
{
static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
old_AB <<= 2; //remember previous state
old_AB |= ( ENCODER_PORT & 0x03 ); //add current state
return ( enc_states[( old_AB & 0x0f )]);
}
BLYNK_WRITE(vPin) { // Slider Widget set to 0-255
rotCounter = param.asInt(); // Synced from Slider Widget
// Control stuff with the slider here
}