AAE6183_Tutorial2B_Q3.ino
- // Define the pins for red and green LEDs
- #define RLED 21
- #define GLED 22
- // Declare hardware timer pointers
- hw_timer_t *My_timer1 = NULL;
- hw_timer_t *My_timer2 = NULL;
- // Declare timer status flags
- boolean timer1_status = false;
- boolean timer2_status = false;
- // My_timer1 interrupt function - toggles red LED state
- void IRAM_ATTR blink1(){
- digitalWrite(RLED, !digitalRead(RLED));
- }
- // My_timer2 interrupt function - toggles green LED state
- void IRAM_ATTR blink2(){
- digitalWrite(GLED, !digitalRead(GLED));
- }
- void setup() {
- // Set the LED pins as output
- pinMode(RLED, OUTPUT);
- pinMode(GLED, OUTPUT);
- // Initialize the timers, prescaler = 80, count up
- My_timer1 = timerBegin(1000000);
- My_timer2 = timerBegin(1000000);
- // Attach interrupt functions to the timers
- timerAttachInterrupt(My_timer1, &blink1);
- timerAttachInterrupt(My_timer2, &blink2);
- // Set the timer alarms and disable them
- timerAlarm(My_timer1, 250000, true, 0); // 250ms
- timerStop(My_timer1);
- timerAlarm(My_timer2, 125000, true, 0); // 125ms
- timerStop(My_timer2);
- // Begin serial communication for user interaction
- Serial.begin(9600);
- Serial.println(F("Please select an LED: "));
- }
- void loop() {
- // Check if any character available for reading from the serial port
- if (Serial.available()) {
- char c = Serial.read();
- // If the received character is 'r' or 'R', toggle red LED
- if (c == 'r' || c == 'R') {
- timer1_status = !timer1_status;
- if (timer1_status)
- timerStart(My_timer1);
- else {
- timerStop(My_timer1);
- digitalWrite(RLED, LOW); // Ensure LED is off
- }
- }
- // If the received character is 'g' or 'G', toggle green LED
- else if (c == 'g' || c == 'G') {
- timer2_status = !timer2_status;
- if (timer2_status)
- timerStart(My_timer2);
- else {
- timerStop(My_timer2);
- digitalWrite(GLED, LOW); // Ensure LED is off
- }
- }
- // If the received character is neither 'r'/'R' nor 'g'/'G', return an error
- else {
- Serial.println(F("Error, please select a valid LED."));
- }
- Serial.println(F("Please select an LED: "));
- }
- delay(50); // delay in between reads for stability
- }
Pasted 2026-05-06 10:36:40
Short link:
Short link: