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.
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);
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? 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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With