How to send float over serial

2019-02-13 10:40发布

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.

7条回答
不美不萌又怎样
2楼-- · 2019-02-13 11:44

hm. How about this:

void send_float (float arg)
{
  // get access to the float as a byte-array:
  byte * data = (byte *) &arg; 

  // write the data to the serial
  Serial.write (data, sizeof (arg));
}
查看更多
登录 后发表回答