I have a simple sketch here that should just blink a led once a second or so (approximately):
boolean onOff=true;
int count=0;
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
count++;
delay(1);
if (count == 316) {
onOff=!onOff;
digitalWrite(13, onOff);
count=0;
}
}
So, if count
is 316 it changes the state of led. It works right now, but it does not without delay()
function or some other complex ones like digitalWrite()
being in the loop()
too. If i am deleting delay()
, than led is just always on. I can feel it is smth about interrupts, but i am not sure.
What am i trying to do here is to make an alternative to delay()
and millis()
for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses long
variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing. So, the questions are:
- Why does my sketch works only with delay(), but does not work without it?
- Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
- Am i a bad person for trying to make smth like an ASAP timer?:) Is saved ram and cpu time worth of it? Any other possible problems?
- Can this sketch be workable without
delay()
or other complex or ram and cpu costly functions?
Thank you.
So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:
boolean onOff=1;
unsigned int counter=0;
unsigned long time=0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(57600);
}
void loop() {
if (counter==0) time=micros();
counter++;
if (counter == 0) {
onOff= !onOff;
digitalWrite(13, onOff);
Serial.println(micros()-time);
}
}
With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.
delay()
it is doing exactly what you tell it. It is blinking the LED - just far too fast for you to see. Try using values in the hundreds of millions instead of just a few hundred for your counter.