Led Motorcycle Lights & Arduino Programming With No Delays

Hello Gang!

I am working on a Turn Signal, Brake Light and Headlight controller for my motorcycle with the Arduino. The issue I have came up with is that while I push a button for the turn signals I get a delay before the brake light will come on(not a good thing :frowning: ) What I want to find out is there a way I can program the Arduino to not have these delays?

I will need the Headlight to pulse during the day and this will probably tie up the processor during those cycles. I need to have everything able to react when needed, especially the brake light.

I know the bike already has part of the system I am doing but I want it to be enhanced with the Arduino and added features.

Thanks for any help!
Kevin

You did not post in the wishful thinking forum, or in the right my code for me forum. You posted in the programming forum. Therefore, the first thing we want to see is the program that you need help with.

The issue I have came up with is that while I push a button for the turn signals I get a delay before the brake light will come on

You wouldn't with the proper code.

I will need the Headlight to pulse during the day and this will probably tie up the processor during those cycles.

Certainly will. But "those cycles" amount to a few nanoseconds per second. You can do plenty in the other 99.999% of the time.

I need to have everything able to react when needed, especially the brake light.

The brake light on my bike(s) is activated by a switch. No computer involved. Why is the Arduino mucking with such an essential feature?

You should start with making a list of what you want the Arduino to do. Pulsing the headlight is reasonable. Pulsing the brake lights may, or may not be.

Once you know what you want the Arduino to do, check that doing all those things is not illegal. Flashing headlights are illegal in some places. Flashing brake lights are illegal in a lot more places.

First let me say thanks for replying! Second for some reason I don't like your tone with your response. Third I'm not here to get a lesson in laws just programming.

I have seen a lot of smart -ss coments on here and that is no way for long term members to treat newbys.

The lights on your bike are fine for you, I am doing a custom bike and I want a custom system. There is people on here doing things that have already been done but that doesn't keep them from learning and that is what the Arduino is for.

The laws a very defined and lighting systems on vehicles but that doesn't make them right. Out of all of the technological advancements car manufacturers have not improved upon these for safety factors. I am looking beyond what the car manufactures haven't done.

/*

Buttons Turn on and off LEDs connected to outputs 

CIRCUIT:
* LED attached from output pins to ground with current limiting resistor 
* pushbuttons attached to input pins from ground with each pin having a 10k pull up resistor to positive

*/

// constants won't change. They're used here to 
// set pin numbers:

const int buttonPinLT = 2; // the number of the pushbutton pin
const int buttonPinRT = 3; // the number of the pushbutton pin
const int buttonPinBR = 4; // the number of the pushbutton pin
const int buttonPinHL = 5; // the number of the pushbutton pin

const int ledPinLT = 10; // the number of the LED pin
const int ledPinRT = 11; // the number of the LED pin
const int ledPinBR = 12; // the number of the LED pin
const int ledPinHL = 13; // the number of the LED pin

bool isBrakeOn = false;


void setup() 

{ 
	// initialize the LED pins as an output:
	pinMode(ledPinLT, OUTPUT);
	pinMode(ledPinRT, OUTPUT);
	pinMode(ledPinBR, OUTPUT);
	pinMode(ledPinHL, OUTPUT);

	// initialize the pushbutton pins as an input:
	pinMode(buttonPinLT, INPUT);
	pinMode(buttonPinRT, INPUT);
	pinMode(buttonPinBR, INPUT);
	pinMode(buttonPinHL, INPUT);

}

void loop()

{ 
	//Process the left button
	if (digitalRead(buttonPinLT) == LOW)
	{
		TurnOn(ledPinLT);
	}


	//Process the right button
	if (digitalRead(buttonPinRT) == LOW)
	{
		TurnOn(ledPinRT);
	}

	//Process the brake
	if (digitalRead(buttonPinBR) == LOW)
	{
		TurnOnBrake(ledPinBR);
	}
	else
	{
		TurnOff(ledPinBR);
	}


}





