C # serial Communication Tutorial simplifies everything with only the core functionality this may be the easiest to understand tutorial

Source: Internet
Author: User
Tags rar

The definition of serial port, please know for yourself.

C # operation serial communication in. NET powerful class library, only three steps are required:

1 Create

2 Open

3 Send/Receive

1 Create:

1 The required namespaces for serial communication are as follows:

using System.IO.Ports; using System.IO;

2 declared as a global variable because it is used globally

Private New SerialPort ();

3 specifying the serial port name

" COM1 " ; // continue to specify port baud rate, check bit and other information as required // in the example we specify only the name, and the rest of it.

2 Open:
Spsend.open ();

3 Send/Receive
// Send byte [] data = Encoding.ASCII.GetBytes (" message to send "0, data.) Length);

// Receive byte New byte  0new asciiencoding (). GetString (data); // Information received

Well, the core code is that simple, see the full example below,

Interface:

Control Name:

drop-down box comlist Open button btnopen send box txtsend send button btnsend receive box Txtinfo There is also a timer Timer1

Full Source:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.IO.Ports;//Required NamespacesusingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespacechengchenxu.com.comdemo{ Public Partial classForm1:form {PrivateSerialPort Spsend =NewSerialPort ();//Global Variables         PublicForm1 () {InitializeComponent (); }         Private voidForm1_Load (Objectsender, EventArgs e) {            //get a list of native serial ports            string[] Comlist =Serialport.getportnames (); if(Comlist.length = =0) MessageBox.Show ("This machine does not have any serial port"); //bind the serial port list to the drop-down list, set the first item to the default value            foreach(varCominchcomlist)            {ComList.Items.Add (COM); } Comlist.selectedindex=0; //Start Timer to accept information, not multi-threading, easier to understandtimer1.        Start (); }        Private voidBtnopen_click (Objectsender, EventArgs e) {            if(ComList.Items.Count = =0) {MessageBox.Show ("no serial port found"); return; }             //decide whether to open or close the Operation            if(Btnopen.text = ="Open the serial port")            {                if(!spsend.isopen) {//Set port name//Here we just set the name of the port, all the others are used by default.Spsend.portname =ComList.SelectedItem.ToString (); Try                    {                        //Open the serial portSpsend.open (); }                    Catch(Exception ex) {MessageBox.Show (ex).                    Message); }                    //Update control State                     This. Btnopen.text ="Close the serial port";  This. comlist.enabled =false; }            }            Else if(btnopen.text=="Close the serial port")            {                //Close the serial portSpsend.close (); Btnopen.text="Open the serial port"; Comlist.enabled=true; }        }         Private voidBtnsend_click (Objectsender, EventArgs e) {            //Send Data//Prepare data Here we only implement send ASCII code other can first convert to byte[] then send            byte[] data =Encoding.ASCII.GetBytes (Txtsend.text); if(spsend.isopen) {Try                {                    //Send action parameter three the length of the data start offset position respectivelySpsend.write (data,0, data.                Length); }                Catch(Exception ex) {MessageBox.Show (ex).                Message); }            }            Else{MessageBox.Show ("Port is not yet open"); }         }         Private voidReceive () {//receive information first to determine whether it is an open state            if(spsend.isopen) {//ready to receive                byte[] data =New byte[Spsend.bytestoread]; //Accept ActionSpsend.read (data,0, data.                Length); //turns the received message into a string to display in the control                 This. Txtinfo.text + =Newasciiencoding ().            GetString (data); }        }        Private voidTimer1_Tick (Objectsender, EventArgs e) {            //timer to perform the Receive action interval 100 milliseconds periodicallyReceive (); }    }}

How to test

Serial communication since it is a communication then definitely need to participate in two parties, how to test in a single machine? Here are a few ways to do this:

1 Method A computer serial Port 2 3 pin link up, then the receiver and the sender can be the same port. Because the 2 pin is responsible for sending, the 3 pin is responsible for receiving, the connection can form the loop

2 using two computers, connected by serial cable

3 using the virtual serial port software, the most simple and easy to use, here we use this method for testing.

First software Download: VirtualSerialPortDriver:VirtualSerialPortDriver.rar

This is a fee software, half-month trial period, if necessary, can search under whether there is cracked version

After installation, open the software, the right side select two ready to connect the serial port and then click Add Pair. I chose COM9 and COM10 can see the left virtual ports below already have the COM9 and COM10 now they can achieve communication

After compiling the demo, run two instances directly: one choice COM9 a choice COM10 and then all the serial ports open.

Now we can send messages to each other.

Send for COM9 issued by COM9 has been sent to COM10

COM9 has also received the message sent by COM10 Send for COM10

This example uses only the simplest examples to demonstrate the serial communication process, simplifying all functions for better understanding.

Source Code and DEMO:ChengChenXu.com.COMDemo.rar

This article for Bo Master Original, reproduced please retain the source:
Http://www.chengchenxu.com/Article/27/netchuankou

C # serial Communication Tutorial simplifies everything with only the core functionality this may be the easiest to understand tutorial

Related Article

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.