Arduino:itoa打印201,sprintf打印99

时间:2017-03-16 04:53:11

标签: arduino byte percentage uint8t itoa

我在使用itoa()打印字节值(uint8_t)时遇到困难,需要打印一定百分比的音量。我想使用这个函数,因为它减少了二进制大小。

updateStats函数的两个版本(使用OLED_I2C库在OLED显示屏上打印统计数据:OLED显示屏(SDA,SCL,8);):

ITOA(不工作,PR:V:201%)

void updateStats()
{
  char buff[10]; //the ASCII of the integer will be stored in this char array
  memset(buff, 0, sizeof(buff));

  buff[0] = 'V';
  buff[1] = ':';

  itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent
  strcat( buff,"%" ); 

  display.print( getInputModeStr(), LEFT  , LINE3 );  
  display.print( buff, RIGHT , LINE3 );  
}

SPRINTF(作品预期,作品V:99%)

void updateStats()
{
  char buff[10]; //the ASCII of the integer will be stored in this char array
  memset(buff, 0, sizeof(buff));
  sprintf(buff, "V:%d%%", (uint8_t)getVolume() ); // get percent

  display.print( getInputModeStr(), LEFT  , LINE3 );  
  display.print( buff, RIGHT , LINE3 );  
}

问题

知道为什么itoa()函数打印错误的数字?任何解决方案如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

此行itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent错误。

当您想要在基数为10时,您要求基数为7的数字。

这是一个快速计算:

99÷7 = 14 r 1
14÷7 = 2 r 0
∴99 10 = 201 7

完整代码

更正的示例如下所示:

void updateStats()
{
  char buff[10]; //the ASCII of the integer will be stored in this char array
  memset(buff, 0, sizeof(buff));

  buff[0] = 'V';
  buff[1] = ':';

  itoa( (uint8_t)getVolume() ,&buff[2], 10 ); // get percent
  strcat( buff,"%" ); 

  display.print( getInputModeStr(), LEFT  , LINE3 );  
  display.print( buff, RIGHT , LINE3 );  
}
相关问题