3

我正在从事一个项目,涉及向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();
        //}
    }
}
4

2 回答 2

0

我在诺基亚论坛上读到诺基亚手机 60 系列不支持读取短信命令,并且此 at 命令不适用于诺基亚手机

于 2013-08-20T13:55:19.027 回答
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;
        }
    }
于 2013-08-18T23:46:13.943 回答