[英]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.我目前正在开发一个带有 STM32 的项目,该项目从摄像头读取数据并通过 UART 连接发送数据。
On the other end I have my C# application connected to the serial port where the data is coming.在另一端,我将 C# 应用程序连接到接收数据的串行端口。 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#).
我将传入数据写入 a.txt 文件以查看它现在的样子,然后再继续我的项目(将数据放回 C# 中的图像)。
This is the function that writes in the.txt upon the "receive" button being pressed.这是在按下“接收”按钮时写入.txt 的函数。
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.在这里,我使用 UTF8 编码获取数据,但我希望能够以原始方式写入数据,完全不使用任何编码。 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?
我可以使用 StreamWriter 以外的东西吗? 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.注意:使用 Docklight 我能够获得关于我收到的数据的一些积极结果,但我无法在我自己的应用程序中获得相同的结果。
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.请注意,如果数据实际上是文本,它仍将使用某种形式的编码,它只会使用发送设备正在使用的任何编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.