Simple Headlight Control Code

I’m thinking about making my car headlights turn on/off automatically for day/night with an additional 2 minute delay after I turn off the car. The code I made up seems pretty solid but would like someone else to look at it to be safe. I might have my sensor values and relay low/high values mixed around but i’m not worried about that till i bench test it. Just want to know if the code will work

// Example 07: Send to the computer the values read from 
// analogue input 0
// Make sure you click on "Serial Monitor"
// after you upload
//
// Copy and paste this example into an empty Arduino sketch

#define SENSOR 0  // select the input pin for the 
                  // sensor resistor

int val = 0; // variable to store the value coming
             // from the sensor
int relay = 12;
int ignition = 11;

void setup() {
  


 Serial.begin(9600); // open the serial port to send
                     // data back to the computer at
pinMode(relay, OUTPUT);                 // 9600 bits per second
pinMode(ignition, INPUT);
}

void loop() {
  
  if (digitalRead (ignition), HIGH) {
  
 { val = analogRead(SENSOR); // read the value from
                            // the sensor

  Serial.println(val); // print the value to
                       // the serial port

  delay(100); // wait 100ms between
              // each send  
 }
 
   if (analogRead(SENSOR) <500) {
     digitalWrite(relay, LOW);
     delay(120000);         //delay sensor readings to prevent headlight
   } else {                 //shut off at night from street lights, other cars..ect
     digitalWrite(relay, HIGH);
   }
  } else {
  delay(120000); //keep lights on 2 minutes after ignition off
  digitalWrite(relay, LOW);
  }
}

What's with the cross-posting?
What's with the cross-posting?

sorry haha, the website was taking forever to upload my thread so I had to reset the page and i guess it posted it twice

Putting such long delay of 120000 may not work…

try that instead

for (int i=0, i<120, i++){ // 120 times 1 second delay
delay(1000);
}

All the best.

I've used a 120000 millisecond delay before w/o issue on my uno rev 3 with a motion sensor lamp I made. Other than that how does the code look? I should probably put that first IF statement after the serial monitor command though I suppose?

Instead of using delay which essentially stops the microprocessor from running any further code you may wish to use a millis() function and allow the program to loop until the correct delay period has been reached

I presume your arduino has a number of inputs and outputs and you may wish to use these to do something else

If your microprocessor is only doing one thing then you may consider later you wish to get it to do something else and the delay function will not allow parallel operation until delay has completed the delay

well I know when I had my motion sensor lamp going, If you set off the motion sensor again, say a minute after setting it off the first time, it would start/reset the 2 minute cycle all over again before the first one ended . Idk, maybe that was a loop hole in my favor in the code i wrote. I've never used millis() before. Not quite sure how it works. I plan on also using an arduino as a PWM Controller with a POT for mosfets controlling something else entirely in the same vehicle. Would I be able to have the same arduino accomplish both tasks simultaneously?

Would I be able to have the same arduino accomplish both tasks simultaneously?

Very likely.

To use millis() to do timing you save the start time of an activity then check each time through loop() whether the required interval has passed. If so you respond to it and, if not, execute the rest of the code in loop(). Note that you can time several activities like this by saving different start times.

Alright so i believe this to be the code I need to control my mosfets. I am totally lost at integrating this code and the one from above together. I was somewhat of a noob but i haven't touched my arduino in months so i'm pretty much right back at square one. The codes I have come up with thus far are bits and pieces of code I put together from codes I implemented months ago in different projects

int sensorPin = A1;   
int mosfet = 9;      
int val = 0;  

void setup() {
  pinMode(mosfet, OUTPUT);  
}

void loop() {
  
  val = analogRead(sensorPin);
val = map(val,0, 1023, 0, 255); 
  
  analogWrite(mosfet, val);  
        
}

Before moving on you need to fix the original code  if (digitalRead (ignition), HIGH) This will probably work but it is wrong.

