如何通过串行发送浮动 [英] How to send float over serial

查看:25
本文介绍了如何通过串行发送浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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.

这篇关于如何通过串行发送浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