im trying to write a program to make the LED blink according to the delay given by the user (in
milliseconds) through Serial input screen and at every 10 second interval the program
should update the Serial output screen with the current delay of the LED.
My code is as follows :-
int led=13;
int timedelay;
String readString;
int n;
long int delayy=1000;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
while (Serial.available())
{
char c = Serial.read();
readString += c;
delay(2);
}
if (readString.length() >0)
{
int n = readString.toInt();
}
digitalWrite(led ,HIGH);
delay(readString.toInt());
digitalWrite(led ,LOW);
delay(readString.toInt());
unsigned long int loopTime = millis() - delayy;
if (loopTime >= 10000 && loopTime <= 11500)
{
Serial.println(readString.toInt());
}
else
{
}
}
My problem is that the program doesn't print the delay value every 10 seconds . I don't know where i am going wrong.
My problem is that the program doesn't print the delay value every 10 seconds . I don't know where i am going wrong.
Maybe if you printed out loopTime (a dumb name), a clue by four would whack you.
You are setting "loopTime" to the run time one second ago and then checking to see if it is between 10 and 11.5 seconds. That will be true only between 11 and 12.5 seconds after the sketch starts.
Typically to do something periodically you keep track of the last time it happened and when millis() minus theLastTimeItHappened is greater than the desired interval, it's time to do that thing again:
static unsigned long lastTimeItHappened = 0;
if (millis() - lastTimeItHappened >= 10000) { // Ten seconds or more since it last happened
lastTimeItHappened = millis();
// DO IT HERE
}
Don't use delay() for timing. Have a look at how millis() is used to manage timing in several things at a time.
You may also be interested in serial input basics.
...R
In this code fragment:
if (readString.length() >0)
{
int n = readString.toInt();
}
you do not use n for anything, so why bother defining it?
Also, to make sure the compiler converts constants correctly, statements like:
if (loopTime >= 10000 && loopTime <= 11500)
should use explicit type modifiers, like:
if (loopTime >= 10000UL && loopTime <= 11500UL)
otherwise they are compiled as ints.