I am trying to check some values some AT commands ran on a GSM modem.
I am stuck at the point where when trying to check if the output of a command contains some values is true or not.
Using the following code:
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());
}
}
}
I get this output:

Why is it that sometimes buff is empty and is displayed later ?
There are calls to
ReadExisting()that are superfluous.You should not be reading your serial port output in the main method, let the event handler do the work for you.
Also, you should append what you read in the event handler to the
buffvariable so that you can all the data received when you check your buffer.Try this instead: