i need to make an led stay on for 1 second at a regular interval of one second using the millis(); function
here is the code i have
const int ledPin = 13;
int ledState = LOW;
long previousMillis = 0;
long interval = 1000;
long space = 3000;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop()
{
unsigned long currentMillis = millis(); // Store the current time
Serial.println(currentMillis);
if(currentMillis - previousMillis > interval && currentMillis - previousMillis + 1000 < space) {
// save the last time you blinked the LED
previousMillis = currentMillis; // move current time into previous time
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin,LOW);
}
}
the led needs to stay on when the time is between 1000 millis and 2000 millis. i need to use this code in another project when i con get it going
I think you've got a few problems, but the most immediate is that the way you have written the code, the LED will only go high for a cycle of the loop, before immediately being set to LOW the next time through the loop.
The
digitalWrite(ledPin,LOW);
also needs a millis() time guard around it. Only set it LOW after the LED has been on for the time interval you want.
semi-messy example of real time principles at work.
this blinks and watches for user single digit input through serial monitor.
working example:
const byte ledPin = 13;
byte ledState = LOW;
unsigned long previousMillis, currentMillis, waitMillis = 1000;
unsigned long markMillis = 1000, spaceMillis = 2000;
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin( 115200 ); // make sure that serial monitor is set to 115200 baud
Serial.println( "\n\n Enter 1 - 9 to change the blink speed/restart blink" );
Serial.println( " Enter 0 to stop blink\n" );
}
inline void blink()
{
currentMillis = millis(); // Store the current time
if ( waitMillis > 0 )
{
if(currentMillis - previousMillis >= waitMillis)
{
previousMillis += waitMillis; // start time corrected if late
ledState = !ledState;
if ( ledState )
{
waitMillis = markMillis; // led will be on for mark time
}
else
{
waitMillis = spaceMillis; // led will be off for space time
}
// save the last time you blinked the LED
digitalWrite(ledPin, ledState);
}
}
}
inline void usrKey() // read one digit and set blink on time
{
static char ch;
if ( Serial.available()) // this part is for you to figure out
{
ch = Serial.read();
Serial.println( ch );
if ( ch >= '1' && ch <= '9' )
{
markMillis = waitMillis = (unsigned long) ( ch - '0' + 1 ) * 100UL;
spaceMillis = 2UL * markMillis;
}
else if ( ch == '0' )
{
waitMillis = 0UL; // 0 makes 0% stop
}
}
}
void loop()
{
usrKey();
blink();
}