gpt4 book ai didi

c - 将 uint16_t var 打印到 4 个位置的函数将不起作用

转载 作者:行者123 更新时间:2023-11-30 21:08:06 26 4
gpt4 key购买 nike

平台:ESP8266 和 Arduino

我正在尝试在 4 个字符的位置输出 uint16_t 。激光器(VL53L0X)正在从 2 到 4 个数字位置读取数据。(永远不会超过 4 个位置,MAX 8190 输出)

Serial.print( mmLaser);

可以工作,但无法格式化这 4 个位置。
如果我调用该函数,我会收到错误

**ERROR:** invalid conversion from 'char' to 'char*' [-fpermissive]

如果我编译而不调用该函数:没有错误

我做错了什么?

声明的变量

char  c_temp;
uint16_t mmLaser = 0; // hold laser reading

调用的函数

uint16_2_char( mmLaser, c_temp); 
Serial.print( c_temp );

函数

// Convert uint16_t to char*
// param 1 n - uint16_t Number
// param 2 c - char to return char value to
//
void uint16_2_char(uint16_t n, char* c){
sprintf( c, "%04d", (int) n );
}

最佳答案

代码需要一个字符数组

//       Pointer to a character -----v                            
void uint16_2_char(uint16_t n, char* c){
sprintf( c, "%04d", (int) n );
}

问题代码

//     This is one character
char c_temp;

uint16_t mmLaser = 0; // hold laser reading

// **ERROR:** invalid conversion from 'char' to 'char*'
// Does not make sense to pass a character when an address is needed
// Need to pass the initial _address_ as an array of characters instead.
// v
uint16_2_char( mmLaser, c_temp);

更好的代码

#define INT_BUF_SIZE 24 
char buffer[INT_BUF_SIZE];

// When an array is passed to a function,
// it is converted to the address of the 1st character of the array.
// The function receives &buffer[0]
uint16_2_char( mmLaser, buffer);

更好的是,传递一个地址和可用的大小

void uint16_2_char(uint16_t n, char* c, size_t sz){
unsigned u = n;
// I'd expect using unsigned types. (use `%u`)
// snprintf() will not not overfill the buffer
snprintf( c, sz, "%04u", u);
}

char buffer2[INT_BUF_SIZE];
uint16_2_char2( mmLaser, buffer, sizeof buffer);

关于c - 将 uint16_t var 打印到 4 个位置的函数将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com