int input_pin = 2 ;
volatile int valume;
volatile int mode = 0; // ตัวแปรนับจำนวน (volatile เพราะใช้ใน Interrupt)
void setupTimer1() {
noInterrupts();
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
// 1 HZ (16,000,000/((15624+1)*1024))
OCR1A = 15624;
// Configure Timer3 in CTC mode
TCCR1B |= (1 << WGM12);
// Set prescaler to 1024
TCCR1B |= (1 << CS12) | (1 << CS10);
// Enable Output Compare Match A Interrupt
TIMSK1 |= (1 << OCIE1A);
interrupts();
}
void setupTimer3() {
noInterrupts();
TCCR3A = 0;
TCCR3B = 0;
TCNT3 = 0;
// 1 HZ (16,000,000/((15624+1)*1024))
OCR3A = 31249;
// Configure Timer3 in CTC mode
TCCR3B |= (1 << WGM32);
// Set prescaler to 1024
TCCR3B |= (1 << CS32) | (1 << CS30);
// Enable Output Compare Match A Interrupt
TIMSK3 |= (1 << OCIE3A);
interrupts();
}
void setup() {
pinMode(input_pin, INPUT); // Input pin with pull-up resistor
attachInterrupt(digitalPinToInterrupt(input_pin), incrementCounter, FALLING); // Trigger on falling edge
DDRC = 0xFF; // Set PORTC as output for LEDs
setupTimer1();
setupTimer3(); // Default to 0.5 Hz for Timer3
Serial.begin(9600);
}
void loop() {
// Green LED (PC0) blinks to indicate the program is running
PORTC ^= (1 << PC0);
Serial.print("MODE: ");
Serial.println(mode);
delay(500); // หน่วงเวลาเล็กน้อยเพื่อดูการแสดงผลชัดเจน
}
// void state(){
// valume = digitalRead(input_pin);
// Serial.print("Input reading: ");
// Serial.println(valume);
// }
void incrementCounter() {
static unsigned long lastInterruptTime = 0; // ตัวแปรสำหรับ debounce
unsigned long currentTime = millis();
if(mode==3){
mode = 1;
}
// ตรวจสอบว่าเวลาเพียงพอสำหรับ debounce (200 ms)
if (currentTime - lastInterruptTime > 200) {
mode++; // เพิ่มค่าตัวแปร counter
lastInterruptTime = currentTime; // อัปเดตเวลา
}
}
ISR(TIMER1_COMPA_vect) {
if (mode == 2) {
// Turn off LEDs PC1, PC2, PC3
PORTC &= ~((1 << PC1) | (1 << PC2) | (1 << PC3));
// Toggle LEDs PC4, PC5, PC6, PC7
PORTC ^= (1 << PC4) | (1 << PC5) | (1 << PC6) | (1 << PC7);
}
}
ISR(TIMER3_COMPA_vect) {
if (mode == 1) {
// Turn off LEDs PC4, PC5, PC6, PC7
PORTC &= ~((1 << PC4) | (1 << PC5) | (1 << PC6) | (1 << PC7));
// Toggle LEDs PC1, PC2, PC3
PORTC ^= (1 << PC1) | (1 << PC2) | (1 << PC3);
}
}