开发者

How to manage write and read in serialport when write depends on read data

开发者 https://www.devze.com 2022-12-20 18:05 出处:网络
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.

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[] dat开发者_开发知识库a = "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;  
        }


Are you trying to use Flag as the ack? The logic doesn't make sense. Don't you need to do something like

while (Flag == false)
    ; //wait for flag to become true after previous write
...write...
Flag = false;


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,

 byte[] data = "Your message to be sent on serial port";
    serialPort.Write(data, 0, data.Length);

    byte[] buffer = new byte[16];
    int vintctr = 0;
                    while (vintctr < 16)
                        vintctr  += serialPort.Read(buffer, 0, 16);

Debug this and you you can get the reply from the port.
0

精彩评论

暂无评论...
验证码 换一张
取 消