我正在使用可以使用2波特率的硬件,并且可以使用rs 232命令设置此波特率。
问题是我不想手动设置波特率,我希望软件设置一个波特率并发送命令,如果我得到答复,请继续此波特率,否则将其更改为第二个波特率并发送命令(如果已回答),则以该波特率继续。
步骤:
我写了一个代码,但是命令没有发送到硬件,如果我给Thread.sleep(),那么我的界面就会死机。我该如何实现?
以下是我的代码:
if (!SCP.IsOpen) {
SCP.PortName = cBoxComPort.Text;
SCP.BaudRate = 38400;
SCP.Parity = Parity.None;
SCP.DataBits = 8;
SCP.StopBits = StopBits.One;
SCP.DataReceived += SerialPort1DataReceived;
SCP.ReceivedBytesThreshold = 1;
SCP.Open();
dataout = "get rs232"; // test command
SCP.Write(dataout + "\r");
progressBar1.Value = 100;
fnLogFile = new StreamWriter("Logfile_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".log", true);
//string valueofdatain = datain;
string stringvalue = "command syntax error at cursor position 000";
if (stringvalue.CompareTo(datain) == 0 ) {
SCP.Close();
fnLogFile.Close();
SCP.PortName = cBoxComPort.Text;
SCP.BaudRate = 9600;
SCP.Parity = Parity.Even;
SCP.DataBits = 8;
SCP.StopBits = StopBits.One;
SCP.Open();
SCP.DataReceived += SerialPort1DataReceived;
SCP.ReceivedBytesThreshold = 1;
dataout = "get rs232";
SCP.Write(dataout + "\r");
progressBar1.Value = 100;
fnLogFile = new StreamWriter("Logfile_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".log", true);
} else {
SCP.Close();
fnLogFile.Close();
progressBar1.Value = 0;
}
}
答案 0 :(得分:0)
DataReceived
事件的代码在哪里?您需要状态机来完成您要尝试执行的操作。参见this link,我对如何执行此操作有很好的记录。
基本上,您将在38400发送命令1,如果得到响应,很好,请转到下一个状态,在此状态下您需要执行的操作。否则,如果没有响应,请超时,将波特率设置为9600,然后返回到命令1状态(请注意,我相信您可以在端口打开时切换波特率)。
使用链接中的示例,这是添加超时的方法:
Stopwatch sw = new Stopwatch();
case StateMachine.SendCmd1:
sw.Reset();
sw.Start();
CallbackResponse = Cmd1Response; //set our delegate to the first response
sp.Write("Send first command1"); //send our command through the serial port
currentState = StateMachine.Cmd1Response; //change to cmd1 response state
break;
case StateMachine.Cmd1Response:
//waiting for a response....you can put a timeout here
if (sw.ElapsedMilliseconds > (5000) && sw.ElapsedMilliseconds != 0)
{
//set the baud rate
//set current state back to SendCmd1
}
break;