Home > front end >  How to pass variable to const char type?
How to pass variable to const char type?

Time:12-23

void printLCD(int col, int row , const char *str) {
    for(int i=0 ; i < strlen(str) ; i  ){
      lcd.setCursor(col i , row);
      lcd.print(str[i]);
    }
}

void loop(){
    lightAmount = analogRead(0);
    
    // Here
    printLCD(0, 0, printf("Light amount: %d", lightAmount ));
}

I'm newbie to c language for arduino project.

I want to show "Light Amount: 222" to LCD.

But 3rd parameter in printLCD function, it could receive string type only, so an error occurred.

How can I display variable and string together in above case?

CodePudding user response:

printf doesn't return the string, it prints it to a standard output which is not configured on most Arduinos by default.

You can use snprintf C function to format a string in Arduino sketch.

void printLCD(int col, int row , const char *str) {
  lcd.setCursor(col, row);
  lcd.print(str);
}

void loop(){
    lightAmount = analogRead(0);
    
    char str[17]; // for 16 positions of the LCD   terminating 0
    snprintf(str, sizeof(str), "Light amount:%d", lightAmount);
    printLCD(0, 0, str);

   delay(100);
}

Some LCD display libraries support print function for numbers. Then you can do

void loop(){
  lightAmount = analogRead(0);
    
  lcd.setCursor(0, 0);
  lcd.print("Light amount:");
  lcd.print(lightAmount);

  delay(100);
}
  • Related