AAE6183_Tutorial2B_Q3.ino
  1. // Define the pins for red and green LEDs
  2. #define RLED 21
  3. #define GLED 22
  4.  
  5. // Declare hardware timer pointers
  6. hw_timer_t *My_timer1 = NULL;
  7. hw_timer_t *My_timer2 = NULL;
  8.  
  9. // Declare timer status flags
  10. boolean timer1_status = false;
  11. boolean timer2_status = false;
  12.  
  13. // My_timer1 interrupt function - toggles red LED state
  14. void IRAM_ATTR blink1(){
  15. digitalWrite(RLED, !digitalRead(RLED));
  16. }
  17.  
  18. // My_timer2 interrupt function - toggles green LED state
  19. void IRAM_ATTR blink2(){
  20. digitalWrite(GLED, !digitalRead(GLED));
  21. }
  22.  
  23. void setup() {
  24. // Set the LED pins as output
  25. pinMode(RLED, OUTPUT);
  26. pinMode(GLED, OUTPUT);
  27.  
  28. // Initialize the timers, prescaler = 80, count up
  29. My_timer1 = timerBegin(1000000);
  30. My_timer2 = timerBegin(1000000);
  31.  
  32. // Attach interrupt functions to the timers
  33. timerAttachInterrupt(My_timer1, &blink1);
  34. timerAttachInterrupt(My_timer2, &blink2);
  35.  
  36. // Set the timer alarms and disable them
  37. timerAlarm(My_timer1, 250000, true, 0); // 250ms
  38. timerStop(My_timer1);
  39. timerAlarm(My_timer2, 125000, true, 0); // 125ms
  40. timerStop(My_timer2);
  41.  
  42. // Begin serial communication for user interaction
  43. Serial.begin(9600);
  44. Serial.println(F("Please select an LED: "));
  45. }
  46.  
  47. void loop() {
  48. // Check if any character available for reading from the serial port
  49. if (Serial.available()) {
  50. char c = Serial.read();
  51.  
  52. // If the received character is 'r' or 'R', toggle red LED
  53. if (c == 'r' || c == 'R') {
  54. timer1_status = !timer1_status;
  55. if (timer1_status)
  56. timerStart(My_timer1);
  57. else {
  58. timerStop(My_timer1);
  59. digitalWrite(RLED, LOW); // Ensure LED is off
  60. }
  61. }
  62. // If the received character is 'g' or 'G', toggle green LED
  63. else if (c == 'g' || c == 'G') {
  64. timer2_status = !timer2_status;
  65. if (timer2_status)
  66. timerStart(My_timer2);
  67. else {
  68. timerStop(My_timer2);
  69. digitalWrite(GLED, LOW); // Ensure LED is off
  70. }
  71. }
  72. // If the received character is neither 'r'/'R' nor 'g'/'G', return an error
  73. else {
  74. Serial.println(F("Error, please select a valid LED."));
  75. }
  76. Serial.println(F("Please select an LED: "));
  77. }
  78. delay(50); // delay in between reads for stability
  79. }
  80.  
Pasted 2026-05-06 10:36:40

Short link: