Alexander
Alexander

Reputation: 1

COM port communication problems, Text To ASCII

I'm making a simple program, to send information from PC to COM port. So far I have established a connection between the PC and the COM port and I can send information and see what the port received, but I have two problems, the first one is that when I send the info to an actual com port (COM port to USB cable made to echo the signal) the first time I all of the information is received. Then it becomes random, sometimes again, all of what I have written, sometimes only the first character. And sometimes nothing. My assumption is this happens because I haven't put any time-outs or anything at all. Help with this would be nice.

But the real problem that I have is that I want all of the information sent from the textbox to be sent in ASCII code since I'm making the program for communication with PLC.

Here is the code:

   public Form1()
    {
        InitializeComponent();
    }
    //BTN new serial port creation - port taken from comport text box
    private void button1_Click(object sender, EventArgs e)
    {
        System.IO.Ports.SerialPort sport = new System.IO.Ports.SerialPort(comport.Text, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);

        //opening the com port and sending the information from textbox1
        try
        {
                sport.Open();
            sport.Write(textBox1.Text);

        }
        //if there is an error - show error message 
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        //Adding timestamp to received info
        DateTime dt = DateTime.Now;
        String dtn = dt.ToShortTimeString();
        //reading the information form the com port
        textBox2.AppendText("[" + dtn + "] " + "Recieved: " + sport.ReadExisting() + "\n");
        //closing the port
        sport.Close();
    }

Upvotes: 0

Views: 481

Answers (1)

Baddack
Baddack

Reputation: 2053

The problem is, you are reading every time you click the button and may not have recieved everything. You should use the SerialPort class' DataReceived event to receive your data. The event fires every time data is received through your COM port, so you can press your button to write to the port then as the data comes in you should see the event fire with your data.

Microsoft has a good definition and example here.

The event is on a separate thread, so to write it to a textbox you may have to invoke it to display it on your gui. See the example code below:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string Data = serialPort1.ReadExisting();

    this.Invoke((MethodInvoker)delegate
    {
        textBox2.AppendText(Data);
    });
}

Upvotes: 1

Related Questions