简体   繁体   中英

How to write the raw data coming from a serial port to a .txt file

I am currently working on a project with a STM32 that reads from a camera and sends the data through an UART connection.

On the other end I have my C# application connected to the serial port where the data is coming. I write incoming data in a.txt file to see what it looks like for now, before going further in my project (putting back the data into an image in C#).

This is the function that writes in the.txt upon the "receive" button being pressed.

private void btnReceive_Click(object sender, EventArgs e)
{
    try
    {
        if (serialPort1.IsOpen)
        {
            //Debug.Write(serialPort1.ReadExisting());
            using (StreamWriter writetext = new StreamWriter("write.txt", false, Encoding.UTF8))
            {
                writetext.WriteLine(serialPort1.ReadExisting());
            }
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Here I get the data with a UTF8 encoding, but my wish would be to be able to write the data in a raw way, with no encoding at all. But I have no idea how to write the decimal value coming in the serial port directly in the file. Is there something else than the StreamWriter that I can use? Or another king of encoding value?

NB: using Docklight I am able to get some positive results regarding the data I receive, but I can't get the same in my own app.

If you just want to read bytes from the port and write these to a file, you need to read bytes from the port.

var buffer = new byte[serialPort1.ReadBufferSize];
using var fs = File.OpenWrite(...);
while(serialPort1.IsOpen){
    var readBytes = serialPort1.Read(buffer, 0, buffer.Length);
    fs.Write(buffer, 0, readBytes );
}

Note that if the data is actually text it will still use some form of encoding, it will just use whatever encoding the sending device is using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM