我正在尝试检查一些在 GSM 调制解调器上运行的 AT 命令的值。在尝试检查命令的输出是否包含某些值时,我陷入了困境。
使用以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Timers;
namespace SerialTest
{
public class Program
{
public static void Main(string[] args)
{
string buff="0";
string ok = "OK";
SerialPort p = new SerialPort("COM28");
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
p.Open();
string line = "1";
p.Write("AT" + "\r");
buff = p.ReadExisting();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
p.Write("AT+CMGF=1"+ "\r" );
buff = p.ReadExisting();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
do
{
p.Write("AT+CMGL=\"REC UNREAD\" " + "\r");
buff = p.ReadExisting();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
/*if (buff.Contains(ok))
Console.WriteLine("Everything is OK");
else
Console.WriteLine("NOK");*/
line = Console.ReadLine();
} while (line != "quit");
p.Close();
}
public static void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine((sender as SerialPort).ReadExisting());
}
}
}
我得到这个输出:
为什么有时buff为空,稍后显示?