/* ** Rotary Encoder Example ** Use the Sparkfun Rotary Encoder to vary brightness of LED ** ** Sample the encoder at 200Hz using the millis() function */ int brightness = 120; // how bright the LED is, start at half brightness int fadeAmount = 10; // how many points to fade the LED by unsigned long currentTime; unsigned long loopTime; const int pin_0 = 0; // first rotary encoder pin const int pin_1 = 1; // second rotary encoder pin const int pin_2 = 2; // button const int LED = 3; // pin 3, which is PWM capable unsigned char encoder_A; unsigned char encoder_B; unsigned char button = 1; // button is high when not pressed unsigned char prev_button; unsigned char encoder_A_prev=0; void setup() { // declare LED to be an output: pinMode(pin_0, INPUT); pinMode(pin_1, INPUT); pinMode(pin_2, INPUT_PULLUP); pinMode(LED, OUTPUT); currentTime = millis(); loopTime = currentTime; prev_button = !digitalRead(pin_2); // set initial state Serial.begin(57600); Serial.setTimeout(25); } void button_changed() { if (!button) { // pressed Serial.println("d"); // button pushed down } else { Serial.println("u"); // button let up } prev_button = button; // toggle for next time } void knob_rotated() { // A has gone from high to low if(encoder_B) { // B is high so clockwise // increase the brightness, dont go over 255 if(brightness + fadeAmount <= 255) { // max brightness += fadeAmount; } Serial.println("+"); // clockwise } else { // B is low so counter-clockwise // decrease the brightness, dont go below 0 if (brightness - fadeAmount >= 0) { // min brightness -= fadeAmount; } Serial.println("-"); // counter-clockwise } //Serial.println("Brightness: "+String(brightness)); } void loop() { // get the current elapsed time currentTime = millis(); if(currentTime >= (loopTime + 5)){ // 5ms since last check of encoder = 200Hz encoder_A = digitalRead(pin_0); // Read encoder pins encoder_B = digitalRead(pin_1); button = digitalRead(pin_2); if (button != prev_button) { // button changed state button_changed(); } if((!encoder_A) && (encoder_A_prev)){ // A has gone from high to low knob_rotated(); } encoder_A_prev = encoder_A; // Store value of A for next time // set the brightness of pin 9: analogWrite(LED, brightness); loopTime = currentTime; // Updates loopTime } }