问题
I have two float now,say f1 and f2. I want to send them to my micro controller through my computer serial port, how should I do it? My understanding is we need to convert f1 and f2 to binary first,then send to micro, after that cnvert back to float again. So I am confused that HOW DO I CONVERT FLOAT TO BINARY BEFORE I SEND THEM OUT? My code now is
b1 = System.BitConverter.GetBytes(f1);
b2 = System.BitConverter.GetBytes(f2);
回答1:
It depends on the endianness of your microcontroller's architecture. But roughly speaking you need to do this:
- Convert your float to a 4-byte array. You're on the right track, although my C# is very rusty.
- Send them one by one to the microcontroller
If your microcontroller supports floating point representation you could cast the four-byte array into a float:
byte array[4]; // Pre-allocate your array getBytesFromSerial(array); // Fill the array with values from serial port float converted = 0; memcpy(&converted, array, 4); /** Now "converted" holds the float value */
Now that will work only if the endianness of your uC is consistent with the order in which you are sending the data. If that doesn't work try sending the byte array in inverted order. And please mind the error checking!
来源:https://stackoverflow.com/questions/25354428/how-to-send-float-through-serial-port-in-c