c# saving COMport data to file

1.5k Views Asked by At

I am trying to send float data from STM32 board to computer via UART. Im sending float data via UART as 4 frames - 4x8bits. I have already made a function that converts those frames back to float.

My question is what should I do to stack like 1000 floats into array so I can later use it - outside of Handler.

class Program
{
    static void Main()
    {
        SerialPort com = new SerialPort("Com3");

        com.BaudRate = 9600;
        com.Parity = Parity.None;
        com.StopBits = StopBits.One;
        com.DataBits = 8;
        com.Handshake = Handshake.None;
        com.RtsEnable = true;

        com.DataReceived += new SerialDataReceivedEventHandler(RxHandler);
        com.Open();

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
        com.Close();
    }

    private static void RxHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        int bytes = sp.BytesToRead;
        byte[] buffer = new byte[bytes];
        sp.Read(buffer, 0, bytes);
        Console.WriteLine(ToFloat(new byte[] { buffer[0], buffer[1], buffer[2], buffer[3] }));
    }

    static float ToFloat(byte[] input)
    {
        byte[] fArray = new[] { input[0], input[1], input[2], input[3] };
        return BitConverter.ToSingle(fArray, 0);
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

Here the code parts I added to save the floats into a file:

class Program 
{
    private static List<float> list = new List<float>();
    static void Main() {
        // see your code
        // ......
        com.Close();

        // Write list to file
        System.IO.File.WriteAllLines("data.txt", list.Select(p => p.ToString()));
        // convert list to array
        float[] floatArray = list.ToArray();
    }

    private static void RxHandler(object sender, SerialDataReceivedEventArgs e) {
        // see your code
        // ......
        sp.Read(buffer, 0, bytes);

        // store float in variable
        float f = ToFloat(new byte[] { buffer[0], buffer[1], buffer[2], buffer[3] }));
        Console.WriteLine(f);
        // add float to list
        list.Add(f);
    }
3
On

If all you care about is saving your floats' bytes on disk after validating them as such (i.e., as System.Single values) thru your existing ToFloat method, you could use File.WriteAllBytes for instance.

If you'd like to save them as a human-readable representation, I guess you'll want to rely on Single.ToString before using, say, File.WriteAllText.