简体   繁体   中英

How do I access COM-Port with C#?

Here the serial communication port shows error it cannot be accessed .....But the serial communication port works perfect in arduino, so it cant be the port problem, its not the driver problem either, the driver is updated and works well, so the problem can be in the code .....i am a newbie to C#.

public partial class Form1 : Form
{
    private SerialPort myport;
    private string in_data;
    public Form1()
    {
        InitializeComponent();
    }

    private void Start_Click(object sender, EventArgs e)
    {

        myport = new SerialPort();
        myport.BaudRate = 19200;
        myport.PortName = pn.Text;
        myport.Parity = Parity.None;
        myport.DataBits = 8;
        myport.StopBits = StopBits.One;
        myport.DataReceived += myport_DataReceived;
        try
        {
            myport.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!");
        }

    }

    void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        *in_data = myport.ReadLine();***
        this.Invoke(new EventHandler(displaydata_event));

    }
    private void displaydata_event(object sender, EventArgs e)
    {
        string[] newData = in_data.Split(',');

        bv.Text = newData[0];
        bi.Text = newData[1];
        pv.Text = newData[2];
        pi.Text = newData[3];
        t.Text = newData[4];
    }
}

it cannot be accessed

This may indicates that the port doesnt exists or is already in use. Maybe another application is already listening on this port. (arduino?)

Comport.Open() Exceptions are descibed here: MSDN SerialPort.Open Method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM