If statement using millis function in Attiny 85 does not work as intended

Asked 2 years ago, Updated 2 years ago, 334 views

The if statement below should only be executed once every 100 milliseconds, but it is executed every 200 milliseconds and is processed twice.
What's wrong?

 if(millis()%100==0){...}

arduino

2022-11-06 02:00

1 Answers

The code literally works when you get the time in milliseconds and it's divisible by 100.Therefore, if the next time runs less than a millisecond after one split, it will continue to be a hit, and on the contrary, if you are unlucky, you may not be able to.

Therefore, if you want to implement it as intended, you need a code that records the last time you ran it, and then runs it again after more than 100 milliseconds.Here's the reference code.

static int last=0;

int now = millis();
if((now-last)>=100){
    last = now;
    // TODO: Write here what you want to do every 100 milliseconds
}

There is a high possibility that this code will not work as it is, so please rewrite it accordingly.


2022-11-06 02:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.