Since this question is highly dependent on search engines, I put together a working solution.
A WARNING. If you don't need full floating point precision, convert it to a string and send it (using sprintf or dtostrf or use Serial.print (value, NumberOfDecimalPlaces) (documentation) ). This is because the following solution: a) does not work for machines of different consistencies, and b) some of the bytes may be misinterpreted as control characters.
Decision. Get the pointer for the floating point number, and then pass it as an array of bytes to Serial.write ().
eg.
/* Code to test send_float function Generates random numbers and sends them over serial */ 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)); Serial.println(); } void setup(){ randomSeed(analogRead(0)); //Generate random number seed from unconnected pin Serial.begin(9600); //Begin Serial } void loop() { int v1 = random(300); //Generate two random ints int v2 = random(300); float test = ((float) v1)/((float) v2); // Then generate a random float Serial.print("m"); // Print test variable as string Serial.print(test,11); Serial.println(); //print test variable as float Serial.print("d"); send_float(test); Serial.flush(); //delay(1000); }
Then, to get this in python, I used your solution and added a function to compare the two outputs for verification.
# Module to compare the two numbers and identify and error between sending via float and ASCII import serial import struct ser = serial.Serial('/dev/ttyUSB0', 9600) // Change this line to your port (this is for linux ('COM7' or similar for windows)) while True: if(ser.inWaiting() > 2): command = ser.read(1)
References: Sending a floating-point number from python to arduino and How to send a float through a serial port
Aaron source share