我尝试通过打开串口连接发送AT命令,我的目标是发送短信。我能够实现这一点并且消息被发送出去,这表明WriteLine()方法成功完成。但是,我似乎无法在接收缓冲区中获得任何响应。我通过在stackoverflow上查看这里的一些答案来启用echo。
但仍然没有回应。我尝试使用Thread.Sleep()并使用处理程序p_DataReceived等待。仍然没有回应。
一个例子就是简单的" AT"命令应该有" ok"的响应。但根本没有响应(即BytesToRead属性大小为0)
我尝试使用D-Link的dwm222 4G LTE USB适配器
任何指针都将非常感谢!
private void button_Click(object sender, RoutedEventArgs e)
{
mySerialPort = new SerialPort("COM15");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.NewLine = Environment.NewLine;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
mySerialPort.Open();
mySerialPort.DiscardInBuffer();
mySerialPort.DiscardOutBuffer();
mySerialPort.WriteLine("ATE1"); //turn on echo
mySerialPort.WriteLine("AT"); //test response
Thread.Sleep(3000);
string responseSTR = mySerialPort.ReadLine();
if (responseSTR.Contains("OK")) //empty string
{
MessageBox.Show(responseSTR);
}
this.SendSms("+XXXXXXXXXXXXXXXXXXX", "Hello From C#");
mySerialPort.Close();
}
public void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string s = (sender as SerialPort).ReadExisting();
buff += s;
MessageBox.Show(buff);
}
void SendSms(string destination, string text)
{ ........}
答案 0 :(得分:1)
启用DTR和RTS填充串行端口对象的缓冲区。
mySerialPort = new SerialPort("COM17");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.NewLine = Environment.NewLine;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
mySerialPort.Open();
mySerialPort.DiscardInBuffer();
mySerialPort.DiscardOutBuffer();
mySerialPort.DtrEnable = true; //this solved my problem
mySerialPort.RtsEnable = true; //this solved my problem
答案 1 :(得分:0)
我认为你应该每次都丢弃缓冲区,所以你应该获得一个新的传入数据尝试我在你的事件处理程序中修改过的代码
public void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string s = mySerialPort.ReadExisting();
buff += s;
mySerialPort.DiscardInBuffer();
mySerialPort.DiscardOutBuffer();
MessageBox.Show(buff);
}