Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass variable to const char type?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading