gpt4 book ai didi

c# - 从串行端口读取和存储字节

转载 作者:太空狗 更新时间:2023-10-29 22:32:27 25 4
gpt4 key购买 nike

我正在尝试创建一个 RS232 应用程序来读取传入数据并将其存储在缓冲区中。我在 RS232 示例中找到了以下代码,但我不确定如何使用它

*RS232 示例 port_DataReceived*

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!comport.IsOpen) return;

if (CurrentDataMode == DataMode.Text)
{
string data = comport.ReadExisting();

LogIncoming(LogMsgType.Incoming, data + "\n");
}
else
{
int bytes = comport.BytesToRead;

byte[] buffer = new byte[bytes];

comport.Read(buffer, 0, bytes);

LogIncoming(LogMsgType.Incoming, ByteArrayToHexString(buffer) + "\n");

}
}

我正在尝试编写另一种方法,该方法采用传入的字节数组并将其与另一个数组组合......见下文:

private void ReadStoreArray()
{
//Read response and store in buffer
int bytes = comport.BytesToRead;
byte[] respBuffer = new byte[bytes];
comport.Read(respBuffer, 0, bytes);

//I want to take what is in the buffer and combine it with another array
byte AddOn = {0x01, 0x02}
byte Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

目前我的代码中有这两种方法,因为我对如何读取传入字节并将其存储到端口感到困惑。我可以在我的“ReadStoreArray”方法中使用“port_DataReceived”方法吗?我需要修改我的“ReadStoreArray”方法吗?还是我应该重新开始?

最佳答案

当您创建 SerialPort 时:

SerialPort comport = new SerialPort("COM1");
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Shortened and error checking removed for brevity...
if (!comport.IsOpen) return;
int bytes = comport.BytesToRead;
byte[] buffer = new byte[bytes];
comport.Read(buffer, 0, bytes);
HandleSerialData(buffer);
}

//private void ReadStoreArray(byte[] respBuffer)
private void HandleSerialData(byte[] respBuffer)
{
//I want to take what is in the buffer and combine it with another array
byte [] AddOn = {0x01, 0x02}
byte [] Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

关于c# - 从串行端口读取和存储字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com