void TurnOn(int led)

{

	for (int i=0;i<3;i++) // flash 3 times & delay
	{ 
		digitalWrite(led, HIGH); // set the LED on
		delay(250); // wait for a 1/4 second

		digitalWrite(led, LOW); // set the LED off
		delay(250); // wait for a 1/4 second
	} 
	delay(500); // wait for a 1/2 second

}





void TurnOnBrake(int led)

{

	if (isBrakeOn == false)

	{

		for (int i=0;i<10;i++) // flash 10 times & delay
		{ 
			digitalWrite(led, HIGH); // set the LED on
			delay(50); // wait for a 1/4 second

			digitalWrite(led, LOW); // set the LED off
			delay(50); // wait for a 1/4 second
		} 
		digitalWrite(led, HIGH); // set the LED on

		isBrakeOn = true;

	}

}





void TurnOff(int led)

{

	digitalWrite(led, LOW); // set the LED off

	isBrakeOn = false;

}

Besides it's my safety on the bike not anyone else, other than the people around me!

Like the old saying goes, If You Don't Have Anything Nice To Say(post) Then Don't Say(post) Anything.

You are not enabling the internal pullup resistors on the input pins for the switches. This means that you have external resistors, right?

You are not going to be reading anything while those delay() calls are happening. Right now, before you write any more code, would be a good time to learn about state machines and the millis() function, and to forget that delay() exists.

The laws a very defined and lighting systems on vehicles but that doesn't make them right.

Try telling that to the judge when your bike gets impounded for improper lights.

I have been working on this new code that uses Blink without delay. For some reason I can't get the led's to blink. When I push the buttons the led's just come on until I let go of the button.

Can someone look over the code and make any suggestions?

Sorry it may not look nice and organized.

/*

Buttons Turn on and off LEDs connected to outputs 

CIRCUIT:
* LED attached from output pins to ground with current limiting resistor 
* pushbuttons attached to input pins from ground with each pin having a 10k pull up resistor to positive

*/

// constants won't change. They're used here to 
// set pin numbers:

const int buttonPinLT = 2; // the number of the pushbutton pin
const int buttonPinRT = 3; // the number of the pushbutton pin
const int buttonPinBR = 4; // the number of the pushbutton pin
const int buttonPinHL = 5; // the number of the pushbutton pin

const int ledPinLT = 10; // the number of the LED pin
const int ledPinRT = 11; // the number of the LED pin
const int ledPinBR = 12; // the number of the LED pin
const int ledPinHL = 13; // the number of the LED pin


//variables for turn signals  Note: This assumes that only one turn signal can be turned on at a time.
long previousMillis = 0;
int ledState = LOW;             // ledState used to set the LED
const long interval = 10000;     // interval at which to blink (milliseconds)

 
//variables for brake signal
long previousMillisBR = 0;
int ledStateBR = LOW;             // ledState used to set the LED
const long intervalBR = 10000;     // interval at which to blink (milliseconds)
int blinkCount = 0;               // keeps track of the number of times that the brake light has blinked

void setup() 

{ 
	// initialize the LED pins as an output:
	pinMode(ledPinLT, OUTPUT);
	pinMode(ledPinRT, OUTPUT);
	pinMode(ledPinBR, OUTPUT);
	pinMode(ledPinHL, OUTPUT);

	// initialize the pushbutton pins as an input:
	pinMode(buttonPinLT, INPUT);
	pinMode(buttonPinRT, INPUT);
	pinMode(buttonPinBR, INPUT);
	pinMode(buttonPinHL, INPUT);

}

void loop()

{ 
	//Process the left button
	if (digitalRead(buttonPinLT) == LOW)
		TurnOn(ledPinLT);
	else
		TurnOff(ledPinLT);


	//Process the right button
	if (digitalRead(buttonPinRT) == LOW)
		TurnOn(ledPinRT);
	else
		TurnOff(ledPinRT);


	//Process the break
	if (digitalRead(buttonPinBR) == LOW)
		TurnOnBrake(ledPinBR);
	else
		TurnOffBrake(ledPinBR);

}





