如何将变量传递给 const char 类型?

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 ));
}

我是 arduino 项目的 c 语言新手。

我想给 LCD 显示 "Light Amount: 222"

但是printLCD函数中的第3个参数,只能接收字符串类型,所以出错

如何在上述情况下同时显示变量和字符串?

printf 没有 return 字符串,它将它打印到标准输出,默认情况下大多数 Arduinos 上没有配置。

您可以使用 snprintf C 函数在 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);
}

一些 LCD 显示库支持 print 数字功能。那么你可以做

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

  delay(100);
}