Jay Blanchard
Jay Blanchard

Reputation: 34426

Understanding millis() in digitalWrite()

I have been doing a lot more Arduino programming, especially going back to things I have done before and getting rid of delay() where I can. I ran across an interesting post having the following code to "flash" an LED:

digitalWrite(strobe1, (millis() % 1000L) < 500L);

I read the math as (current milliseconds modulo 1000) < 500 and this math seems to "flash" the LED. What I don't quite understand is why? The math doesn't seem to be a test (result of mod is less than 500) but does set the pin HIGH for whatever is being calculated here.

I have been searching the web to try and understand what is going on here, but cannot find anything explicit. Can someone explain?

Upvotes: 0

Views: 443

Answers (1)

tkausl
tkausl

Reputation: 14279

I read the math as (current milliseconds modulo 1000) < 500

Thats correct.

What I don't quite understand is why? The math doesn't seem to be a test

I don't really understand your statement. (millis() % 1000L) < 500L is a test, it tests whether millis() % 1000L is less than 500 or not and results in either true, which is equivalent to 1 or false, which is equivalent to 0.

So, half of a second, the condition is false -> 0 gets written, and the other half of a second it's true, 1 gets written.

I guess I am used to seeing the test being more explicit, like if((millis() % 1000L) < 500). So this is a ternary function?

No, not at all a ternary, neither a if. You need to understand what a logical/boolean expression is and results in. Lets break it down a bit:

 bool result = (millis() % 1000L) < 500L;

It should be clear what this line does: It checks whether the result of millis() % 1000L is less than 500 and stores the resulting boolean in result. A boolean is nothing more than true or false. A value. A value like 1, 34561 or "hello world". Of course, you can use the value as a conditional in a if statement like this:

if(result) { /* some code */ } else { /* more code */ }

But you don't need to. Because its just a value, where true is the same as 1 and false is the same as 0, you can pass this boolean which implicitly decays to the corresponding integer (it always was a integer to begin with) to a function which expects a HIGH (1) or a LOW (0). You could also think of the digitalWrite function as if it would take in a bool instead of the logical 1 or 0, the result would be the same.

Upvotes: 3

Related Questions