Fun With Interrupts – James Kyle

How it works:

I played around with buttons switches and potentiometers to change light blinking patterns and came up with this circuit. The switch has an interrupt which changes whether all lights blink at the same time or different times (a blink mode). The button changes which light blinks in the event that they are not blinking at the same time. The potentiometer changes the speed at which the lights blink.

I had some trouble with getting the switch interrupt to work more than once and I ended up having to place it before the button interrupt which I assume prioritizes it.

 

Code:

int toggle_color = 3;
int GREEN_LED = 7;
int YELLOW_LED = 6;
int RED_LED = 5;
int POT = A0;
int blink_rate = 250;
int toggle_blinkMode = 2;


//LED blinking variables
volatile int LED_pin = 5;
volatile bool individual_blink;


//Debounce variables
volatile unsigned long last_press = 0;
int wait_time = 50;




void setup() {

  Serial.begin(9600);

  //Initializing Pins
  pinMode(GREEN_LED, OUTPUT);
  pinMode(YELLOW_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);

  pinMode(toggle_color, INPUT_PULLUP);
  pinMode(POT, INPUT);


  //Interrupt initialization
  attachInterrupt(digitalPinToInterrupt(toggle_blinkMode), blinkMode, CHANGE);
  attachInterrupt(digitalPinToInterrupt(toggle_color), switchLED, CHANGE);


}

void switchLED() {

  //Turn off previous light
  digitalWrite(LED_pin, LOW);

  //Debounce
  if ((millis() - last_press) >= wait_time) {
    LED_pin++;
    last_press = millis();
  }

  //Go back to first light
  if (LED_pin > 7) {
    LED_pin = 5;
  }


}

void blinkMode() {

  if (individual_blink) {
    individual_blink = 0;
  } else {
    individual_blink = 1;
  }

}

void loop() {

  blink_rate = map(analogRead(POT), 0, 255, 100, 500);

  if (individual_blink) {
    digitalWrite(LED_pin, HIGH);
    delay(blink_rate);
    digitalWrite(LED_pin, LOW);
    delay(blink_rate);
  } else {
    digitalWrite(RED_LED, HIGH);
    digitalWrite(GREEN_LED, HIGH);
    digitalWrite(YELLOW_LED, HIGH);
    delay(blink_rate);
    digitalWrite(RED_LED, LOW);
    digitalWrite(GREEN_LED, LOW);
    digitalWrite(YELLOW_LED, LOW);
    delay(blink_rate);
  }

  bool value = individual_blink;
  Serial.println(value);


}

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.