void TurnOn(int led)

{



  // check to see if it's time to blink the LED; that is, if the 

  // difference between the current time and last time you blinked 

  // the LED is bigger than the interval at which you want to 

  // blink the LED.

   unsigned long currentMillis = millis();

  

   if(currentMillis - previousMillis > interval) 

   {

		 // save the last time you blinked the LED 

		previousMillis = currentMillis;   



		// if the LED is off turn it on and vice-versa:

		 if (ledState == LOW)

		   ledState = HIGH;

		 else

		   ledState = LOW;

 

		// set the LED with the ledState of the variable:

		 digitalWrite(led, ledState);

   }



 }



   

void TurnOff(int led)

{

	digitalWrite(led, LOW); // set the LED off

	// Reset the variables that control the blinking

	previousMillis = 0;
	ledState = LOW;

}





void TurnOnBrake(int led)

{

	//Since we only want the light to blink 10 times, keep track of the number of blinks

	if (blinkCount < 10)

	{

		unsigned long currentMillisBR = millis();

		

		if(currentMillisBR - previousMillisBR > intervalBR) 

		{

			 // save the last time you blinked the LED 

			 previousMillisBR = currentMillisBR;



			 // if the LED is off turn it on and vice-versa:

			 if (ledState == LOW)

			 {

				ledState = HIGH;

				blinkCount++;

			 }

			 else

			 {

			   ledState = LOW;

			 }

 

			 // set the LED with the ledState of the variable:

			 digitalWrite(led, ledState);

		}

	}

	//The last time thru the above loop, the brake will be turned on and will stay on.

}





void TurnOffBrake(int led)

{

	digitalWrite(led, LOW); // set the LED off

	// Reset the variables that control the blinking

	blinkCount = 0;

	previousMillisBR = 0;
	ledStateBR = LOW;

}

Thanks,
Kevin

You are not enabling the internal pullup resistors on the input pins for the switches. This means that you have external resistors, right?.

You haven't answered this question.

If you are, and you push the switch connected to the buttonPinLT pin, the TurnOn() function should be called, with the ledPinLT pin.

In that function, you see if "now" minus "then" is greater than interval, without having set "then". That's the first problem.

Then, you would need to hold the switch pressed for more than 10 seconds to make the LED blink. A 10 second interval seems way too long to me. My turn signals flash far faster than that.

What kind of switches are you using? Japanese bikes typically have on/off switches for the turn signals. Turn the switch on to start the blinking; turn the switch off to stop the blinking. Harleys have momentary contact switches. Push once to start the blinking; push again to stop the blinking. Harleys, at least, stop the blinking automatically after a period of time, a distance, or a lean angle as occurred. are you planning to implement any of those features?

Yes I am using external pull up resistors. I will look over your suggestion on the code at what I overlooked. It is just a whole new way to code especially with doing the delay before. I will get it though it just takes some time to understanding the programming. The 10 second delay is something I missed and will change that, yes that's not good. My bike is a custom Japanese bike so the switches stay on.

Yes I plan on a few features but for now just want to get the core functions working and then build off of that. The main features I want to do are not illegal, I did my research before starting. Of coarse we talked about pulsing the headlight that is one feature and it can not according to Ohio law dim down to more than 17%. I also want to use the rear turn signals as brake lights(will change color for that) and turn signals in the front for small headlights or running lights(will change to white for that). These are just a small bit of what I want to do. Ohio law also states distance at which these should be visible and I will adhere to those laws also.

My bike is a custom Japanese bike so the switches stay on.

Then with the external resistors, the switches should be being read correctly (assuming that they are wired correctly, which I assume you have tested). It's likely, then, that the 10 second delay is the source of your problem, along with not setting the time when the switch is turned on (which requires that you detect a transition, which requires that you maintain a previous state variable).

