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

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

问题描述

什么是发送浮动的最佳方式双击 INT16 在上Arduino的串口?

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

Serial.print()只发送值的 ASCII EN codeD。但是,我要发送的值作为字节。 Serial.write()字节接受和ByteArrays的,但什么是将值转换为字节的最好方法?

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 字节* ,没有运气。我也用的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()是,海事组织,做这种转换最方便的方式:

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 我忘了,对于整数 / 多头,该函数的输入参数要成为无符号。同样对于格式字符串传递给的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;
}

和对花车和双打相似。在code做转换已经提前知道。它被告知 - 什么样的它的转换实体,所以你可能最终与功能的char * float2str(浮点float_num)的char * dbl2str(双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).

您会得到一个NULL结尾的左调整(没有前导空格或零)字符串出了转换。

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天全站免登陆