平台: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/

10-10 11:24