I have been studying the code and I am lost. I see where the interval is set to 1000 but that is one second, not sure where the 10 sec problem is unless your are referring to a calculation and I am totally missing that too. Can you show me the trouble spots with out doing it for me?

Thanks,
Kevin

const long interval = 10000; // interval at which to blink (milliseconds)

That is ten seconds, not one second.

Ok got it! I have the delay figured out that PaulS was talking about. Just need tofigure out what elase is going wrong, still at a loss on it.

Thanks,
Kevin

Just need tofigure out what elase is going wrong, still at a loss on it.

Post your current code, and describe what problem(s) you are having.

As mentioned I got the interval figured out. I have have the brake light figured out and working except when the 10 flashes happen the transition between high and low is too fast and the led is very dim. Seems to need a interval in between high and low to let the led come to full brightness.

I still haven't figure out the turn signal code problem.

  /*

   Buttons Turn on and off LEDs connected to outputs 
 
   CIRCUIT:
   * LED attached from output pins to ground with current limiting resistor 
   * pushbuttons attached to input pins from ground with each pin having a 10k pull up resistor to positive
 
   */

  // constants won't change. They're used here to 
  // set pin numbers:
const int buttonPinLT = 2; // the number of the pushbutton pin
const int buttonPinRT = 3; // the number of the pushbutton pin
const int buttonPinBR = 4; // the number of the pushbutton pin
const int buttonPinHL = 5; // the number of the pushbutton pin

const int ledPinLT = 10;   // the number of the LED pin
const int ledPinRT = 11;   // the number of the LED pin
const int ledPinBR = 12;   // the number of the LED pin
const int ledPinHL = 13;   // the number of the LED pin


  //variables for turn signals  Note: This assumes that only one turn signal can be turned on at a time.
long previousMillis = 0;
int ledState = LOW;               // ledState used to set the LED
const long interval = 100;        // interval for Button delay (milliseconds)

  //variables for brake signal
long previousMillisBR = 0;
int ledStateBR = LOW;             // ledState used to set the LED
const long intervalBR = 100;      // interval at which to blink (milliseconds)
int blinkCount = 0;               // keeps track of the number of times that the brake light has blinked


void setup() 
{ 
  // initialize the LED pins as an output:
  pinMode(ledPinLT, OUTPUT);
  pinMode(ledPinRT, OUTPUT);
  pinMode(ledPinBR, OUTPUT);
  pinMode(ledPinHL, OUTPUT);

  // initialize the pushbutton pins as an input:
  pinMode(buttonPinLT, INPUT);
  pinMode(buttonPinRT, INPUT);
  pinMode(buttonPinBR, INPUT);
  pinMode(buttonPinHL, INPUT);
}


void loop()
{ 
  //Process the left button
  if (digitalRead(buttonPinLT) == LOW)
    TurnOn(ledPinLT);
  else
    TurnOff(ledPinLT);

  //Process the right button
  if (digitalRead(buttonPinRT) == LOW)
    TurnOn(ledPinRT);
  else
    TurnOff(ledPinRT);

  //Process the break
  if (digitalRead(buttonPinBR) == LOW)
    TurnOnBrake(ledPinBR);
  else
    TurnOffBrake(ledPinBR);
}


void TurnOn(int led)
{
  // check to see if it's time to blink the LED; that is, if the 
  // difference between the current time and last time you blinked 
  // the LED is bigger than the interval at which you want to 
  // blink the LED.

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) 
{
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(led, ledState);
}
}


void TurnOff(int led)
{
  digitalWrite(led, LOW); // set the LED off

  // Reset the variables that control the blinking
  previousMillis = 0;
  ledState = LOW;
}


void TurnOnBrake(int led)
{
  //Since we only want the light to blink 10 times, keep track of the number of blinks
  if (blinkCount < 10)
{
    unsigned long currentMillisBR = millis();

    if(currentMillisBR - previousMillisBR > intervalBR) 
{
      // save the last time you blinked the LED 
      previousMillisBR = currentMillisBR;

      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW)
        ledState = HIGH;
        blinkCount++;
}
      else
        ledState = LOW;

      // set the LED with the ledState of the variable:
      digitalWrite(led, ledState);
}

      //The last time thru the above loop, the brake will be turned on and will stay on.

}

