0
votes

I want to receive message through gsm modem in C#.I have written a code but on console I get continuous stream of ERROR whenever a message is received.Please help me in receiving a message.Here is my code.

     static void Main(string[] args)
        {   
              SerialPort serialport = new SerialPort();
              int mSpeed = 1;
              serialport.PortName = "COM16";
              serialport.BaudRate = 9600;
              serialport.Parity = Parity.None;
              serialport.DataBits = 8;
              serialport.StopBits = StopBits.One;
              serialport.Handshake = Handshake.XOnXOff;
              serialport.DtrEnable = true;
              serialport.RtsEnable = true;
              serialport.NewLine = Environment.NewLine;


            serialport.DataReceived += newSerialDataReceivedEventHandler(DataReceivedHandler);
            serialport.Open();
            Console.ReadKey();

    }
    private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        sp.WriteLine("AT+CMTI" + Environment.NewLine);
        Console.WriteLine(sp.ReadLine());

    }
}
1
I don't understand why you use synchronous ReadLine (and Writeline) calls when you als have an async handler... SerialDataReceivedEventArgs holds your data, use that... And I guess only ONE CMTI command is needed, just after serialport.Open();rene

1 Answers

1
votes

After your serialport.Open() use these code.
serialport.Write("AT+CMGF=1\r"); // Instruct the GSM modem to operate in SMS text mode serialport.Write("AT+CNMI=1,2,0,0,0\r"); // Receive notification of incoming messages

try this.. on your DataReceivedHandler.

SerialPort sp = (SerialPort)sender; string input = sp.ReadExisting(); Console.WriteLine(input);