0

I am building a Windows Form Application in visual studio. This is my form1.cs file,

    using System;
    using System.Windows.Forms;

    using System.IO.Ports;       // used to access the SerialPort Class

    namespace Simple_Serial_VS2013
    {
       public partial class Form1 : Form
    { 
        string logTxt;
        string Port_Name;
        string ReceivedData;
        delegate void serialCalback(string val);
        string Selected_Port_Baudrate; //used for storing selected Baudrate and COMport,for displaying purposes 
        int Baud_Rate;
        static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    public Form1()
    {
        InitializeComponent();

        myTimer.Interval = 1000;
        myTimer.Tick += new EventHandler(TimerEventProcessor);

        //Populate the Combobox with SerialPorts on the System
        ComboBox_Available_SerialPorts.Items.AddRange(SerialPort.GetPortNames());

        //Disable both Transmit and receive functions 
        GroupBox_Serial_Transmit.Enabled = false;
        GroupBox_Serial_Receive.Enabled  = false;

        // Disable Baudrate Selection also
        ComboBox_Standard_Baudrates.Enabled = false; 

        // Displaying System Information 

        string SystemInformation;//Used for Storing System Information 

        SystemInformation  = " Machine Name = " + System.Environment.MachineName;                                         // Get the Machine Name 
        SystemInformation  = SystemInformation + Environment.NewLine + " OS Version = " + System.Environment.OSVersion;    // Get the OS version
        SystemInformation  = SystemInformation + Environment.NewLine + " Processor Cores = " + Environment.ProcessorCount; // Get the Number of Processors on the System

        TextBox_System_Log.Text = SystemInformation; //Display into the Log Text Box
        
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    // Will run, when user selects a serialport using Drop Down Menu
    private void ComboBox_Available_SerialPorts_SelectionChangeCommitted(object sender, EventArgs e)
    {

        Selected_Port_Baudrate = ComboBox_Available_SerialPorts.SelectedItem.ToString() + " Selected"; // Store the Selected COM port

        TextBox_System_Log.Text = Selected_Port_Baudrate;  // Display the Selected COM port in the Log Text Box                                  

        ComboBox_Standard_Baudrates.Enabled = true;       // Enable Baudrate Selection after COM port is Selected

    }

    // Will run, when user selects a baudrate using Drop Down Menu after Serialport is selected
    private void ComboBox_Standard_Baudrates_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Selected_Port_Baudrate = Selected_Port_Baudrate + Environment.NewLine;             
        Selected_Port_Baudrate = Selected_Port_Baudrate + ComboBox_Standard_Baudrates.SelectedItem.ToString() + " bps selected";
        TextBox_System_Log.Text = Selected_Port_Baudrate;  // Display the Selected Baudrate in the Log Text Box 

        //Enable both Transmit and Receive Groupboxes
        GroupBox_Serial_Transmit.Enabled = true;
        GroupBox_Serial_Receive.Enabled  = true;
        Port_Name = ComboBox_Available_SerialPorts.SelectedItem.ToString();    // Store the selected COM port name to "Port_Name" varaiable
        Baud_Rate = Convert.ToInt32(ComboBox_Standard_Baudrates.SelectedItem); // Convert the string "9600" to int32 9600
        SerialPort COMport = new SerialPort(Port_Name, Baud_Rate);
        COMport.Open();
        COMport.Write("*");
        COMport.Close();
    }

    private void TextBox_Data_Transmitted_Validated(object sender, EventArgs e)
    {
        //Not used
    }

    private void TextBox_Data_Transmitted_Click(object sender, EventArgs e)
    {
        //Not used
    }

    //Used for sending data to SerialPort
    private void Button_Transmit_Data_Click(object sender, EventArgs e)
    {
        myTimer.Stop();


        GroupBox_Serial_Receive.Enabled = false; // Disable the Receive Groupbox

        //Local Variables
                    
        string Data      = TextBox_Data_Transmitted.Text;                             //Store the string in Textbox to variable "Data"


        // MessageBox.Show(Port_Name);           // Debugging Purpose
        // MessageBox.Show(Baud_Rate.ToString());

        SerialPort COMport = new SerialPort(Port_Name, Baud_Rate); //Create a new  SerialPort Object (defaullt setting -> 8N1)
        COMport.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
        //try to Open SerialPort


        try
        {
            COMport.Open();
        }
        #region  
        catch (UnauthorizedAccessException SerialException) //exception that is thrown when the operating system denies access 
        {
            MessageBox.Show(SerialException.ToString());
            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
            COMport.Close();
        }

        catch (System.IO.IOException SerialException)     // An attempt to set the state of the underlying port failed
        {
            MessageBox.Show(SerialException.ToString());
            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
            COMport.Close();
        }

        catch (InvalidOperationException SerialException) // The specified port on the current instance of the SerialPort is already open
        {
               MessageBox.Show(SerialException.ToString());
               TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
               TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
               COMport.Close();
        }

        catch //Any other ERROR
        {
            MessageBox.Show("ERROR in Opening Serial PORT -- UnKnown ERROR");
            COMport.Close();
        }
        #endregion

        //If we are able to open the port 
        if (COMport.IsOpen == true)
        {
            //MessageBox.Show("Port Opened");
            COMport.WriteLine(Data);                // Send Data
            COMport.Close();                        // Close the Port
            GroupBox_Serial_Receive.Enabled = true; // Enable the Receive Groupbox

            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + Data + "  Written to Port";
        }
        else
        {
            GroupBox_Serial_Receive.Enabled = true; // Enable the Receive Groupbox
            MessageBox.Show("Unable to Write to COM port ");
            COMport.Close();
        }
    }

    //Used for Receiving Data from Serial Port
    private void Button_Receive_Data_Click(object sender, EventArgs e)
    {
        myTimer.Start();


        //GroupBox_Serial_Transmit.Enabled = false; // Disable the Transmit Groupbox
        #region
        //Local Variables
        string Port_Name = ComboBox_Available_SerialPorts.SelectedItem.ToString();      // PortName
        int Baud_Rate = Convert.ToInt32(ComboBox_Standard_Baudrates.SelectedItem);   // BaudRate
        ReceivedData = ""; //                                                    // String Containing Received Data
       

        SerialPort COMport = new SerialPort(Port_Name, Baud_Rate);
        #endregion
        COMport.ReadTimeout = 1500; //Setting ReadTimeout =3500 ms or 3.5 seconds

        //Open the Serial Port 
        #region
        try
        {
            COMport.Open();
        }
        catch (UnauthorizedAccessException SerialException) //exception that is thrown when the operating system denies access 
        {
            myTimer.Stop();
            MessageBox.Show(SerialException.ToString());
            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
            COMport.Close();                                  // Close the Port
        }

        catch (System.IO.IOException SerialException)     // An attempt to set the state of the underlying port failed
        {
            myTimer.Stop();
            MessageBox.Show(SerialException.ToString());
            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
            COMport.Close();                                  // Close the Port
        }

        catch (InvalidOperationException SerialException) // The specified port on the current instance of the SerialPort is already open
        {
            myTimer.Stop();
            MessageBox.Show(SerialException.ToString());
            TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
            COMport.Close();                                  // Close the Port
        }


        catch //Any other ERROR
        {
            myTimer.Stop();
            MessageBox.Show("ERROR in Opening Serial PORT -- UnKnown ERROR");
            COMport.Close();                                  // Close the Port
        }
        #endregion

        try
        {
            //If we are able to open the port 
            if (COMport.IsOpen == true)
            {
                //MessageBox.Show("Port Opened");
                TextBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;

                ReceivedData = COMport.ReadLine();                // Wait for data reception
                #region

                //if(ReceivedData.Split(' ').Length -1 != 2)
                //{
                //    ReceivedData = null;
                //}
                //else if(ReceivedData.Split('<').Length - 1 != 1)
                //{
                //    ReceivedData = null;
                //}
                //else if(ReceivedData.Split('>').Length -1 != 1)
                //{
                //    ReceivedData = null;
                //}

                setLog(ReceivedData);

                //TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + Environment.NewLine + "Waiting for Data";
                //TextBox_received_Data.Text = ReceivedData;

                COMport.Close();                                  // Close the Port

                TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + ReceivedData + "  Received from Port";
                #endregion
                GroupBox_Serial_Transmit.Enabled = true; // Enable the Transmit Groupbox
            }
            else
            {
                GroupBox_Serial_Transmit.Enabled = true; // Enable the Transmit Groupbox
                MessageBox.Show("Unable to Write to COM port ");
                GroupBox_Serial_Transmit.Enabled = true; // Enable the Transmit Groupbox
                COMport.Close();                                  // Close the Port
            }
        }

        // Only catch timeout exceptions.
        catch (TimeoutException SerialTimeOutException)
        {
            myTimer.Stop();
            #region
            // Show in a Message Box 
            MessageBox.Show(COMport.ReadTimeout.ToString() + " milliSeconds Passed" + Environment.NewLine + "Operation Timed Out");
            MessageBox.Show(SerialTimeOutException.ToString());

            //Show in Log TextBox
            TextBox_System_Log.Text = COMport.ReadTimeout.ToString() + " milliSeconds Passed" + Environment.NewLine + "Operation Timed Out";
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + SerialTimeOutException.ToString();
            #endregion
            COMport.Close();                                  // Close the Port

            GroupBox_Serial_Transmit.Enabled = true; // Enable the Transmit Groupbox
        }
    }

    private void ComboBox_Available_SerialPorts_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void TimerEventProcessor(object sender, EventArgs e)
    {
        Button_Receive_Data.PerformClick();
    }

    private void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
    {

        SerialPort sp = (SerialPort)sender;
        sp.WriteTimeout = 1000;
        sp.ReadTimeout = 2000;

        sp.NewLine = "\n";
        //sp.WriteLine("@" + sendtemp + "#");
        string indata = "";
        while(sp.ReadChar() != '\n')
        {
            indata += sp.ReadChar();
        }
        //string indata = sp.ReadExisting(), logTxt;
        logTxt = indata;
    }

    private void setLog(string val)
    {
        if (this.TextBox_System_Log.InvokeRequired)
        {
            serialCalback scb = new serialCalback(setLog);
        }
        else
        {
            TextBox_System_Log.Text = TextBox_System_Log.Text + Environment.NewLine + Environment.NewLine + "Waiting for Data";
            TextBox_received_Data.Text = ReceivedData;
        }
    }

    } //end of Partial Class Form1
}//end of namespace Simple_Serial_VS2013

