// English for which LED to Strobe
#define RED 0x0
#define BLUE 0x1
// Variable to track which LED is on
byte whichLED = RED;
// Where are the LEDs connected?
const int LED_Red = 7;
const int LED_Blue = 11;
// State variables for the LEDs
byte Red_State = LOW;
byte Blue_State = LOW;
// Some delay values to change flashing behavior
unsigned long switchDelay = 250;
unsigned long strobeDelay = 50;
// Seed the initial wait for the strobe effect
unsigned long strobeWait = strobeDelay;
// Variable to see when we should swtich LEDs
unsigned long waitUntilSwitch = switchDelay; // seed initial wait
void setup() {
pinMode(LED_Red, OUTPUT);
pinMode(LED_Blue, OUTPUT);
}
void loop() {
digitalWrite(LED_Red, Red_State); // each iteration of loop() will set the IO pins,
digitalWrite(LED_Blue, Blue_State); // even if they don't change, that's okay
// Toggle back and forth between the two LEDs
if ((millis() - waitUntilSwitch) >= 0) {
// time is up!
Red_State = LOW;
Blue_State = LOW;
whichLED = !whichLED; // toggle LED to strobe
waitUntilSwitch += switchDelay;
}
// Create the stobing effect
if ((millis() - strobeWait) >=0 ) {
if (whichLED == RED)
Red_State = !Red_State;
if (whichLED == BLUE)
Blue_State = !Blue_State;
strobeWait += strobeDelay;
}
}
Based on a question from Andrew on the initial Multitasking with millis() tutorial, this example shows how to create a Police-Light like strobe effect. The following code uses no calls to delay().
Code also available via Pastebin.org.
44 Comments
I hope I’m not stupid, but… I don’t get any flashing of the LEDs whatsoever. They both just light up constantly. I am using the exact code from this page – what am I doing wrong?
How do you have it wired?
The code wouldn’t run until I inserted (long) before the two occurrences of millis in the loop().
This was included in an earlier example but is missing in this one.
Out of interest, it didn’t work with (unsigned long) inserted. Why is this????
Thank you for this, I find it very helpful. One thing I noticed: “`strobeWait += strobeDelay;“` would count up until breaking some limit or buffer wouldn’t it? Could you show to to modify your example to prevent that? Thank you.
It counts up until it rolls over.
Dear James Lewis , I used your code to my IR control code ,the Police Lights can ruining and flash,
but i can not turn off some time,some time the pin 13 light on,some time the pin 11 light on ,some time pin 12 & 13 off .
I am a tiro ,can you help me what wrong in my code at turn off the police lights,thank you.
#include
int irPin = 7; //ir sensor pin
int landing = 5; //landing lights, taxi lights and logo lights
int Position = 6; //red/green/white lights on wing tips – no flash –
int antiCol = 9; //red flashing lights on top and bottom
const int strobe = 8; //tail and wingtips
int all[] = {5, 6, 9, 8}; //all lights
int strobeState = LOW;
long prevMillis = 0;
long interval = 3500; //time between flashes
bool StrobeIsFlashing=false;
// English for which LED to Strobe
#define RED 0x0
#define BLUE 0x1
// Variable to track which LED is on
byte whichLED = RED;
// Where are the LEDs connected?
const int LED_Red = 11;
const int LED_Blue = 13;
// State variables for the LEDs
byte Red_State = LOW;
byte Blue_State = LOW;
// Some delay values to change flashing behavior
unsigned long switchDelay = 250;
unsigned long strobeDelay = 50;
// Seed the initial wait for the strobe effect
unsigned long strobeWait = strobeDelay;
// Variable to see when we should swtich LEDs
unsigned long waitUntilSwitch = switchDelay; // seed initial wait
IRrecv irrecv(irPin);
decode_results results;
void setup(){
Serial.begin(9600); //starts serial monitor *for debuging*
irrecv.enableIRIn(); //starts IR reciever
pinMode(landing, OUTPUT);
pinMode(Position, OUTPUT);
pinMode(antiCol, OUTPUT);
pinMode(strobe, OUTPUT);
pinMode(LED_Red, OUTPUT);
pinMode(LED_Blue, OUTPUT);
}
void loop(){
digitalWrite(LED_Red, Red_State); // each iteration of loop() will set the IO pins,
digitalWrite(LED_Blue, Blue_State); // even if they don’t change, that’s okay
if (irrecv.decode(&results)){
long int decCode = results.value;
Serial.println(decCode);
switch (results.value){
case 2079:
digitalWrite(landing, 1);
Serial.println(“LANDING/TAXI/LOGO LIGHTS ENGAGED”);
break;
case 31:
digitalWrite(landing, 0);
Serial.println(“LANDING/TAXI/LOGO LIGHTS DISENGAGED”);
break;
case 2108:
digitalWrite(Position, 1);
Serial.println(“POSITION LIGHTS ENGAGED”);
break;
case 60:
digitalWrite(Position, 0);
Serial.println(“POSITION LIGHTS DISENGAGED”);
break;
case 0xFF52AD:
Serial.println(“STROBE ACTIVATED”);
StrobeIsFlashing=!StrobeIsFlashing;
break;
default:
Serial.println(“WAITING”);
}
irrecv.resume();
}
if(StrobeIsFlashing)
{
FlashStrobe();
}
}
void FlashStrobe()
{
if (strobeState == 0)
if ((long)(millis() – waitUntilSwitch)>=0) {
// time is up!
Red_State = LOW;
Blue_State = LOW;
whichLED = !whichLED; // toggle LED to strobe
waitUntilSwitch += switchDelay;
}
if ((long)(millis() – strobeWait)>=0) {
if (whichLED == RED)
Red_State = !Red_State;
if (whichLED == BLUE)
Blue_State = !Blue_State;
strobeWait += strobeDelay;
strobeState = 1;
}
else
digitalWrite(LED_Red, LOW);
digitalWrite(LED_Blue, LOW);
strobeState = 0;
}
Hi, Tried your code and it works great. I also added a button to the code so I can turn it on and off. But sometimes (can’t really tell when exactly) when I turn on the flasing leds, they don’t flash like I expect (500/50) but they just light up one by one, with half a second of delay, so the switching of the leds works, but the strobe flashing doesn’t. After a couple of seconds (didn’t count this) the normal pattern starts again.
Any idea what could cause this?
Any number of things, without seeing your code I can only (poorly) guess.
Great to visit the page.
In fact I was looking for how to use mill() instead of delay and the research forced me to leave my problem.
I am working on a program where i want to press and hold a push button and stop the program to wait till i release the button then the program will resume where it stopped within a set time . Now when i press and hold the button, the time is running and after releasing the code ends before the set time ends.
[arduino firstline=””]
while (!digitalRead(pushButtonin)) // If the button pin is low, this will wait until it goes high again. Otherwise it’ll just skip
{}
delay(1000);
float elapsed,finished, start;
while(digitalRead(pushButtonin)==HIGH)
{
digitalWrite(relaypin, LOW);
}
delay(100);
val=digitalRead(pushButtonin);
start=millis();
while(DT>=elapsed)
{
if( val=HIGH){
digitalWrite(relaypin, HIGH);
}
while(digitalRead(pushButtonin))
{
digitalWrite(relaypin, LOW);
}
digitalWrite(relaypin, HIGH);
finished=millis();
elapsed=(finished-start);
}
delay(DT);
digitalWrite(relaypin,LOW);
[/arduino]
kind regards
There are several problems with your code. I added line numbers.
Line 3: millis() variables MUST be an integer and they SHOULD be unsigned long. Making them float adds overhead and makes comparisons difficult. There is NO reason for them to be a float.
In this code, I do not see where DT is defined, nor can I understand what you are trying to do on line 12 and 30.
Line 15: You used = instead of ==.
This example where I show how to detect long and short button presses might help:
https://www.baldengineer.com/detect-short-long-button-press.html
And this example where you do an action after a button has been pressed:
https://www.baldengineer.com/use-millis-with-buttons-to-delay-events.html
Good evening. I used enum instead of #define as you suggested. Not sure if I have used enum correctly. I tried adding another LED and name in the enum, like this, enum blinkStates {RED, BLUE, YELLOW}; adding YELLOW within the enum did not have any affect within the code.
I don’t understand what the #define RED 0x0 and #define BLUE 0x1 are doing. These are only setting a value of 0 or 1, off or on? This would be the same for the enum statement? enum {RED, BLUE}; is setting RED as 0 and BLUE as 1?
I first started with 3 LEDs and then I added a 4th. Thank you for the guides. Perry
Here is the modified code
// English for which LED to Strobe
enum blinkStates {RED, BLUE};
//enum blinkStates whichLED;
//#define RED 0x0
//#define BLUE 0x1
// Variable to track which LED is on
byte whichLED = RED;
// Where are the LEDs connected?
const int LED_G = 10;
const int LED_Red = 11;
const int LED_Y = 12;
const int LED_Blue = 13;
// State variables for the LEDs
byte Red_State = LOW;
byte Blue_State = LOW;
byte Y_State = LOW;
byte G_State = LOW;
// Some delay values to change flashing behavior
unsigned long switchDelay = 250;
unsigned long strobeDelay = 50;
// Seed the initial wait for the strobe effect
unsigned long strobeWait = strobeDelay;
// Variable to see when we should swtich LEDs
unsigned long waitUntilSwitch = switchDelay; // seed initial wait
void setup() {
pinMode(LED_Red, OUTPUT);
pinMode(LED_Blue, OUTPUT);
pinMode(LED_Y, OUTPUT);
pinMode(LED_G, OUTPUT);
}
void loop() {
digitalWrite(LED_Red, Red_State); // each iteration of loop() will set the IO pins,
digitalWrite(LED_Blue, Blue_State); // even if they don’t change, that’s okay
digitalWrite(LED_Y, Y_State);
digitalWrite(LED_G, G_State);
// Toggle back and forth between the two LEDs
if ((long)(millis() – waitUntilSwitch)>=0) {
// time is up!
Red_State = LOW;
Blue_State = LOW;
Y_State = LOW;
whichLED = !whichLED; // toggle LED to strobe
waitUntilSwitch += switchDelay;
}
// Create the stobing effect
if ((long)(millis() – strobeWait)>=0) {
if (whichLED == RED)
Red_State = !Red_State;
G_State = !Red_State;
if (whichLED == BLUE)
Blue_State = !Blue_State;
Y_State = !Blue_State;
strobeWait += strobeDelay;
}
}
Hi, I used your code (which by the way works perfectly. I added switch to control when strobe should work. My problem is , when turn it off one of LEDs still lid. If you can help me how to stop diods when switch is off.
part of code,
[arduino language=””]
void strobeLights()
{
strobeButtonState = digitalRead(strobeButton);
if (strobeButtonState == HIGH)
{
digitalWrite(redLedPin, redLedState);
digitalWrite(blueLedPin, blueLedState);
if ((long)(millis() – waitUntilSwitch)>=0)
{
redLedState = LOW;
blueLedState = LOW;
whichLED = !whichLED;
waitUntilSwitch += switchDelay;
}
if ((long)(millis() – strobeWait)>=0)
{
if (whichLED == RED)
redLedState = ! redLedState;
if (whichLED == BLUE)
blueLedState = ! blueLedState;
strobeWait += strobeDelay;
}
}
}
[/arduino]
Add an else statement that sets the states to off.
Hi James, thanks for answer. When I add statemens blue led lids constantly. Whithout statements, i just interrupt function in random state of leds ( one of them is lid constantly, or if I get right moment both are off?). Another thing is whe switch is on led blink slower anf after 1-2seconds are blinking properly.
I am using multiple leds on a Heli and need 3 leds all strobing at different rate2. How can use milis to accomplish this?
Thanks!
With the code in this example, you could take out the “switchDelay” and just make multiple strobe delays. Or you could look at the Independent On and Off times, duplicating the state variables 3 times.
Thanks, like it. How to control How many times led strobes. Please
may i ask how i can add more led’s to the loop but stil maintain the concept of two groups flikkering on and off?
Depends on what you mean by add. If you want more LEDs to turn on at the same time, add more pin assignments, pinmodes(), and digitalWrites().
If you more patterns, then you duplicate all of the “red/blue” variables for more groups. There are more efficient coding methods, maybe using an enum.
what’s the circuit diagram for this project? Your video is cool though not obvious to duplicate.
Nothing special. Just two LEDs connected to I/O pins with a resistor to ground.
I/O Pin -> LED -> Resistor -> Ground
I found this code on Youtube and I’m sure it is yours but it is slightly different as it has wigwags integrated into it. I absolutely love the design. and will be using it in my project (Thank you). I was hoping to be able to alter the wigwag to wigwag for a few seconds and then strobe for a couple seconds then repeat. Also I was wondering if there is a way to integrate an IR receiver to control functions separately. For example 1 just the wigwags and another just the other lights, and another all the lights. I hope that you can help as I can alter code some but am terrible at writing it. Here is the code I have:
[arduino collapse=”true”]
#define RED 0x0
#define BLUE 0x1
int variStrobe[7]={100,250,250,100,450,50,75};
int variCount = 0;
int variAdder = 0;
int variLast = 0;
int wigWagDelay = 200;
long wigWagPrev = 0;
int wigWagState = LOW;
byte whichLED = RED;
const int LED_Red = 12;
const int LED_Blue = 13;
const int LED_wigwag1 = 11;
const int LED_wigwag2 = 10;
byte Red_State = LOW;
byte Blue_State = LOW;
unsigned long switchDelay = variStrobe[variAdder];
unsigned long strobeDelay = 50;
unsigned long strobeWait = strobeDelay;
unsigned long waitUntilSwitch = switchDelay;
void setup() {
pinMode(LED_Red, OUTPUT);
pinMode(LED_Blue, OUTPUT);
pinMode(LED_wigwag1, OUTPUT);
pinMode(LED_wigwag2, OUTPUT);
}
void loop() {
digitalWrite(LED_Red, Red_State);
digitalWrite(LED_Blue, Blue_State);
unsigned long wigWagMillis = millis();
if ((long)(millis() – waitUntilSwitch)>=0) {
// time is up!
Red_State = LOW;
Blue_State = LOW;
whichLED = !whichLED; // toggle LED to strobe
waitUntilSwitch += switchDelay;
variCount++;
if(variCount-variLast==10)
{
variAdder++;
variLast = variCount;
switchDelay = variStrobe[variAdder];
if(variAdder>6){
variCount = 0;
variAdder = 0;
variLast = 0;
}
}
}
// Create the stobing effect
if ((long)(millis() – strobeWait)>=0) {
if (whichLED == RED)
Red_State = !Red_State;
if (whichLED == BLUE)
Blue_State = !Blue_State;
strobeWait += strobeDelay;
}
if(wigWagMillis – wigWagPrev > 150)
{
wigWagPrev = wigWagMillis;
wigWagState = !wigWagState;
digitalWrite(LED_wigwag1, wigWagState);
digitalWrite(LED_wigwag2, !wigWagState);
}
}
[/arduino]
In order to help, you’d need to provide more details. It might be better to post your questions on a forum, like the Programming Forum on arduino.cc. So that others can help you as well.
hello, I would like to include in your sketch also turn signals. which code should I add? Thanks. Sorry for my bad! english.
This is unbelievable to me. The logic evades me for some reason. I’ve even drawn the flow of it out on paper and can’t quite get it. It works beautifully, though. Really cool. I had my own version without using delay(), but yours is more robust. The strobes are brighter and more definite.
My version switches between two if() statements with 4 digitalWrite()s in each of them. LOL.
Thanks.
WHAT ARE THE MATERIALS NEEDED?
Two LEDs, two resistors, a breadboard, some hookup wire, and an Arduino.
Just an update from me, I built 2 light bars for my truck and modified your code here to suit my needs and I’ve made a video of both bars.
You can view the video here
Looks great! Thanks for sharing the update.
Love the code, simplifies my giant batch of delays which stopped me reading an input status down to something totally workable.
one question though, is it possible to have differnt timing for the on and off times. ie yours currently runs at 50ms on 50ms off and completes 3 flashes before changin colour.
is it possible to have 60ms on, 25 ms off. in the same pattern? obviously changing the switch delay to 340ms (would give 4 flashes of each colour with a delay in the middle. unlike your code that skips the delay on the transition?)
You would need to modify the code to define an “on” and “off” delay. An example of a single LED can be found here: https://www.baldengineer.com/blog/2013/12/10/millis-ind-on-off-times/. Can’t just copy and paste the two together, but I think you could see how to build up a simple state machine.
Great site, thanks. Took your Police Light and implemented it on a NeoPixel Shield. You can see a video here http://youtu.be/2VhoQlK7hMs and the code is available in pastebin http://pastebin.com/eeiPckxx
Thanks
Stuart/
[Edit: I fixed the link and deleted the other comment…]
like this setup. trying to get a strobe to work where i get two quick flashes and then off for x time trying to so without a delay command
You need to setup a flag variable to tell when you should be strobing and a variable as the timer. Set the timer to off-value. Whenever the timer is reached, set the flag variable to true. When flag variable is true, flash the strobes. On the 2nd strobe, set the variable back to false and reset your timer.
Would it be possible to see an example with more than 2 led’s, say maybe 7 led’s?
I’m not really sure how to create a “police” strobe with 7 LEDs, since they generally just flash back and forth.
I’m thinking more along the lines of a light bar, like you see on the roof of the cars, they have 8 segments (16 if you include front and rear), that flash at different times.
I have acquired a tow truck light bar (all amber leds) that was damaged. I only have 7 working led packs (three to a pack) and am currently using lots of delays and spaghetti code to make it work. Your method seems nicer.
Can they flash randomly or do you want a specific pattern?
Currently I have 6 patterns that I can select from, but that’s overkill really. A random strobe effect would be cool, as well as two official looking patterns. I was discussing your code with a friend a bit more knowledgeable than myself, and he said using arrays to define the patterns would be my best bet.
Sorry about that. I’m not sure what step in my publishing process introduces the change. The symbols < and > are used by HTML code, so one step in my process converts them into the symbol codes > and %lt;.
But, that’s why I also make the code available via Pastebin. 😉
Checked code on other site and it was better..it should be a > symbol.
What is the >? It gives me an error..
Andrew
I will give that a try and try to add more lights at different rates. Thanks!
Pingback: millis() Tutorial: Arduino Multitasking - CMiYC Labs, Inc.