有关 SerialPort 的两点疑问,求解答!
项目中需要利用短信猫发短信,于是用 SerialPort 封装所需的AT指令,但现在遇到两点问题:
1、如果不将属性SerialPort.RtsEnable的值设为true, 则 DataReceived 事件不会发生,是否是设备原因?
2、将 SerialPort.RtsEnable的值设为true时,DataReceived 事件中接收到的数据中会包含先前写入的AT指令,例如写入"AT+CSCA?"数据后,接收到的数据则是 AT+CSCA?\n\r\n+CSCA: "+8613010112500",145\r\n\r\nOK\r\n。这是什么原因呢?
对串口操作不熟悉,求解答,多谢!!
- C# code
public class Sms { SerialPort port; TimeSpan waitTime; EventWaitHandle eventWait; public Sms(string portName, int baudRate) { this.port = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One); this.port.RtsEnable = true; this.port.ReceivedBytesThreshold = 1; this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); this.waitTime = TimeSpan.FromMinutes(1); this.eventWait = new EventWaitHandle(false, EventResetMode.AutoReset); } public bool IsOpen { get { return this.port.IsOpen; } } public bool Open() { this.port.Open(); return true; } public void Close() { this.port.Close(); } public string GetCenterNumber() { var response = this.ExecAtCommand(@"AT+CSCA?"); var number = string.Empty; if (!string.IsNullOrEmpty(response)) { var reg = new System.Text.RegularExpressions.Regex("\\+86[0-9]{10,13}"); var mt = reg.Match(response); if (mt.Success) { number = mt.Value.Substring(1); } } return number; } public string ExecAtCommand(string commandText) { if (this.port.IsOpen) { this.port.DiscardOutBuffer(); this.port.DiscardInBuffer(); this.port.WriteLine(commandText); this.eventWait.WaitOne(waitTime); Thread.Sleep(500); var response = this.port.ReadExisting(); return response; } else { return string.Empty; } } void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (this.port.BytesToRead > 0) { Thread.Sleep(500); this.eventWait.Set(); } } }
[解决办法]
参考
http://blog.sina.com.cn/s/blog_6017fba00100dyd1.html
http://www.eefocus.com/sxl630828191/blog/2012-02/235722_e9cf3.html
[解决办法]
默认开了回显,你执行1次关闭回显AT命令就行了,如
AT0