Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send float over serial

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.

like image 526
chriszero Avatar asked Jul 17 '10 09:07

chriszero


People also ask

How do I send float through UART?

suppose you want to send over UART a float, you can send it in binary or use a human readable format: char temp[32]; int c= snprintf(temp, sizeof(temp),"%f\r\n", number); send_uart(temp, c);

How are floating-point numbers stored?

Scalars of type float are stored using four bytes (32-bits). The format used follows the IEEE-754 standard. The mantissa represents the actual binary digits of the floating-point number.

How do I send a serial message to Arduino?

How? Using serial inputs is not much more complex than serial output. To send characters over serial from your computer to the Arduino just open the serial monitor and type something in the field next to the Send button. Press the Send button or the Enter key on your keyboard to send.


1 Answers

This simply works. Use Serial.println() function

void setup() {
  Serial.begin(9600);

}

void loop() {
  float x = 23.45585888;
  Serial.println(x, 10);
  delay(1000);
}

And this is the output:

enter image description here

like image 102
partho Avatar answered Sep 27 '22 16:09

partho