C # the serial communication tutorial Simplifies everything and only retains the core functions. This is probably the easiest to understand,

Source: Internet
Author: User

C # the serial communication tutorial Simplifies everything and only retains the core functions. This is probably the easiest to understand,

For details about the serial port definition, see.

C # With the support of the powerful. Net class library, you only need to perform the following three steps:

1. Create

2 open

3 send/accept

 

1 Creation:

 

1. The namespace required for serial communication is as follows:

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

 

2. declared as a global variable because it is used globally.

private SerialPort spSend = new SerialPort();

 

3. Specify the serial port name

SpSend. PortName = "COM1"; // specify the port baud rate and check bit as needed. // in this example, only the name is specified.

 

2 open:
spSend.Open();

 

3 send/receive
// Send byte [] data = Encoding. ASCII. GetBytes ("message to be sent"); spSend. Write (data, 0, data. Length );

 

// Receives byte [] data = new byte [spSend. bytesToRead]; spSend. read (data, 0, data. length); String str = new ASCIIEncoding (). getString (data); // collected information

 

Okay, the core code is so simple. Let's take a look at the complete example below,

Interface:

Control name:

In the drop-down box, open the ComList button. In the btnOpen sending box, send the txtSend button. In the btnSend receiving box, txtInfo has a timer Timer1.

 

Complete source code:

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. IO. ports; // The required namespace using System. IO; using System. linq; using System. text; using System. windows. forms; namespace ChengChenXu.com. COMDemo {public partial class Form1: Form {private SerialPort spSend = new SerialPort (); // global variable public Form1 () {InitializeComponent ();} private voi D Form1_Load (object sender, EventArgs e) {// obtain the local serial port list string [] comList = SerialPort. getPortNames (); if (comList. length = 0) MessageBox. show ("the local machine does not have any serial port"); // bind the serial port list to the drop-down list and set the first item to the default value foreach (var com in comList) {ComList. items. add (com);} ComList. selectedIndex = 0; // start the timer to accept information. It is easier to understand timer1.Start ();} private void btnOpen_Click (object sender, EventArgs e) {if (ComList. items. count = 0) {Me SsageBox. Show ("No serial port found"); return ;}// determine whether to enable or disable the operation if (btnOpen. Text = "open serial port") {if (! SpSend. isOpen) {// set the port name // Here we only set the name of the port, all others use the default. spSend. portName = ComList. selectedItem. toString (); try {// open the serial port spSend. open ();} catch (Exception ex) {MessageBox. show (ex. message);} // update the control status this. btnOpen. text = "Disable serial port"; this. comList. enabled = false ;}} else if (btnOpen. text = "Close serial port") {// close the serial port spSend. close (); btnOpen. text = "open serial port"; ComList. enabled = true;} private void btnSend_Click (object sender, EventArgs e) {// send data // prepare data. Here, only the ASCII code can be converted to byte [] Before byte [] data = Encoding. ASCII. getBytes (txtSend. text); if (spSend. isOpen) {try {// three sending action parameters are respectively the length of the Start offset position of the Data spSend. write (data, 0, data. length);} catch (Exception ex) {MessageBox. show (ex. message) ;}} else {MessageBox. show ("port not opened") ;}} private void Receive () {// Receive information first determine whether the status is open if (spSend. isOpen) {// prepare to receive byte [] data = new byte [spSend. bytesToRead]; // receives the spSend action. read (data, 0, data. length); // convert the received information into a string and display it to this.txt Info in the control. text + = new ASCIIEncoding (). getString (data) ;}} private void timereffectick (object sender, EventArgs e) {// use a timer to periodically execute the receiving action at a time interval of 100 ms Receive ();}}}

 

 

How to test

Since serial communication is communication, it must be two parties involved. How can we test it on a single machine? The following are several methods:

Method 1 1 link the two or three pins of the computer serial port, then the receiver and the sender can be the same port. Because the two pins are responsible for sending and the Three pins are responsible for receiving, the connection can form a loop.

2. Use two computers and connect them with a serial Cable

3 using virtual serial port software is the easiest to use. Here we use this method for testing.

First download the software: VirtualSerialPortDriver: VirtualSerialPortDriver.rar

This is a paid software, with a half-month trial period. You can search for a cracked version if necessary.

 

After the software is installed, open the software, select two serial ports on the right, and click Add pair. I chose COM9 and COM10. Now we can see that COM9 and COM10 are available under Virtual ports on the left. They can implement communication.

 

After compiling the DEMO, run two instances: Choose COM9, choose COM10, and then open the serial port.

 

Now you can send messages to each other.

The Send for COM9 sent by COM9 has been sent to COM10

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

 

This example only uses the simplest example to demonstrate the serial communication process and simplify all functions.

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

 

This article is original to the blogger. for reprinting, please keep the source:
Http://www.chengchenxu.com/Article/27/netchuankou

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.