如何通过串行发送浮点数

2022-01-18 00:00:00 c bytearray arduino serial-port c++

在 Arduino 上通过串行发送 floatdoubleint16 的最佳方式是什么?

What's the best way to send float, double, and int16 over serial on Arduino?

Serial.print() 仅以 ASCII 形式发送值编码.但我想将值作为字节发送.Serial.write() 接受字节和字节数组,但是将值转换为字节的最佳方法是什么?

The Serial.print() only sends values as ASCII encoded. But I want to send the values as bytes. Serial.write() accepts byte and bytearrays, but what's the best way to convert the values to bytes?

我尝试将 int16 转换为 byte*,但没有成功.我也使用了 memcpy,但它使用了许多 CPU 周期.Arduino 使用普通的 C/C++.这是一个 ATmega328 微控制器.

I tried to cast an int16 to an byte*, without luck. I also used memcpy, but that uses to many CPU cycles. Arduino uses plain C/C++. It's an ATmega328 microcontroller.

推荐答案

是的,要发送这些数字,您必须先将它们转换为 ASCII 字符串.如果您使用 C,sprintf() 是 IMO 进行此转换的最简便方法:

Yes, to send these numbers you have to first convert them to ASCII strings. If you are working with C, sprintf() is, IMO, the handiest way to do this conversion:

[稍后添加:AAAGHH!我忘记了对于 ints/longs,函数的输入参数需要无符号.对于传递给 sprintf() 的格式字符串也是如此.所以我在下面改了.很抱歉我的糟糕疏忽,这将是一个很难找到的错误.此外,ulong 使其更通用.]

[Added later: AAAGHH! I forgot that for ints/longs, the function's input argument wants to be unsigned. Likewise for the format string handed to sprintf(). So I changed it below. Sorry about my terrible oversight, which would have been a hard-to-find bug. Also, ulong makes it a little more general.]

char *
int2str( unsigned long num ) {
    static char retnum[21];       // Enough for 20 digits plus NUL from a 64-bit uint.
    sprintf( retnum, "%ul", num );
    return retnum;
}

浮点数和双精度数也类似.进行转换的代码是事先知道的.必须告诉它 - 它正在转换什么样的实体,所以你可能会得到函数 char *float2str(float float_num)char *dbl2str(double dblnum).

And similar for floats and doubles. The code doing the conversion has be known in advance. It has to be told - what kind of an entity it's converting, so you might end up with functions char *float2str( float float_num) and char *dbl2str( double dblnum).

您将从转换中得到一个以 NUL 结尾的左调整(没有前导空格或零)字符串.

You'll get a NUL-terminated left-adjusted (no leading blanks or zeroes) character string out of the conversion.

您可以在任何地方/任何您喜欢的方式进行转换;这些功能只是说明.

You can do the conversion anywhere/anyhow you like; these functions are just illustrations.

相关文章