sto cercando di far funzionare decentemente un encoder tipo questo:
collegnadolo ad un arduino uno usando gli interrupt esterni disponibili sui pin 2 e 3.
Ho scritto questo codice:
- Codice: Seleziona tutto
#define SW_PIN 2
#define CLK_PIN 3
#define DRCT_PIN 4
volatile int encoder_count = 0;
volatile boolean state;
boolean last_state;
void button_handler ()
{
state = !state;
Serial.println ();
Serial.println ("Ora inverto senso rotazione.");
}
void encoder_handler ()
{
static unsigned long last_encoder_time;
unsigned long encoder_time = millis();
if ((encoder_time - last_encoder_time) > 300) {
state = !state;
if (digitalRead (DRCT_PIN)) {
encoder_count ++;
}
else {
encoder_count --;
}
last_encoder_time = encoder_time;
}
}
void setup() {
pinMode (SW_PIN, INPUT);
pinMode (CLK_PIN, INPUT);
pinMode (DRCT_PIN, INPUT);
attachInterrupt (0, button_handler, FALLING); // encoder SW_PIN.
attachInterrupt (1, encoder_handler, FALLING); // encoder CLK_PIN.
Serial.begin (9600);
}
void loop() {
if (state != last_state) {
Serial.print (encoder_count);
Serial.print (" ");
}
last_state = state;
}
con l' idea di incremetare la variabile encoder_count quando ruoto in un senso e decrementarla quando ruoto nell' altro.
Ho provato anche a variare il tempo di debounce ma i risultati non mi sembrano un gran che.
Questo è cio che ottengo ruotando abbastanza lentamente l' encoder:
1 1 3 3 4 5 4 3 2 3 4 6 7 7 6 5 6 5 6 8 7 8 10 12 11 12 11
Ora inverto senso rotazione.
11 10 9 8 9 8 9 8 7 4 3 2 3 2 3 2 1 1 0 -1
Ora inverto senso rotazione.
-1 1 2 3 2 2 3 4 3 2 3 2 1 0 -1 0 1 2 4 3 4 4 4 3 4 5 6 7 7 6 7 6 7 8
Sono tutto orecchie.