How to print on LCD once under void loop

Hello, for my next arduino project I have been trying to figure out how to use the LCD display. The problem is that whenever I would print something under the void loop(), it would print the string multiple times and I would like to know how to print the string only once under the loop.

void loop() {
static byte first = 1;
if (first) {
   print_on_lcd();
   first = 0;
  }
 ...

Another option is to print something in setup(), which will happen only once.

Your loop() function should run hundreds or thousands of times a second. There is absolutely no need to print to the LCD every time through loop(). A couple times a second should be sufficient. Humans can't really read any faster than that, anyway.

// hd44780 library see https://github.com/duinoWitchery/hd44780
// thehd44780 library is available through the IDE library manager
#include <Wire.h>
#include <hd44780.h>                       // main hd44780 header
#include <hd44780ioClass/hd44780_I2Cexp.h> // i2c expander i/o class header

hd44780_I2Cexp lcd; // declare lcd object: auto locate & auto config expander chip

// LCD geometry
const int LCD_COLS = 16;
const int LCD_ROWS = 2;

void setup()
{
   lcd.begin(LCD_COLS, LCD_ROWS);
   lcd.clear();
   lcd.print("Hello World");
   lcd.setCursor(0, 1);
   lcd.print("Millis ");  // label is permanent
}

void loop()
{
   updateLCD();
}

void updateLCD()
{
   static unsigned long lcdTimer = 0;
   unsigned long lcdInterval = 500; // update the LCD 2 times a second
   if (millis() - lcdTimer >= lcdInterval)
   {
      lcdTimer = millis();
      lcd.setCursor(8, 1);
      lcd.print("       "); // overwrite old data
      lcd.setCursor(8, 1);  // reset the cursor
      lcd.print(millis());
   }
}

Even better is to only print to the LCD when the information to be printed changes in order to minimize accessing the slow LCD.

Do not use the clear() function in your loop(), it is very time consuming. Overwrite data on the LCD with spaces and/or the new data.

your code is strange.
error 1:

error 2

even if not static this variable will be always 1 and

if (first) {

will run always too.

Suggestion: try the code before making a fool of yourself.

This code prints "test" once:

void setup() {
Serial.begin(9600);
}

void loop() {
static byte first=1;
if (first) {
  Serial.println("test");
  first = 0;
}
}

it is no need to set the variable as static in comparison to normal global variable definition

bool first = true;
void loop() {
  if (first) {
    Serial.println("test");
    first = false;
  }
}

Glad you learned something, and you are welcome!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.