我使用PlatformIO和arduino-framework = arduino来开发ESP32代码,并使用Serial.printf进行调试,如下所示:
int64_t test_val = 12345;
Serial0.printf("ADC millivolts value = %d , tim:%d \n",analogVolts,test_val);
我发现第二个%d没有正确输出,结果是这样的(实际上是tim=12345) :
ADC millivolts value = 31 , tim:3
所以,我使用下面的代码做了一些测试:
int analogVolts = analogReadMilliVolts(1);
int64_t test_val = 12345;
Serial0.printf("ADC millivolts value = %d , tim:%d \n",analogVolts,test_val);
Serial0.printf("Test-d:%d, %d, %d, %d, %d, %d, %d, %d \n",
test_val,test_val,test_val,test_val,
test_val,test_val,test_val,test_val);
Serial0.printf("Test-ld:%ld, %ld, %ld, %ld, %ld, %ld, %ld, %ld \n \n",
test_val,test_val,test_val,test_val,
test_val,test_val,test_val,test_val);
运行这些测试代码的结果是:
ADC millivolts value = 32 , tim:3
Test-d:12345, 0, 12345, 0, 12345, 0, 12345, 0
Test-ld:12345, 0, 12345, 0, 12345, 0, 12345, 0
其他一些信息:
Visual Studio Code: V1.79.0
PlatformIO: Core 6.1.13·Home 3.4.4
Platforms: Espressif 32 v6.5.0
platformio.ini:
[env:adafruit_feather_esp32s3]
platform = espressif32
board = adafruit_feather_esp32s3
framework = arduino
board_build.f_cpu = 240000000L
board_build.f_flash = 80000000L
upload_speed = 921600
monitor_speed=921600
lib_deps = adafruit/Adafruit NeoPixel@^1.12.0
文件
size_t Print::printf(const char *format, ...)
第 47 行有关于 C:\Users\UserName\.platformio\packages\framework-arduinoespressif32\cores\esp32\Print.cpp
的函数:
size_t Print::printf(const char *format, ...)
{
char loc_buf[64];
char * temp = loc_buf;
va_list arg;
va_list copy;
va_start(arg, format);
va_copy(copy, arg);
int len = vsnprintf(temp, sizeof(loc_buf), format, copy);
va_end(copy);
if(len < 0) {
va_end(arg);
return 0;
}
if(len >= (int)sizeof(loc_buf)){ // comparation of same sign type for the compiler
temp = (char*) malloc(len+1);
if(temp == NULL) {
va_end(arg);
return 0;
}
len = vsnprintf(temp, len+1, format, arg);
}
va_end(arg);
len = write((uint8_t*)temp, len);
if(temp != loc_buf){
free(temp);
}
return len;
}
在这种情况下,您使用了错误的长度说明符。
%d
期望打印 int
和 unsigned int
类型的数据,在 ESP32 上长度为 32 位。
您的数据类型是
int64_t
,长度为 64 位。由于在 ESP32(以及许多其他平台)上 int64_t
是 long long int
的别名,因此 quick 解决方案是使用其长度说明符 lld
而不是 d
:
int64_t test_val = 12345;
Serial0.printf("ADC millivolts value = %d , tim:%lld \n",analogVolts,test_val);
请注意,标准库添加了 macros ,它会自动替换
int64_t
的正确长度(以及具有定义长度的其他类型)。所以portable解决方案是使用长度说明符PRId64
:
int64_t test_val = 12345;
Serial0.printf("ADC millivolts value = %d , tim:" %PRId64 "\n",analogVolts,test_val);