none
Serial port reading loop RRS feed

  • Question

  • Hello!

    I am new in Visual Studio 2019, but have more experience with C and C++ because of long years with MCU-s.

    Also, i have an STM32 device, that send over Serial port an AES encrypted Hex data any 2 seconds. All messages are finished with newline. My program (with User Interface, not a console one) is able to read from serial and to decrypt the data, even in loop still working good, but the problem is that in loop i can't use the disconnect function, so my program stay in "infinite loop".

    public void button1_Click(object sender, EventArgs e)
            {
                try 
                {
                    serialPort1.PortName = cBoxComPort.Text;
                    serialPort1.BaudRate = 9600;
                    serialPort1.DtrEnable = true;
                    serialPort1.ReadTimeout = 5000;
                    serialPort1.WriteTimeout = 500;
                    serialPort1.Open();
                    lblStatusCom.Text = "Connected";
                    lblMessage.Text = "I am on!";
    
                    while (serialPort1.IsOpen)
                    {
                        string mgs1 = serialPort1.ReadLine();
                        byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
                        byte[] enc = StringToByteArray(mgs1);
                        byte[] dec = Decrypt(enc, key);
                        lblMessage.Text = getString(dec);
                    }
                }
                catch(Exception err)
                {
                    MessageBox.Show(err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //lblStatusCom.Text = "Disconnected";
                }
            }

    How can i "put to background" this loop process, so that a user can click to disconnect, if he wish to quit the reading?

    Wednesday, February 19, 2020 5:50 PM

All replies

  • When the button gets clicked what you want to do is start listening for requests on the port. As requests come in you will process them. This does occur on the UI thread by default but doesn't require a loop since the runtime will call back to your code. When configuring the serial port listen for the DataReceived event (and optionally the others).  All you need to do in the button click is configure the port and open it. A full example is provided in the link I gave above on how to listen for events and not block the caller. Here's a stub of the code.

    //In the designer hook up the OnDataReceived method to the DataReceived event on your serialPort1 object you dragged onto the form (should probably also handle ErrorReceived)
    
    private void OnDataReceived ( object sender, SerialDataReceivedEventArgs e )
    {
       //Handle receiving data in this method, note that you may not receive all the data at once so you need to handle batching
    
      //This is called on the UI thread (because of the designer generated code) so you can update the UI normally
    }
    
    private void button1_Clicked ( object sender, EventArgs e )
    {
       //If port is already open then do nothing??
       if (serialPort1.IsOpen)
          return;
    
       //Configure the port
       serialPort1.PortName = cBoxComPort.Text;
       ..
    
       //Open it
       serialPort1.Open();  
    }
    
    //Hook this up to your button that closes the port
    private void OnDisconnectPort ( object sender, EventArgs e )
    {
       serialPort1.Close();
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, February 20, 2020 3:38 PM
    Moderator
  • How can i "put to background" this loop process, so that a user can click to disconnect, if he wish to quit the reading?

    I wouldn't screw around with async at all with something like this.  Any time you get into cryptography you're throwing performance to the wind anyway.

                    while (serialPort1.IsOpen)
                    {
                        string mgs1 = serialPort1.ReadLine();
                        byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
                        byte[] enc = StringToByteArray(mgs1);
                        byte[] dec = Decrypt(enc, key);
                        lblMessage.Text = getString(dec);
    
                        // The item that makes your UI responsive while looping:
                        Application.DoEvents();
                    }

    • Proposed as answer by simonb549 Tuesday, February 25, 2020 7:43 AM
    Thursday, February 20, 2020 7:28 PM
  • Hi Renault Jan,

    Thank you for posting here.

    Here is a code example from Microsoft documentation, I made some changes to it.

           private void button1_Click(object sender, EventArgs e)
            {
                SerialPort mySerialPort = new SerialPort("COM1");
                mySerialPort.BaudRate = 9600;
                mySerialPort.Parity = Parity.None;
                mySerialPort.StopBits = StopBits.One;
                mySerialPort.DataBits = 8;
                mySerialPort.Handshake = Handshake.None;
                mySerialPort.RtsEnable = true;
                mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                mySerialPort.Open();
            }
    
            private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
            {
                SerialPort serialPort1 = (SerialPort)sender;
                if (serialPort1.IsOpen)
                {
                    string mgs1 = serialPort1.ReadLine();
                    //Do something...
                }
    
            }

    Microsoft provides technical documentation on SerialPort, if you want to know more about it, please refer to the following documents.

    SerialPort Class

    SerialPort.DataReceived Event

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, February 21, 2020 6:35 AM
  • Hi,

    Has your problem been solved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, February 26, 2020 9:48 AM