C# 串口短信发送工具 AT指令

来源:互联网 发布:帝国数据库备份目录 编辑:程序博客网 时间:2024/05/16 14:20

公司要做一个井盖的短信收发系统,懵逼的两天,查阅大量资料后,发现需要实现的也不多。

1.串口的连接(sim900的设备)

2.AT指令发送(sim的用户手册有)


串口连接的核心代码

        public ComPortClass ( string PortName , int PortNum )         //初始化串口实例         {            sp = new SerialPort ( PortName , PortNum , Parity.None , 8 );            sp.ReceivedBytesThreshold = 5;            sp.Handshake = Handshake.RequestToSend;            sp.Parity = Parity.None;            sp.ReadTimeout = 200;            sp.WriteTimeout = 200;            sp.Open ( );        }
短信发送的核心代码(参考设备的手册)
 public string SendToCom ( string mobile , string CenterNum , string msgTxt )//发送信息         {            try            {                sp.Write ( "AT+CSCA=+86" + CenterNum + ";&W" + "\r" );                Thread.Sleep ( 200 );                sp.Write ( "AT+CMGF=0" + "\r" );                Thread.Sleep ( 200 );                SendPdu ( mobile , msgTxt );                byte [ ] buffer = new byte [ sp.BytesToRead ];                               return System.Text.Encoding.ASCII.GetString ( buffer );            }            catch            {                return "发送失败!";            }        }

AT指令发送的核心代码
public string ATCommand ( string ATCmd )//发送AT指令         {            try            {                if ( ATCmd.Substring ( 0 , 2 ).ToLower ( ) != "at" )                {                    return "失败!";                }                sp.Write ( ATCmd + "\r" );                Thread.Sleep ( 500 );                byte [ ] buffer = new byte [ sp.BytesToRead ];                sp.Read ( buffer , 0 , buffer.Length );                return System.Text.Encoding.ASCII.GetString ( buffer );            }            catch            {                return "失败!";            }        }

关键代码如上,期间有个插曲,不清楚短信中心代码为何物,后续调试了很久无法发出短信,当地的短息中心号码要设置好。
0 0
原创粉丝点击