To whom it may concern: An example how to use the modulus operator for making something go periodically on/off, with duty cycle and frequency of your choice. Not for critical timing functions, but for slow stuff I think it's good.
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(millis()%60000<10000); // you chose duty cycle and period; example 10s HIGH and 50s LOW during the 60s period
delay(1000);
}
gcjr:
have you considered
if (! (millis() % N)
hmm, I think you risk missing the 'millis' count where the modulus result is zero. You also have no control over duty cycle.
The '%' operator is computationally expensive compared with the standard comparison and increment. It's taking a step backwards.
just ran this piece of code:
uint32_t nowMillis;
uint32_t prevMillis;
boolean thing;
void loop() {
// put your main code here, to run repeatedly:
prevMillis=micros();
thing=millis()%60000<10000; // you chose duty cycle and period; example 10s HIGH and 50s LOW during the 60s period
nowMillis=micros();
Serial.println("modulus operator took " + String(nowMillis-prevMillis) + " micro-seconds to compute");
Serial.println("thing state: " + String(thing));
delay(1000);
}
result from the serial monitor:
modulus operator took 2 micro-seconds to compute
thing state: 1
modulus operator took 2 micro-seconds to compute
thing state: 1
modulus operator took 2 micro-seconds to compute
thing state: 0
modulus operator took 2 micro-seconds to compute
thing state: 0
modulus operator took 2 micro-seconds to compute
thing state: 0
modulus operator took 2 micro-seconds to compute
thing state: 0
modulus operator took 2 micro-seconds to compute
thing state: 0
modulus operator took 2 micro-seconds to compute
When the code is much more elegant and compact than comparison and increment solution, who cares about 2 micro-seconds?