简体   繁体   English

STM32 CDC_Transmit_FS:为什么在使用 sprintf() 或 strcat() 时会出现 '\\x'?

[英]STM32 CDC_Transmit_FS: why does '\x' appear when using sprintf() or strcat()?

I am trying to send values from ADC through USB using "CDC_Transmit_FS()"我正在尝试使用“CDC_Transmit_FS()”通过 USB 从 ADC 发送值

On the receiving side, I am receiving data using readline() and decoding the 'string' to 'int'在接收端,我使用 readline() 接收数据并将“字符串”解码为“int”

The code works fine but occasionally I receive for example, b'\\x00234\\n' instead of b'1234\\n', which raises decoding error.该代码工作正常,但有时我会收到例如 b'\\x00234\\n' 而不是 b'1234\\n',这会引发解码错误。

Do you know why does '\\x' appear?你知道为什么会出现'\\x'吗?

One more question is: Is there any smarter method to send ADC values through USB instead of converting int values to string?还有一个问题是:有没有更聪明的方法可以通过 USB 发送 ADC 值而不是将 int 值转换为字符串?

I want to make the transmission faster.我想让传输更快。 thanks in advance!提前致谢!

uint32_t adcbuff[sample];
char endofpacket[5] = {'9', '9', '9', '9', '\n'};
char txbuff[sample*5];

while(1)
{

    HAL_ADC_Start_DMA(&hadc2,(uint32_t*)adcbuff, sample);

    for(i = 0; i < sample; i++)
    {
     sprintf (tempbuff,  "%u\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000); 
     strcat( txbuff,tempbuff);
    }
        
    strcat( txbuff,endofpacket);
    CDC_Transmit_FS( (uint8_t*)txbuff, strlen(txbuff));  
    strcpy(txtbuff,"");

}

not enough rep to post as a comment没有足够的代表发表评论

Usually \\x is an indication of a hexadecimal value.通常\\x是十六进制值的指示。 Could it be that a non alphanumeric value is being received?是否会收到非字母数字值? For troubleshooting, I would temporarily change对于故障排除,我会暂时改变

sprintf (tempbuff, "%u\\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000); to

sprintf (tempbuff, "%s\\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000); to see what kind of characters are being sent over.看看什么样的字符被发送过来。 (Maybe sprintf to a tmp file instead.) (也许 sprintf 改为 tmp 文件。)

b' \\x00 234\\n' - This means that first byte is 0! b' \\x00 234\\n' - 这意味着第一个字节是 0! Not ASCII 0 = 0x30, but just 0. Probably this is effect of strcat - after concatenating this function adds '\\0' at the end of string.不是 ASCII 0 = 0x30,而是 0。这可能是 strcat 的影响 - 连接此函数后在字符串末尾添加 '\\0' 。

Instead of using sprintf, just redirect stdout to USB-CDC and use printf:不使用 sprintf,只需将 stdout 重定向到 USB-CDC 并使用 printf:

int _write(int file, char *ptr, int len)
{
    UNUSED(file);
    CDC_Transmit_FS((uint8_t*)ptr, len);
    while (hcdc->TxState != 0);
    return len;
}

If you want to send all at once use setvbuf for stdout with _IOFBF and call fflush(stdout);如果您想一次发送所有内容,请使用setvbuf for stdout with _IOFBF 并调用 fflush(stdout);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM