[Assignment 9] Police Light

Concept

For this assignment, I made a police light using two LEDs, a button, and a potentiometer. When the button is pressed once, the blue LED turns on; when the button is pressed twice, the blue LED turns off and the red LED turns on; when the button is pressed three times, the two LEDs turn on and off alternatively. Using the potentiometer, the user can also control how fast the two LEDs will turn on and off.

Codes

As mentioned above, this police light has 3 modes: two single-light modes and alternating lights modes. This mode (0, 1, and 2) will change whenever the user presses the button. Since Arduino will read a single button press as a series of multiple “1s,” I used millis() to make sure Arduino reads only a single 1 for every 200ms. This means Arduino will ignore any 1s that come after the first 1 within 200ms. When 1 is read, the mode will increase by 1 and back to 0 after 2. Variable blueLED is a boolean that is used to keep track of which single LED to turn on and off.

if (currentTime == 0 || millis() - currentTime > 200) {
    if (switchVal) {
      mode = ++mode % 3;
      if (mode != 2) blueLED = !blueLED; 
    }
    currentTime = millis();
  }

Then, the program will turn LEDs on and off according to the current mode. For mode 0 and 1:

if (mode != 2) {
  if (blueLED) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  } else {
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }
}

For mode 2, two LEDs turns on and off alternatively. I could have used delay() to achieve this effect, but I decided to not use such function because Arduino cannot read any other sensor data at the same time. Instead, I used millis() to do this.  pVal is a analog reading of potentiometer and the input was mapped to a value between 0 and 800. LEDs will turn on and off for every pVal ms.

int pVal = map(analogRead(A0), 1023, 0, 0, 800);

else {
  if (millis() - ledTime > pVal) {
    if (ledOnOff) {
      digitalWrite(13, HIGH);
      digitalWrite(12, LOW);
    } else {
      digitalWrite(13, LOW);
      digitalWrite(12, HIGH);
    }

    ledTime = millis();
    ledOnOff = !ledOnOff;
  }
}

Future Improvements

This project turned out to be better than I first expected. I am very satisfied about the fact that the button is functional even when LEDs are alternatively lighting up by not using delay(). For future improvements, I may be able to add more complex patterns to the LEDs, which seems challenging because no delay()s can be used. Additionally, adding piezo speaker included in the kit will make this police light more interesting and realistic.

Leave a Reply