Once this is fixed change the program to use millis() for timing. The BlinkWithoutDelay example in the IDE and Gammon Forum : Electronics : Microprocessors : How to do multiple things at once ... like cook bacon and eggs will get you started nut feel free to ask for help here. Once the main program works using millis() you can set about integrating the second one which will be easy once loop() is free running and not blocked by delays.

Do I need one = or the ==? whats the difference between "const int" and just using "int" its kind of ridiculous that there are about a 100 different ways of accomplishing the same end result with arduino. Makes it very hard to learn

if (digitalRead (ignition), HIGH)should be if (digitalRead (ignition) == HIGH)
== does comparison = sets a variable to a value.

const int tells the compiler that the value will not change and it then stores it differently. It also spots and warns if your program tries to change the value in code.

There are often different ways to achieve the same thing, or nearly the same thing. The most important thing (IMO) is to write code that works consistently and does what you want. Then you can set about improving it. The use of delay() is a good example. Beginners need to see instant results from code changes and changing the value of the delay() argument fulfills this need. Then they (you) find out that using delay() has side effects if you want to do more complicated things so you research alternatives and they then become part of your armoury of tools.

Something that I meant to mention.
You could useif (digitalRead (ignition))because digitalRead() returns either HIGH or LOW which equate to true and false, but the explicit test is more readable.

So should I replace all my sketches using only "int" with "const int" for a more reliable sketch

and do all sketches using millis() use that "if(currentMillis - previousMillis > interval)"

wikitjuggla:
and do all sketches using millis() use that “if(currentMillis - previousMillis > interval)”

Yes. It means you don’t have to worry about issues with rollover of mills.

wikitjuggla:
So should I replace all my sketches using only "int" with "const int" for a more reliable sketch

const int is preferable where the following two things are true
1 - the value will not change
2 - an int is required. byte is preferable for smaller numbers

The program will not be more reliable either way.

UKHeliBob:
Before moving on you need to fix the original code if (digitalRead (ignition), HIGH)This will probably work but it is wrong.

Once this is fixed change the program to use millis() for timing. The BlinkWithoutDelay example in the IDE and Gammon Forum : Electronics : Microprocessors : How to do multiple things at once ... like cook bacon and eggs will get you started nut feel free to ask for help here. Once the main program works using millis() you can set about integrating the second one which will be easy once loop() is free running and not blocked by delays.

Well that gammon link is a lot easier for me to interpret than the blinkwithoutdelay example on the arduino website but, I still haven't a clue on how to implement that into my sketch or how to make it conditional to only happen and keep the lights on for 2 minutes after I turn off the ignition key. I spent a long time looking at it and I get the idea easily enough but just don't know how to implement it for anything else but...well, blinking an led

  if (digitalRead (ignition), HIGH) {

Have you fixed that line? Perhaps post your new code.

#define SENSOR 0  // select the input pin for the 
                  // sensor resistor

int val = 0; // variable to store the value coming
             // from the sensor
const int relay = 12;
const int ignition = 11;

void setup() {
  


 Serial.begin(9600); // open the serial port to send
                     // data back to the computer at
pinMode(relay, OUTPUT);                 // 9600 bits per second
pinMode(ignition, INPUT);
}

void loop() {
  
  
  
 { val = analogRead(SENSOR); // read the value from
                            // the sensor

  Serial.println(val); // print the value to
                       // the serial port

  delay(100); // wait 100ms between
              // each send  
 }
 
 if (digitalRead (ignition) == HIGH) {
 
   if (analogRead(SENSOR) <500) {
     digitalWrite(relay, LOW);
     delay(120000);         //delay sensor readings to prevent headlight
   } else {                 //shut off at night from street lights, other cars..ect
     digitalWrite(relay, HIGH);
   }
 } else {
  delay(120000); //keep lights on 2 minutes after ignition off
  digitalWrite(relay, LOW);
  }
}

Does that “delay(100)” after “serial.println” also need to be changed to millis() or is that a small enough of a delay that it won’t make a difference?