Well the solution works but it does have one tiny flaw: It uses delay!
In this case, with a 72 ms delay you're able to get away with it, but I'll show you how to do the same without delay by using the Automaton framework.
First I start with a basic sketch and define some Automaton objects: an encoder, two leds and a button. I call the Automaton scheduler from the loop() function.
#include <Automaton.h>
Atm_encoder encoder;
Atm_led led_up, led_down;
Atm_button button;
void setup() {
Serial.begin( 9600 );
}
void loop() {
automaton.run();
}
Now it's time to initialize the led and button components in setup().
led_up.begin( 4 ) // Led on pin 4
.blink( 72, 0, 1 );
led_down.begin( 5 ) // Led on pin 5
.blink( 72, 0, 1 );
button.begin( 18 ) // Encoder button on pin 18
.onPress( [] ( int idx, int v, int up ) {
Serial.println( "Button press" );
});
Both leds are setup to give a single (1) pulse of 72 ms when triggered.
The button uses a lambda expression (more about this in the Automaton Introduction page).
The only thing left is to make the encoder object trigger the led objects whenever the shaft rotates CW (up) of CCW (down), also in setup():
encoder.begin( 2, 3 ) // Encoder on pins 2 & 3
.onChange( ATM_UP, led_up, led_up.EVT_BLINK )
.onChange( ATM_DOWN, led_down, led_down.EVT_BLINK );
That's all. Whenever the encoder moves it triggers one of the led pulses. The button thing just works in parallel. No delay() was used in this sketch and everything remains fully responsive even if the pulses are changed to 7200 ms.
Automaton is an event based framework, therefore the syntax and program flow are different from what you're used to seeing here. It is very well suited to any Arduino sketch that uses combinations of delays and asynchronous inputs.
If the syntax and logic of this sketch seem strange to you there's a short introduction on the project's Github wiki that explains the concepts and syntax.
encoder_pulse.ino (602 Bytes)