Adding Rotary encoder and a button to arduino

This is from my latest project arduino-controlled-bass-treble-volume-and-input-selector. I only created a separate thread for the rotary encoder and button part just in case you only needed that part on your project.

Rotary encoder is just a replacement of up and down button with a turning single knob. This is practically helpful especially when you need to vary large range of values. For example if your volume value ranges from 0-100 then it will be a pain to push the button 100 times to get from 0 to 100 and vice versa.

Circuit




Arduino Code:

// define encoder pins
const int up_sw       = 12; // up
const int down_sw = 13; // down
const int mode_sw =  5;    // mode switch

int n = LOW;
int debounce_ctr = 0;
int reset_ctr = 0;
bool up = false;
bool down = false;

void setup() {
pinMode(mode_sw, INPUT);
pinMode(up_sw, INPUT);
pinMode(down_sw, INPUT);
}

 

void loop() {

debounce:
if(digitalRead(mode_sw))  //Read Mode switch
{
delay(1);
reset_ctr = 0;
debounce_ctr++;
if(debounce_ctr > 150)
{
debounce_ctr = 0;
modebuttonState = true; //
} else {
goto debounce;
}
}

//Rotary Encoder
n = digitalRead(up_sw);
if ((encoder0PinALast == LOW) && (n == HIGH))
{
if (digitalRead(down_sw) == LOW) {
up = true;
reset_ctr = 0;
} else {
down = true;
reset_ctr = 0;
}
}
encoder0PinALast = n;

// Read the sate of the buttons

if(up) //rotary encoder up
{
//Your code here
up = false;//do not remove – reset the flag
}

if(down) //rotary encoder down
{
//Your code here
down = false;//do not remove – reset the flag
}

if(modebuttonState) //Button clicked
{
//Your code here
modebuttonState = false; //do not remove – reset the flag
}

 

}