【发布时间】:2019-04-21 11:21:56
【问题描述】:
我正在尝试通过串行端口编写命令格式并期待回复。在接收过程中,即使我没有在另一端写入相同的模式或数据,我也会收到一些未知的数据模式以及作为命令写入的任何内容。
创建串口
port= new SerialPort(s, 9200, Parity.None, 8, StopBits.One);
发送和接收
public byte[] SendAndRecieve(COMMAND request)
{
Console.Write("\nSendAndRecieve\n");
Console.Write("\n\n");
byte retry = 0;
bool flag = false;
while (retry < 3)
{
/
Console.Write("\n Send&Recive retry {0} \n",retry);
WriteCommandAsByte(request.ToByteArray());
Stopwatch sw = new Stopwatch();
while (sw.Elapsed < TimeSpan.FromMilliseconds(3000))
{
if (readBuffer == null)
{
flag = true;
break;
}
}
if (flag)
break;
retry++;
}
return readBuffer;
}
写函数
public void WriteCommandAsByte(byte [] data)
{
try
{
Console.Write("\nWriting Data: ");
foreach (byte bt in data)
Console.Out.Write(" {0:x2}", bt);
Console.Write("\n\n");
port.DiscardOutBuffer();
port.Write(data, 0, data.Length);
port.Write("\n");
port.DiscardOutBuffer();
}
catch (System.IO.IOException e)
{
Console.WriteLine("WriteCommandAsByte Error");
}
}
接收到串行数据事件处理程序
private void Port_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000);
try
{
Console.WriteLine("\n Data Recieved\n");
int ByteToRead = port.BytesToRead;
readBuffer = new byte[ByteToRead];
port.Read(readBuffer, 0, readBuffer.Length);
port.DiscardInBuffer();
Console.WriteLine("\n Data: \n\n");
foreach (byte bt in readBuffer)
Console.Write(" {0:x2}", bt);
}catch(Exception ex)
{
//Handle exceptions
}
请求数据:
写入数据:01 01 01 00 00 01 00 31 40 c9
回应:
模式 5e 41 5e 41 5e 41 5e 40 5e 和我发送的数据 31 40 c9
5e 41 5e 41 5e 41 5e 40 5e 40 5e 41 5e 40 31 40 c9 0d 0a 5e 41 5e 41 5e 41 5e 40 5e 40 5e 41 5e 40 31 40 c9 0d 0a 5e 41 5e 41 5e 41 5e 40 5e 40 5e 4
5e 40 31 40 c9 0d 0a 5e 41 5e 41 5e 41 5e 40 5e 40 5e 41 5e 40 31 40 c9 0d 0a 5e 41 5e 41 5e 41 5e 40 5e 40 5e 41 5e 40 31
为什么我会收到我写的任何内容以及一些意外数据?
【问题讨论】:
-
串口连接了什么样的设备?
-
USB 串口设备
-
哪个?我的意思是,你在问接收到的数据是什么意思。接收到的数据显然是由连接到串口的东西发送的。所以为了解释它,你需要知道他的设备发送了什么。
-
我马上注意到你的波特率有问题——你是说 9600 吗?不同的 UARTS(如您的 USB 串行设备中的那个)可能会也可能不会尝试将其设置为您所要求的。不知道如果出错了会怎样。
-
哦,还有几件事......你的 Write 方法在你写之前和之后都有一个 DiscardOutputBuffer() 调用。前一个很好,但后一个似乎可能导致您不发送一些字节,因为 Write() 调用将缓冲字节并在发送之前返回。如果您正在单步执行或遇到断点,您可能看不到这一点。
标签: c# .net io serial-port