平台:ESP8266和Arduino
我正在尝试在4个字符位置输出uint16_t
。激光(VL53L0X)正在读取2到4个数字位置。(永远不会超过4个位置,MAX 8190输出)
Serial.print( mmLaser);
有效,但不能格式化4个地方 如果我调用该函数我会收到错误
**ERROR:** invalid conversion from 'char' to 'char*' [-fpermissive]
如果我在没有调用函数的情况下编译:没有错误
我做错了什么?
声明Vars
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 );
}
答案 0 :(得分:0)
代码需要一个字符数组
// 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);