0

I am trying to send a string of AT commands to a USB dongle. i have been successful in writing to the serial port. But i have not been successful in reading back. Basically what i want to do is to send lets say AT to the dongle and receive OK in a richtextbox. Next will be to send info from another device to the dongle and read it in the richtextbox.

Below is the code I am using:

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        SerialPort sp = null; //<---- serial port at form level

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            // initialise port in form loadmyport.PortName = "COM3";
            sp = new SerialPort();
            sp.PortName = "COM8";
            sp.BaudRate = 115200;
            sp.Parity = Parity.None;
            sp.DataBits = 8;
            sp.StopBits = StopBits.One;
            sp.NewLine = System.Environment.NewLine;
            sp.ReadTimeout = 2000;
            sp.WriteTimeout = 2000;
            sp.DtrEnable = false;
            sp.RtsEnable = false;
            sp.WriteBufferSize = 4096;
            sp.ReadBufferSize = 4096;
            sp.Handshake = Handshake.None;
            sp.Encoding = System.Text.Encoding.ASCII;

            // also set up baud rate etc here.
            // attach event handler to capture data received 
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        }

        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            connect.Enabled = false;
            try
            {
                // open port if not already open
                // Note: exception occurs if Open when already open.
                if (!sp.IsOpen)
                {
                    sp.Open();
                }
                // send data to port
                sp.Write("ATXXX,XXXXXXX\r\n");
                disconnect.Enabled = true;
            }
            catch (Exception)
            {

               // report exception to user
                Console.WriteLine(e.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            connect.Enabled = true;

            try
            {
                // open port if not already open
                // Note: exception occurs if Open when already open.
                if (!sp.IsOpen)
                {
                    sp.Open();
                }
                // send data to port
                sp.Write("atXX,0\r\n");
            }
            catch (Exception)
            {

                Console.WriteLine(e.ToString());
            }
            finally
            {
                disconnect.Enabled = false;
            }
        }


        public void OnApplicationExit(object sender, EventArgs e)
        {
            sp.Close();
        }
    }
}
Joey Agyeduah
  • 55
  • 1
  • 5
  • You have a datareceived handler (sp_DataReceived), why are you not using it? – user2019047 Jun 26 '13 at 17:54
  • let me update my post. I added this to the data received handler private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(indata); still don't see anything. – Joey Agyeduah Jun 26 '13 at 18:42
  • possible duplicate of [SerialPort DataReceived event does not fire](http://stackoverflow.com/questions/8907490/serialport-datareceived-event-not-fire-c-console-application) – Hans Passant Jun 26 '13 at 19:48
  • @HansPassant Thanks the thread was really helpful. – Joey Agyeduah Jun 27 '13 at 22:06

1 Answers1

3

Don't read data from the serial port directly in your main code. You have an event handler in place for the data received event, and it currently writes the response to the debugging console. All you need to do is change the event handler to write the text into your rich text box instead. (The code you have in place to read the data and display it in the text box will never display anything because (a) port_DataRecieved looks like it is never subscribed to any events, so it won't be called, and (b) your sp_DataReceived event handler is reading the data and logging it to the debug output, so any other code that tries to read the port will find it "empty")

Note that the sp_DataReceived event will be raised on a different thread, not your UI thread, so you will need to Invoke or BeginInvoke to pass control back to the UI thread to add the text to your text box.

Note also that you may not get the response as a single"packet" of data. It may be split into several pieces, so you will need to add each incoming message to the end of the text in your text box in order to stitch together the entire response from all the pieces you received.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
  • Thanks jason. Unfortunately am new to C#. Can give a gist of how to do the invoke and begin invoke thing. Because i think the data received event is not been fired. – Joey Agyeduah Jun 26 '13 at 20:12
  • Check out the example [here](http://msdn.microsoft.com/en-us/library/a06c0dc2.aspx) - it's very close to what you'll need. If the event is not firing at all then you aren't recieving data - see [here](http://stackoverflow.com/questions/8907490/serialport-datareceived-event-does-not-fire) - you are disabling DtrEnable and RtsEnable which may stop the device replying to you. When creating the serial port, you should only set PortName, BaudRate, Parity, DataBits, StopBits, and generally leave all other values to their defaults unless you *know* you need to change them. – Jason Williams Jun 26 '13 at 22:42
  • Thanks @jasonWilliams. It worked after i made the DtrEnable and RtsEnable true and added a Delegate method. My second question is now when i send packets they come in the richtextbox as some weird characters. Do i have to convert it to bytes or something??? – Joey Agyeduah Jun 27 '13 at 17:43
  • You will receive binary data. If it represents ASCII text then you need to use Encoding.ASCII Encoding.GetString() to convert the byte array to text correctly. If it's non-text data, then you need to convert it to a hex dump or other text based format to make it readable in a text box. – Jason Williams Jun 27 '13 at 22:08
  • Hi @jasonWilliams. Thanks for your previous response.Can you please show me link to an example of a hex dump that i can use. I will be receiving values in hexadecimal. "If it's non-text data, then you need to convert it to a hex dump or other text based format to make it readable in a text box" – Joey Agyeduah Jul 17 '13 at 19:06
  • Just search for "c# hex dump" and you'll find plenty of examples like [this one](http://www.codeproject.com/Articles/36747/Quick-and-Dirty-HexDump-of-a-Byte-Array) – Jason Williams Jul 17 '13 at 21:39