读取AT命令结果代码

时间:2012-12-01 18:56:13

标签: c# command at-command

我正在开展一个项目,包括向移动电话调制解调器发送AT命令并接收其结果代码。 我已经成功发送了at命令,但我无法弄清楚的是从命令中读取结果代码,例如当你发送“at”它返回“OK”时如果你发送“at + cbc”它会返回电池状态。 我在发送命令后尝试使用Read和ReadLine以及ReadExisting但它没有工作,我也尝试为接收的数据创建一个事件并使用这些函数,但它也没有用。 这是我的源代码,希望你能给我一些帮助。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApplication1
{
    public partial class check : Form
    {
        SerialPort sp;

        public check()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            sp = new SerialPort();
            sp.PortName = "COM3";
            sp.BaudRate = 9600;
            sp.Parity = Parity.None;
            sp.DataBits = 8;
            sp.StopBits = StopBits.One;
            sp.ReadTimeout = 3000;
            sp.WriteTimeout = 3000;
            //sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        }

        private void btn1_Click(object sender, EventArgs e)
        {
            try
            {
                if(!sp.IsOpen)
                {
                    sp.Open();
                }
                sp.WriteLine(tbCmd+"\r\n");
                System.Threading.Thread.Sleep(2000);
                tbStatus.Text = sp.ReadLine();      
            }
            catch(Exception ex)
            {
                tbStatus.Text = "Error!\r\n" + ex.ToString();
            }
        }

        //void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    tbStatus.Text = sp.ReadExisting();
        //}
    }
}

2 个答案:

答案 0 :(得分:0)

    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

    void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if(e.EventType != SerialData.Chars)
        {
            tbStatus.Text = "IGNORED: " + e.EventType.ToString();
            return;
        }
        try
        {
            int nBytesToRead = sp.BytesToRead;
            char[] receivedData = new char[nBytesToRead];
            sp.Read(receivedData, 0, nBytesToRead);
            tbStatus.Text = "RECEIVED: " + new string(receivedData);
        }
        catch (Exception ex)
        {
            tbStatus.Text = "ERROR: " + ex.Message;
        }
    }

答案 1 :(得分:0)

我在诺基亚论坛上看到,诺基亚手机60系列不支持读取短信息命令,这个命令在诺基亚手机上不起作用