当写入依赖于读取数据时,如何管理串口的写入和读取
我正在尝试将数据写入串行端口,然后等待确认。收到ack后,我写入下一组数据。 请建议一种方法来做到这一点。我尝试了下面的代码,但在收到确认之前,写入会触发并完成执行。
当我在调试模式下运行它时,它工作正常,但当没有断点运行时,它无法正常运行。
// some data for writing
byte[] data = "xxx";
byte[] data1 = "yyy";
byte[] data2 = "zzz";
// loop to write the above 5 times
int times = 1;
for (int i = 0; i < 20; i++)
{
if (Flag == true)
{
Flag = false;
if (times <= 5)
{
serialPort.Write(data, 0, data.Length);
serialPort.Write(data1, 0, data1.Length);
serialPort.Write(data2, 0, data2.Length);
times = times + 1;
}
}
else
{
MessageBox.Show("Some problem in ack...");
}
}
Flag = true;
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//char[] buffer = new char[4];
//serialPort.Read(buffer, 0, 4);
Flag = true;
}
I am trying to write data to serialport and then wait for the acknowledgement. After ack is received, I write the next set of data.
Please suggest a way of doing this. I tried the below code but before receiving the ack, the writing fires and completes execution.
When I run it in debug mode, it works fine, but when run without breakpoints, it doesnot run properly.
// some data for writing
byte[] data = "xxx";
byte[] data1 = "yyy";
byte[] data2 = "zzz";
// loop to write the above 5 times
int times = 1;
for (int i = 0; i < 20; i++)
{
if (Flag == true)
{
Flag = false;
if (times <= 5)
{
serialPort.Write(data, 0, data.Length);
serialPort.Write(data1, 0, data1.Length);
serialPort.Write(data2, 0, data2.Length);
times = times + 1;
}
}
else
{
MessageBox.Show("Some problem in ack...");
}
}
Flag = true;
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//char[] buffer = new char[4];
//serialPort.Read(buffer, 0, 4);
Flag = true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试使用
Flag
作为确认?逻辑没有道理。你不需要做类似的事情吗Are you trying to use
Flag
as the ack? The logic doesn't make sense. Don't you need to do something like您需要一个状态机模式,或者至少需要某种存储状态的方式。我所说的“状态”是指您在读/写过程中所处的位置。状态机是一种常用于通信(或任何事件驱动程序)的基本设计模式,请稍微阅读一下:
http://www.codeproject.com/KB/architecture/statepatterncsharp.aspx
http://www.dofactory.com/Patterns/PatternState.aspx
http://en.wikipedia.org/wiki/State_pattern(我不喜欢他们在这里选择的示例)
You need a state machine pattern, or at least some way of storing state. By "State" I mean where you are in the process of reading/writing. State machines are a basic design pattern commonly used for communications (or any event driven programs), read up on them a bit:
http://www.codeproject.com/KB/architecture/statepatterncsharp.aspx
http://www.dofactory.com/Patterns/PatternState.aspx
http://en.wikipedia.org/wiki/State_pattern (I don't like the sample they chose here)
不知怎的,这已经奏效了,
Somehow this has worked out,