What’s the best way to send float, double, and int16 over serial on Arduino?
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?
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.
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:[Added later: AAAGHH! I forgot that for
ints/longs, the function’s input argument wants to be unsigned. Likewise for the format string handed tosprintf(). So I changed it below. Sorry about my terrible oversight, which would have been a hard-to-find bug. Also,ulongmakes it a little more general.]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)andchar *dbl2str( double dblnum).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.