void TurnOffBrake(int led)
{
      digitalWrite(led, LOW); // set the LED off

      // Reset the variables that control the blinking
        blinkCount = 0;
        previousMillisBR = 0;
        ledStateBR = LOW;
}

Needed to add a couple curly braces I think. I put them where I think they probably should go. Have a look and give it a try:
(also, if you format by Ctrl + T it will indent it properly, and it may be easier to notice missing braces ect.)

void TurnOnBrake(int led)
{
  //Since we only want the light to blink 10 times, keep track of the number of blinks
  if (blinkCount < 10)
  {
    unsigned long currentMillisBR = millis();

    if(currentMillisBR - previousMillisBR > intervalBR) 
    {
      // save the last time you blinked the LED 
      previousMillisBR = currentMillisBR;

      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {  //  <===================== added curly brace
        ledState = HIGH;
        blinkCount++;
      }
      else
        ledState = LOW;

      // set the LED with the ledState of the variable:
      digitalWrite(led, ledState);
    } 
  }  // <================================== added curly brace

    //The last time thru the above loop, the brake will be turned on and will stay on.

}

John_S,

That did it for the brake light problem! Thanks, I originally had a couple in the wrong place and it wouldn't work. These brackets are confusing!

Kevin

Matter of personal preference and style, but if you always add the braces, regardless of need, things will probably work out better for you!

if ( ... )
{
 ...
}

for ( ; ; )
{
 ...
}

while ( ... )
{
}

do
{
 ...
} while (... );

It's hard to go wrong doing this.

  //Process the left button
  if (digitalRead(buttonPinLT) == LOW)
    TurnOn(ledPinLT);
  else
    TurnOff(ledPinLT);

You are still not detecting transitions. You MUST keep track of the previous state of the switches, and only do some thing when the state changes.

int prevLTState = HIGH;
int currLTState;

void loop()
{
   currLTState = digitalRead(buttonPinLT);
   if(currLTState != prevLTState)
   {
      // A transition occurred
      if(currLTState == LOW)
      {
         // ... to pressed
         TurnOn(ledPinLT);
      }
      else
      {
         // ... to released
         TurnOff(ledPinLT);
      }
   }
   prevLTState = currLTState;
}

Some of your function names could use improvement. TurnOn() should be startBlinking(). TurnOff() should be stopBlinking().

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

can be simplified:

   ledState = !ledState;

The less code you write, the less places for errors to creep in.

Sorry, I'm not getting what you mean on the state changes. I do have the brake working fully now and I put seperate blink code for each turn signal and it now works. I was getting tripped up try to use the same code for both.

Yes changing the function names is a great idea and I will do that to make it more clear.

Sorry, I'm not getting what you mean on the state changes.

You don't want to start the turn signal blinking on every pass through loop if the switch is pressed. You only want to start the turn signal blinking once when the switch is pressed but was not pressed last time.

That is either done by detecting a transition (to pressed) or by setting a flag that lets the blinker function know that it is to carry on blinking, rather than start blinking.

In my mind, detecting the transition is easier to understand and implement.

This is cool. Here's something I have been working on for a roadwork vehicle that makes frequent stops on a highway median.
I already have the amber turn signals and white reverse LED's strobing in a specific pattern that are being handled by a separate sketch in a separate ATtiny85 circuit with the turn signal switch, and hazard button.

The brake lights are still Off, Dim, or Bright and controlled by the attached sketch. I decided to use a Arduino for the brake lights for a couple reasons.

  1. The LED's I am using aren't designed to dim, but will with the Arduino.
  2. I wanted to use Arduino to expand the functionality of the brake lights in the future.

I have read and attempted to utilize your final code within the attached code, but failed. Either it does nothing, throws errors, or strobes continuously.

