I have what I hope is a very simple problem. Take the following script. For now all I want it to do is blink the LED ten times with a ten second interval between blinks, then five times with a five second interval. What actually happens is that the first for loop is ignored and the LED blinks every five seconds. Ocassionally, if left switched off for a long time its the second for loop thats ignored. :-? What on Earth is going on/am I doing wrong? The board is a Dieci btw. Many thanks.
int trigger = 13; // device connected to digital pin 13
int tenSec = 10000; // 10 second interval
int fiveSec = 5000; // 5 second interval
long previousMillis = 0; // variable to store last time trigger was fired
int i; // variable i
void setup()
{
pinMode(trigger, OUTPUT); // sets the digital pin as output
}
void loop()
{
for (i=0; i<10; i++) { // test to see if i is less than 10, if not increments i by 1
if (millis() - previousMillis >= tenSec) { // check to see if 10 secs has passed
previousMillis = millis(); // remember previous time
digitalWrite(trigger, HIGH); // sets the trigger to on
delay(1000); // wait for a second
digitalWrite(trigger, LOW); // sets the trigger to off
}
}
for (i=0; i<5; i++) {
if (millis() - previousMillis >= fiveSec) {
previousMillis = millis();
digitalWrite(trigger, HIGH);
delay(1000);
digitalWrite(trigger, LOW);
void loop()
{
int i = 0;
while(i<10) { // test to see if i is less than 10, if not increments i by 1
if (millis() - previousMillis >= tenSec) { // check to see if 10 secs has passed
previousMillis = millis(); // remember previous time
digitalWrite(trigger, HIGH); // sets the trigger to on
delay(1000); // wait for a second
digitalWrite(trigger, LOW); // sets the trigger to off
i++;
}
}
i = 0;
while(i<5) {
if (millis() - previousMillis >= fiveSec) {
previousMillis = millis();
digitalWrite(trigger, HIGH);
delay(1000);
digitalWrite(trigger, LOW);
i++;
}
}
}
but why not just use delay() instead of millis()
void loop()
{
for (i=0; i<10; i++) { // test to see if i is less than 10, if not increments i by 1
digitalWrite(trigger, HIGH); // sets the trigger to on
delay(1000); // wait for a second
digitalWrite(trigger, LOW); // sets the trigger to off
delay( tenSec);
}
for (i=0; i<5; i++) {
digitalWrite(trigger, HIGH);
delay(1000);
digitalWrite(trigger, LOW);
delay( fiveSec) ;
}
}
Not sure that helps. millis() will be 0 when the sketch starts anyway. The problem is that the for loop will iterate from 0 to 9 in a fraction of a millisecond so the
if (millis() - previousMillis >= tenSec)
test is never true.
Don't want to use delay as in the future the intervals will be much longer and other devices will be connected to the board doing their thing, and data logging, during the intervals. Providing i can learn how to do it all.
I like this forum. People can post basic questions and not be made to feel like an idiot. A refreshing change!