The control flow is:

  1. The user is asked to select the COM Port, then the baud rate

  2. The user enters a number in the form of !213# (starting with "!" and ending with "#")

  3. This number is taken in by the arduino which runs on the code -

    This is a ss of the code (was having trouble formatting it over here)

  4. The arduino prints "111 222 T(settemp)" every one second to the serial port

  5. This is read by the visual studio application and printed to two textboxes.

PROBLEM: Some parts of the output text dont appear to show up, see attached image. 111 appears as 11, this shouldn't be happening

TRIED SOLUTIONS:

  1. Tried setting up a delegate for setting the textbox values, because I feel a single thread is doing all the serial communication as well in-program stuff.

FYI: If I am using any incorrect programming terminology, I apologize for unintentionally confusing you. I am more of a hobbyist. Any help with this issue is highly appreciated. Thank You!!!

  • The following may be helpful: https://stackoverflow.com/a/66666984/10024425 , https://stackoverflow.com/a/65971845/10024425 , https://stackoverflow.com/a/70614758/10024425 , and [Serial Port](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=netframework-4.8). – Tu deschizi eu inchid Jul 07 '22 at 02:57
  • Why are you closing the port at end of transmit? The receive and transmit uses the same connection and you should not close until the application terminates. – jdweng Jul 07 '22 at 05:54

0 Answers0