Keep in mind, what I am asking for help with does not involve the turn signals or reverse lights. Only 1 analog output for the brake LED allthough you may notice I am using 2 outputs. 1 for each side of the truck. This is also for future enhancements, but for now, I want the both to mirror each other.

// Brake Light control with driving light dimming and debouncing

// constants won't change. They're used here to 
// set pin numbers:
const int BUTTONpin = 12;         // the number of the pushbutton pin
const int SWITCHpin = 7;          // the number of the pushSWITCH pin

// Variables will change:
int pwr = 0;
int BUTTONstate;                  // the current BUTTONreading from the input pin
int lastBUTTONstate = LOW;        // the previous BUTTONreading from the input pin
long lastBUTTONDebounceTime = 0;  // the last time the output pin was toggled

int SWITCHstate;                  // the current SWITCHreading from the input pin
int lastSWITCHstate = LOW;        // the previous SWITCHreading from the input pin
long lastSWITCHDebounceTime = 0;  // the last time the output pin was toggled

long debounceDelay = 50;          // the debounce time; increase if the output flickers

void setup() {
  pinMode(BUTTONpin, INPUT);
  pinMode(SWITCHpin, INPUT);
}

void loop()
{
  getSWITCHreading();
  getBUTTONreading();
  
  //SWITCHstate is the current state of the SWITCH
  //BUTTONstate is the current state of the BUTTON
  
  if(SWITCHstate==1)     //if SWITCH is on
  {
    if(BUTTONstate == 1) //if BUTTON is pressed
    {
      analogWrite(10, 255);
      analogWrite(11, 255);
    }
    else //if BUTTON not pressed
    {
      analogWrite(10, 60);
      analogWrite(11, 60);
    }
  }
  else //SWITCHstate=LOW //if SWITCH is off
  {
    if(BUTTONstate == 1) //if BUTTON is pressed
    {
      analogWrite(10, 255);
      analogWrite(11, 255);
    }
    else //if BUTTON not pressed
    {
      analogWrite(10, 0);
      analogWrite(11, 0);
    }
  }
}

//Debouncing stuff...

void getSWITCHreading()
{
  // read the state of the switch into a local variable:
  int SWITCHreading = digitalRead(SWITCHpin);
  
  // check to see if you just pressed the SWITCH 
  // (i.e. the input went from LOW to HIGH),  and you've waited 
  // long enough since the last press to ignore any noise:  

  // If the switch changed, due to noise or pressing:
  if (SWITCHreading != lastSWITCHstate) {
    // reset the debouncing timer
    lastSWITCHDebounceTime = millis();
  } 
  
  if ((millis() - lastSWITCHDebounceTime) > debounceDelay) {
    // whatever the SWITCHreading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:
    SWITCHstate = SWITCHreading;
  }
  
  // save the SWITCHreading.  Next time through the loop,
  // it'll be the lastSWITCHstate:
  lastSWITCHstate = SWITCHreading;
}

void getBUTTONreading()
{
  // read the state of the switch into a local variable:
  int BUTTONreading = digitalRead(BUTTONpin);
  

  // check to see if you just pressed the button 
  // (i.e. the input went from LOW to HIGH),  and you've waited 
  // long enough since the last press to ignore any noise:  

  // If the switch changed, due to noise or pressing:
  if (BUTTONreading != lastBUTTONstate) {
    // reset the debouncing timer
    lastBUTTONDebounceTime = millis();
  } 
  
  if ((millis() - lastBUTTONDebounceTime) > debounceDelay) {
    // whatever the BUTTONreading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:
    BUTTONstate = BUTTONreading;
  }

  // save the BUTTONreading.  Next time through the loop,
  // it'll be the lastBUTTONstate:
  lastBUTTONstate = BUTTONreading;
  
}

How can I make the brake light flash 3 times in rapid succession (120MS total / 20MS per on/off) before remaining solid until the brake (button) is released regardless if the running lights (Switch) is on or off?