/* Working out a quadrature encoder routine for ATtiny44 Encoder Signals A [Pin 12] & B [Pin 11] trigger ISRs Forward = Clockwise controlled by H-bridge motor controller L298N [later: TB6612] Enable starts/stops the motor controller adding some false trigger recon'ing by a boolean var A_next Motor runs back and forth several times with fixed number of steps to figure out mistakes in routine No absolute positioning or init routine ATM */ const byte interrupt_A = 1; // Int 1 at Pin 12 const byte interrupt_B = 2; // Int 2 at Pin 11 const byte direction_pin = 5; // can be any I/O pin you like const byte enable = 6; // can be any I/O pin you like byte forward = true; // for TB6612 a different method is required volatile uint16_t steps = 255;// max. 65535 steps volatile uint16_t stepsToGo = steps; // init the countdown var volatile byte A_next = true; //the start is somewhat a guessing game. Will get better with init routine void setup() { pinMode( direction_pin, OUTPUT); pinMode( enable, OUTPUT); pinMode(interrupt_A, INPUT_PULLUP); pinMode(interrupt_B, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interrupt_A), ISR_A, CHANGE); attachInterrupt(digitalPinToInterrupt(interrupt_B), ISR_B, CHANGE); digitalWrite(direction_pin, forward); // set direction pin high/low on H-bridge motor controller digitalWrite(enable, LOW); // start with motor OFF } void loop() { if(stepsToGo >= steps){ // digitalWrite(enable, HIGH); // Start the motor and keep it running }; if (stepsToGo == 0){ digitalWrite(enable, LOW); // switch motor off and wait 1sec delay(1000); stepsToGo = steps; // reset the countdown forward = !forward; // reverse motordirection and restart motor (@next loop) digitalWrite(direction_pin, forward); }; } void ISR_A(){ if( A_next == true){ // check if the interrupt is valid A_next = !A_next; // expect a B-channel trigger next time stepsToGo -= 1; // countdown the remaining steps } } void ISR_B(){ if( A_next == false){ // check if the interrupt is valid A_next = !A_next; // expect a A-channel trigger next time stepsToGo -= 1; // countdown the remaining steps } }