C # serial Communication

Source: Internet
Author: User

This article provides a C # implementation of serial communication instances, personally written, pro-Test available!

Development environment: Vs2008+.net FrameWork3.5 (actually 2.0 should also be possible)

The first step

Create a WinForm form and pull in some interface elements

The point is, the diagram is marked with a red box, the Toolbox-the component--serialport, to do. NET serial communication, this is the necessary control

Step Two

Setting SerialPort Control Properties

Use C # to send data to the serial port nothing special, is to call SerialPort write method to the serial port writing data on the line

But the way to receive data from the serial port is quite special.

First, you need to declare a special event function in your code.

Private void serialport_datareceived (object  sender, System.IO.Ports.SerialDataReceivedEventArgs e)        {            this. Invoke (new  EventHandler (Updateuitext));        }

This function is used to bind to the DataReceived event of the SerialPort control

As the name implies, this event is triggered when the data returned by the serial port is received, which is a code

Interested in this code can be privately re-study, here will not repeat the

In short, this code is used to mobilize another function to update the values of UI elements (and of course you can do other things inside).

        Private voidUpdateuitext (Objects, EventArgs e) {            Try            {                //The thread must be blocked for a period of time in case the transaction times out, because the read is too fast causing the reads to be incompleteSystem.Threading.Thread.Sleep ( -); stringTXT =serialport.readexisting (); Txt_received.text=txt; }            Catch(Exception ex) {MessageBox.Show (ex).            Message.tostring ()); }                    }

Step Three

began to write logic code, nonsense not to say, directly posted up

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing;     Using system.linq;using system.text;using system.windows.forms;namespace WinForm serial Communication {public partial class Form1:form                    {public Form1 () {InitializeComponent (); private void Form1_Load (object sender, EventArgs e) {string[] ports = System.IO.Ports.SerialPo Rt.            Getportnames (); if (ports. Length = = 0) {MessageBox.Show ("This machine does not have a serial port!            ");            } array.sort (ports); Serialport.portname = ports[0];//string number COM3 serialport.baudrate = 115200;//Baud rate serialport.databits = 8; Data bit serialport.stopbits = system.io.ports.stopbits.one;//stop bit serialport.encoding = SYSTEM.TEXT.ENC Oding. GetEncoding ("GB2312");//This line is very important to solve the problem of receiving Chinese garbled//Open serial port try {serialport.open ()            ;    }        catch (Exception ex) {//captures the exception information, creates a new Comm object, and cannot be used before.                SerialPort = new System.IO.Ports.SerialPort ();                   Passing exception information to the user. MessageBox.Show (ex.                Message);            Return }} private void Button1_Click (object sender, EventArgs e) {string msgorder =            Txt_msg.text;            MessageBox.Show (Msgorder);                    Serialport.write (Msgorder);            private void Serialport_datareceived (object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { This.        Invoke (New EventHandler (Updateuitext)); } private void Updateuitext (object s, EventArgs e) {try {//must block a thread for a while                System.Threading.Thread.Sleep (500), in case of a transaction timeout, due to read being too fast                String txt = serialport.readexisting ();            Txt_received.text = txt;            }catch (Exception ex) {MessageBox.Show (ex.            Message.tostring ()); }} private void Form1_formclosing (object sender, FormClosingEventArgs e) {TR y {if (serialPort! = null && serialport.isopen) {ser                    Ialport.close ();                Serialport.dispose ();                   }} catch (Exception ex) {//To pass exception information to the user. MessageBox.Show (ex.                Message);            Return }        }            }}

At this point, a simple and complete serial communication is completed, I hope you have some help

Reprint please don't forget to mark the source, thank you ~

C # serial Communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.