日期:2014-05-18  浏览次数:21260 次

串口发送AT指令给短信猫没有返回值
各位,请教一个关于串口连接短信猫发短信的问题,我看这里也有很多贴子时关于这个问题的,可是我没有我的答案,我用C#写的,打开串口后,发送“AT\r”,返回“OK”正常,但是再发送其他AT指令的话就都没有返回值了。但奇怪的是,我用超级终端打开过串口后,再在程序里打开串口,发送其他AT指令就会有正常的返回值了(例如:“AT+CGMI\r”)。请问有人知道是怎么回事吗?

------解决方案--------------------
串口通信是独占式的,你如果用超级终端打开串口后没有退出来,你的程序中再打开相同的串口,是不应该能够打开的。
在.NET中用Serialport组件来实现串口通信是非常方便的。设置好串口的参数并打开,向串口发送指令,利用SerialPort的DataReceived事件接收数据就可以了。请参考下面的技术要点。

技术要点: 
(1).首先,SerialPort的ReceivedBytesThreshold先设置成1,表示只要有1个字符送达端口时便触发DataReceived事件 
(2).当DataReceived触发时,先把ReceivedBytesThreshold设置成一个比较大的值,达到读取本次端口数据时,不再触发DataReceived. 
(3).循环读取端口中的数据,直至读完。 
(4).移除读取数据中的非法字符。 
(5).触发一个后台线程处理收到的数据。 
(6).在finally中把ReceivedBytesThreshold重置回1 

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 

if (sender.GetType() != typeof(System.IO.Ports.SerialPort)) 

return; 

string strReceive = string.Empty; 
string strCollect = string.Empty; 
System.IO.Ports.SerialPort comPort = (System.IO.Ports.SerialPort)sender; 

try 

comPort.ReceivedBytesThreshold = comPort.ReadBufferSize; 
while (true) 

strReceive = comPort.ReadExisting(); 
if (string.Equals(strReceive, string.Empty)) 

break; 

else 

strCollect += strReceive; 
Application.DoEvents(); 
Thread.Sleep(100); 


strCollect = strCollect.Replace("\0", string.Empty); 
strCollect = strCollect.Replace("\r\n", string.Empty); 
strCollect = strCollect.Replace("\r", string.Empty); 
strCollect = strCollect.Replace("\n", string.Empty); 

if (!this.bIsHandleCom) 

this.bIsHandleCom = true; 
mReceiveData = strCollect; 
if (ReceiveDataParserEvent != null) 
ReceiveDataParserEvent(mReceiveData); 
if (ThreadReceiveParser != null && !ThreadReceiveParser.IsAlive) 

ThreadReceiveParser.Start(); 




catch (Exception ex) 

MessageBox.Show(this, ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 

finally 

comPort.ReceivedBytesThreshold = 1; 

}
------解决方案--------------------
我也碰到过这种 问题 研究了很长时间才解决,发送完 号码时候 要发送个 特殊的内容,在超级终端里面是不用输入那个特殊的标志的
public class PortData
{
public event PortDataReceivedEventHandle Received; //接收事件
public event SerialErrorReceivedEventHandler Error; // 接收事件异常处理
private SerialPort port; //端口
private bool ReceiveEventFlag = false; //接收事件是否有效 false表示有效
private PDUdecoding PDU; //PDU 编码类
/// <