int input_pin = 2; // ขาสวิตช์ต่ออยู่ที่ 2
volatile int switch_count = 0; // ตัวนับจำนวนครั้งที่กดสวิตช์
// ตั้ง Timer3 สำหรับความถี่ 0.5 Hz (สำหรับ PC1-PC3)
void setupTimer3() {
noInterrupts(); // ปิด interrupt ชั่วคราว
TCCR3A = 0; // เคลียร์ register
TCCR3B = 0;
TCNT3 = 0;
// คำนวณค่า OCR3A สำหรับความถี่ 0.5 Hz
// ความถี่ต้องการ = 0.5 Hz
// Clock = 16 MHz, Prescaler = 256
// OCR3A = (16MHz/(2 * 256 * 0.5Hz)) - 1
OCR3A = 62499; // 0.5 Hz
TCCR3B |= (1 << WGM32); // ตั้งโหมด CTC
TCCR3B |= (1 << CS32); // Prescaler = 256
TIMSK3 |= (1 << OCIE3A); // เปิด Compare Match A Interrupt
interrupts(); // เปิด interrupt
}
// ตั้ง Timer1 สำหรับความถี่ 1 Hz (สำหรับ PC4-PC7)
void setupTimer1() {
noInterrupts(); // ปิด interrupt ชั่วคราว
TCCR1A = 0; // เคลียร์ register
TCCR1B = 0;
TCNT1 = 0;
// คำนวณค่า OCR1A สำหรับความถี่ 1 Hz
// ความถี่ต้องการ = 1 Hz
// Clock = 16 MHz, Prescaler = 256
// OCR1A = (16MHz/(2 * 256 * 1Hz)) - 1
OCR1A = 31249; // 1 Hz
TCCR1B |= (1 << WGM12); // ตั้งโหมด CTC
TCCR1B |= (1 << CS12); // Prescaler = 256
TIMSK1 |= (1 << OCIE1A); // เปิด Compare Match A Interrupt
interrupts(); // เปิด interrupt
}
void setup() {
pinMode(input_pin, INPUT); // ตั้งขาสวิตช์เป็น INPUT
DDRC = 0xFF; // ตั้งพอร์ต C (PC0-PC7) เป็น OUTPUT
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(input_pin), handleSwitch, RISING);
setupTimer3();
setupTimer1();
}
void loop() {
// ไฟ LED สีเขียว (PC0) กระพริบด้วยความถี่ 2 Hz
PORTC ^= (1 << PC0);
delay(250); // 2 Hz = 250 ms (on) + 250 ms (off)
}
// ISR สำหรับ Timer3 ควบคุม PC1-PC3 กระพริบที่ 0.5 Hz
ISR(TIMER3_COMPA_vect) {
static bool statePulse1 = false;
if (switch_count == 1 || switch_count == 2) {
statePulse1 = !statePulse1;
if (statePulse1) {
PORTC |= (1 << PC1) | (1 << PC2) | (1 << PC3);
} else {
PORTC &= ~((1 << PC1) | (1 << PC2) | (1 << PC3));
}
} else if (switch_count == 3) {
PORTC &= ~((1 << PC1) | (1 << PC2) | (1 << PC3));
}
}
// ISR สำหรับ Timer1 ควบคุม PC4-PC7 กระพริบที่ 1 Hz
ISR(TIMER1_COMPA_vect) {
static bool statePulse2 = false;
if (switch_count == 2) {
statePulse2 = !statePulse2;
if (statePulse2) {
PORTC |= (1 << PC4) | (1 << PC5) | (1 << PC6) | (1 << PC7);
} else {
PORTC &= ~((1 << PC4) | (1 << PC5) | (1 << PC6) | (1 << PC7));
}
} else if (switch_count == 3) {
PORTC &= ~((1 << PC4) | (1 << PC5) | (1 << PC6) | (1 << PC7));
}
}
void handleSwitch() {
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
if (interrupt_time - last_interrupt_time > 200) {
switch_count++;
if (switch_count > 3) {
switch_count = 1;
}
Serial.print("Switch count: ");
Serial.println(switch_count);
}
last_interrupt_time = interrupt_time;
}