How to make better screen update without delay

I need tu update screen like every half second or every second, but I can't use delay becuse other tinghs need to be working and that delay would make problems, I was using "millis();" for my timer but I can only get it to update every 1.2second. I am sure there is better way to make this becaise I am new to programmig and the code that I made does not look right, take a look and help if you can. :slight_smile:

void timer(){
second = millis();
refresh[0] = second - refresh[1];
if(refresh[0]==120){
    refresh[0]=0;
    refresh[1]=second;
    printScreen();
  }
}

Look at the BlinkWithoutDelay example that comes with the IDE. Why are you using array elements as variables? Please post all your code, not just a snippet.

If you need to refresh a screen every half second, then, depending on what other code is executed in your loop() function, the use of millis() , as in the Blink Without Delay sketch in your Examples folder, just will not cut it.

You would be better off looking at Timer interrupts. However, the subject requires much more depth to it than can adequately be addressed in a reply to your post, so I suggest that you do a Google search for Using Timer Interrupts with Arduino.

Good Luck with your project.

I do mine this way and quite easy, once set you can leave it to do the work. Quite easy to use

#include <TimedAction.h> // include this at the top of your code
//place this just before your setup code 
 void TimerService01();// LCD display routine
TimedAction Timedact01 = TimedAction(500, TimerService01);// mS update the LCD every .5 seconds

//Then place this in you main loop either at the beginning or the end of your code
 Timedact01.check();

//This is your function update the lcd 
void TimerService01() {
//Place your display code here
}

Give it a try

millis() should work for you.

void timer(){
second = millis();
refresh[0] = second - refresh[1];
if(refresh[0]==120){
    refresh[0]=0;
    refresh[1]=second;
    printScreen();
  }
}

Why set refresh[0] to 0? Is refresh[0] used elsewhere?
The "==" should be ">=".
Why do you call a variable "second" when it actually holds milliseconds?
I thought that you need to update the screen every half second or second, but this code gets executed every 120 milliseconds! (Although it may occasionally miss altogether because of the == ).
The millis() function works fine for me. What Arduino are you using? Have you modified it in some way?

I think you mean:

void updateScreen() {
unsigned long currentTime = millis();
static unsigned long previousTime = 0;
const unsigned long interval = 500;  // Every half second
if (currentTime - previousTime >= interval) {
    previousTime += interval;
    printScreen();
  }
}