⌘BABAKOV.NET Let's code!
100% [light] [ru]

Example of working with SerialPort in C#

Simple example of reading incoming data from the COM port using SerialPort on C#.

Everything is quite simple, to get the data, we will need to use the DataReceived event.

Example:

private string stroka="";

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            this.Invoke(new EventHandler(DoUpdate));
        }
private void DoUpdate(object s,EventArgs e)
        {
            stroka = stroka + serialPort1.ReadExisting();
        }


When executing this code, all incoming data from the COM port will be stored in the stroka variable.

To start working with the COM port, you need to start the component with the specified parameters, to stop, do it like this:

serialPort1.PortName = "COM1"; //Указываем наш порт - в данном случае COM1.
serialPort1.BaudRate = 9600; //указываем скорость.
serialPort1.DataBits = 8; 
serialPort1.Open(); //Открываем порт.

.....

serialPort1.Close(); //Закрываем порт.

That's it.
P.S. Before closing the application, it is essential to close the port.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.