int input_pin = 2;
volatile int valume;
volatile int buttonPressCount = 0;
volatile int lastButtonState = HIGH;
volatile bool timer1Active = false;
volatile bool timer2Active = false;
void setupTimer1(){
noInterrupts();
TCCR1A =0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 31249; //0.5Hz
TCCR1B = (1<<WGM12);
TCCR1B |= (1<<CS12) | (1<<CS10);
TIMSK1 |= (1<<OCIE1A);
interrupts();
}
void setupTimer2(){
noInterrupts();
TCCR2A =0;
TCCR2B = 0;
TCNT2 = 0;
OCR2A = 255; //1Hz
TCCR2B = (1<<WGM22);
TCCR2B |= (1<<CS22) | (1<<CS21) | (1<<CS20);
TIMSK2 |= (1<<OCIE2A);
interrupts();
}
void setupTimer3(){
noInterrupts();
TCCR3A =0;
TCCR3B = 0;
TCNT3 = 0;
OCR3A = 7811.5; //2Hz
TCCR3B = (1<<WGM32);
TCCR3B |= (1<<CS32) | (1<<CS30);
TIMSK3 |= (1<<OCIE3A);
interrupts();
}
void setup() {
pinMode(input_pin, INPUT);
attachInterrupt(digitalPinToInterrupt(input_pin), state, FALLING);
DDRC = 0xFF;
setupTimer1();
setupTimer2();
setupTimer3();
Serial.begin(9600);
}
void loop() {
}
void state(){
static unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 150;
// Debounce
if ((millis() - lastDebounceTime) < debounceDelay) {
return;
}
lastDebounceTime = millis();
buttonPressCount++;
switch(buttonPressCount){
case 1 :
timer1Active = true ;
timer2Active = false;
TIMSK1 |= (1 << OCIE1A);
TIMSK2 &= ~(1 << OCIE2A);
break;
case 2 :
timer1Active = false;
timer2Active = true;
TIMSK1 &= ~(1 << OCIE1A);
TIMSK2 |= (1 << OCIE2A);
break;
case 3 :
timer1Active = false;
timer2Active = false;
TIMSK1 &= ~(1 << OCIE1A);
TIMSK2 &= ~(1 << OCIE2A);
buttonPressCount = 0;
PORTC = 0;
break;
}
Serial.print("Button press count: ");
Serial.println(buttonPressCount);
}
ISR(TIMER1_COMPA_vect){
if(timer1Active){
PORTC ^= (1<<PC0) | (1<<PC1) | (1<<PC2);
}
}
ISR(TIMER2_COMPA_vect){
if(timer2Active){
PORTC ^= (1<<PC3) | (1<<PC4) | (1<<PC5) | (1<<PC6);
}
}
ISR(TIMER3_COMPA_vect){
PORTC ^= (1<<PC7);
}