#include <avr/interrupt.h>
#include <wiring_private.h>
#include <pins_arduino.h>
#include <PinChangeInterrupt.h>
volatile int step;
volatile int currentStateClock;
volatile int StateData;
volatile int lastStateClock;
volatile unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
void timerInit(){
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= B00000100;
TIMSK1 |= B00000010;
OCR1A = 31250;
sei();
}
void setup() {
Serial.begin(9600);
timerInit();
DDRD |= 0xC;
PCICR |= 0x4; // Enable pin change interrupts for port D
PCMSK2 |= 0x30; // Enable interrupts for pins 4 and 5
}
void loop() {
// No code in the loop
Serial.println(step);
}
ISR(PCINT2_vect) {
int newClockState = (PIND & 0x10);
if (newClockState != lastStateClock) {
// Debounce the input by ignoring changes that occur too quickly
if (millis() - lastDebounceTime > debounceDelay) {
if ((PIND & 0x20) != newClockState) {
// Clockwise rotation
step++;
sbi(PORTD, PD6);
cbi(PORTD, PD6);
} else {
// Counter-clockwise rotation
step--;
sbi(PORTD, PD7);
sbi(PORTD, PD6);
cbi(PORTD, PD6);
cbi(PORTD, PD7);
}
}
lastDebounceTime = millis();
lastStateClock = newClockState;
}
}
ISR(Timer1_COMPA-vect){
TCNT1 = 0;
}