How to send float through serial port in c#? [duplicate]

我与影子孤独终老i 提交于 2020-01-07 06:24:48

问题


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:

  1. Convert your float to a 4-byte array. You're on the right track, although my C# is very rusty.
  2. Send them one by one to the microcontroller
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!