C # implement simple serial communication,

Source: Internet
Author: User

C # implement simple serial communication,
Preface

Based on the study and research attitude, the c # language is used to implement simple serial communication tools.

I. Serial Communication Principle

The concept of Serial communication is very simple. The Serial port sends and receives bytes by bit. Although it is slower than byte parallel communication, the serial port can use one line to send data while the other line to receive data. It is simple and can implement remote communication. Because serial communication is asynchronous, the port can send data on one line and receive data on the other line at the same time. Other cables are used for handshaking, but not required. The most important parameters for serial communication are the baud rate, data bit, stop bit, and parity. For two ports for communication, these parameters must match.

Common Terms

Baud rate:This is a parameter to measure the symbol transmission rate. It refers to the changes in the unit time after the signal is modulated, that is, the number of times the carrier parameter changes within the unit time, such as transmitting 240 characters per second, each character format contains 10 bits (one start bit, one stop bit, and eight data bits). At this time, the baud rate is 240Bd, And the bitrate is 10 bits * 240 BPS = 2400bps. Generally, the modulation rate is greater than the baud rate, such as the Manchester encoding ). Generally, the baud rates of telephone lines are 14400,28800 and 36600. The baud rate can be much greater than these values, but the baud rate is inversely proportional to the distance. The high baud rate is often used for communication between very close instruments. A typical example is the communication between devices on the GUI.

Data bit:This is a parameter used to measure the actual data bit in communication. When a computer sends an information package, the actual data is usually not 8 bits, and the standard values are 6, 7, and 8 bits. The setting depends on the information you want to transmit. For example, the standard ASCII code is 0 ~ 127 (7 digits ). The extended ASCII code is 0 ~ 255 (8 digits ). If the data uses simple text (Standard ASCII code), each packet uses 7-bit data. Each packet is a byte, including the start/stop bits, data bits, and parity bits. Because the actual data bit depends on the selection of the communication protocol, the term "package" refers to any communication situation.

Stop bit:Used to represent the last digit of a single package. The typical values are 1, 1.5, and 2. Because the data is scheduled on the transmission line, and each device has its own clock, it is very likely that there is a small non-synchronization between the two devices in the communication. Therefore, the stop bit is not only the end of the transmission, but also the opportunity for the computer to correct the clock synchronization. The more digits the stop bit, the higher the synchronization tolerance for different clocks, but the slower the data transmission rate.

Parity bit:A simple error checking method in serial communication. There are four error checking methods: Even, Odd, tall, and low. Of course, it is acceptable that there is no checkpoint. In the case of parity and odd parity, the serial port sets the parity bit (one digit after the data bit), and uses a value to ensure that the transmitted data has even or Odd logic highs. For example, if the data is 011, the parity check bit is 0 to ensure that the number of digits with high logic is an even number. If it is an odd check, the check bit is 1, so there are three logic High. High-level and low-level check data, simple location logic high or low-level Logic validation. In this way, the receiving device can know the status of a single position, and has the opportunity to determine whether there is noise interfering with communication or whether the transmission and receiving data are not synchronized.

Serial Port Pin Diagram

1 Carrier Detection (DCD) 2 accept data (RXD) 3 send data (TXD) 4 data terminal prepare (DTR)

5 signal ground line (SG) 6 data preparation (DSR) 7 request sending (RTS) 8 clear sending (CTS) 9 ringing indication (RI)

 

Ii. Use the System. IO. Port. SerialPort class to implement serial communication System. IO. Port. SerialPort class Introduction

System. IO. Port. SerialPortYes. NET FrameworkProvides methods, attributes, and events for developers to call and operate serial ports.

Call process 1. directly call the static method of SerialPort GetPortNames () to obtain the serial port name array of the current computer 2. initialize the SerialPort object according to the serial port name, set the parameters, and call the Open () method to Open the serial port 3. call the Write () method to send data. 4. register the listener for receiving data to obtain data (or read the received data cyclically in another thread. This article uses the registration listener to receive data)

 

Code Implementation
Using System; using System. IO. ports; using System. text; namespace PortControlDemo {public class PortControlHelper {# region field/attribute/delegate // <summary> // serial port object // </summary> private SerialPort sp; /// <summary> /// serial port receives data delegation /// </summary> public delegate void ComReceiveDataHandler (string data); public ComReceiveDataHandler OnComReceiveDataHandler = null; /// <summary> /// port name array /// </summary> publ Ic string [] PortNameArr {get; set ;}/// <summary> // The status of the serial port communication is enabled /// </summary> public bool PortState {get; set ;} = false; // <summary> // Encoding type // </summary> public Encoding EncodingType {get; set ;}= Encoding. ASCII; # endregion # region method public PortControlHelper () {PortNameArr = SerialPort. getPortNames (); sp = new SerialPort (); sp. dataReceived + = new SerialDataReceivedEventHandler (DataRec Eived );} /// <summary> /// open the port /// </summary> /// <param name = "portName"> port name </param> /// <param name = "boudRate"> baud rate </param> // <param name = "dataBit"> data bit </param> // <param name = "stopBit"> stop bit </param> // <param name = "timeout"> timeout </param> public void OpenPort (string portName, int boudRate = 115200, int dataBit = 8, int stopBit = 1, int timeout = 5000) {try {sp. portName = portName; sp. baudRat E = boudRate; sp. dataBits = dataBit; sp. stopBits = (StopBits) stopBit; sp. readTimeout = timeout; sp. open (); PortState = true;} catch (Exception e) {throw e ;}} /// <summary> /// close the port /// </summary> public void ClosePort () {try {sp. close (); PortState = false;} catch (Exception e) {throw e ;}} /// <summary> /// send data /// </summary> /// <param name = "sendData"> </param> public void SendData (strin G sendData) {try {sp. encoding = EncodingType; sp. write (sendData) ;}catch (Exception e) {throw e ;}} /// <summary> /// receives the data call back /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> private void DataReceived (object sender, serialDataReceivedEventArgs e) {byte [] buffer = new byte [sp. bytesToRead]; sp. read (buffer, 0, buffer. length); string str = EncodingType. getString (buff Er); if (OnComReceiveDataHandler! = Null) {OnComReceiveDataHandler (str) ;}# endregion }}
View Code

 

3. Compile Winform serial communication tool interface Preview
Operations

The main function of this interface is to operate two serial ports, one sending data and the other receiving data. Set parameters for the two serial ports on the left, and click "Open sending and receiving serial ports" after the settings are complete. If the two serial ports are opened successfully, data can be sent and received on the right.

Code Implementation
Using System; using System. windows. forms; namespace PortControlDemo {public partial class FrmPortControl: Form {# region field/attribute int [] BaudRateArr = new int [] {110,300,120 0, 2400,480 0, 115200 }; int [] DataBitArr = new int [] {6, 7, 8}; int [] StopBitArr = new int [] {1, 2, 3 }; int [] TimeoutArr = new int [] {500,100 0, 2000,500 0, 10000}; object [] CheckBitArr = new object [] {"None"}; private bool ReceiveState = false; private PortControlHelper pchSend; private PortControlHelper pchReceive; # endregion # region method // <summary> // initialize the control /// </summary> private void InitView () {cb_portNameSend.DataSource = pchSend. portNameArr; cb_portNameReceive.DataSource = pchReceive. portNameArr; listener = listener; cb_dataBit.DataSource = DataBitArr; cb_stopBit.DataSource = StopBitArr; cb_checkBit.DataSource = CheckBitArr; cb_timeout.DataSource = TimeoutArr; FreshBtnState (pchSend. portState & pchReceive. portState );} /// <summary> /// refresh button status /// </summary> /// <param name = "state"> </param> private void FreshBtnState (bool state) {if (state) {Btn_open.Text = "Disable the sending and receiving serial port"; Btn_send.Enabled = true; Btn_receive.Enabled = true;} else {Btn_open.Text = "enabled the sending and receiving serial port; btn_receive.Enabled = false ;}# endregion # region event public FrmPortControl () {InitializeComponent (); pchSend = new PortControlHelper (); pchReceive = new PortControlHelper (); InitView ();} /// <summary> /// click the send data button, send text data /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void Btn_send_Click (object sender, eventArgs e) {pchSend. sendData (tb_send.Text) ;}/// <summary> /// click the start receiving button, start listening to the serial port to receive the entry data /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void Btn_receive_Click (object sender, eventArgs e) {if (ReceiveState) {pchReceive. onComReceiveDataHandler-= new PortControlHelper. comReceiveDataHandler (ComReceiveData); Btn_receive.Text = "start receiving"; ReceiveState = false;} else {pchReceive. onComReceiveDataHandler + = new PortControlHelper. comReceiveDataHandler (ComReceiveData); Btn_receive.Text = "stop receiving"; ReceiveState = true ;}/// <summary> /// enable or disable the serial ports of the two communications, refresh button status /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void Btn_open_Click (object sender, eventArgs e) {if (pchSend. portState) {pchSend. closePort (); pchReceive. closePort ();} else {pchSend. openPort (cb_portNameSend.Text, int. parse (cb_baudRate.Text), int. parse (cb_dataBit.Text), int. parse (cb_stopBit.Text), int. parse (cb_timeout.Text); pchReceive. openPort (cb_portNameReceive.Text, int. parse (cb_baudRate.Text), int. parse (cb_dataBit.Text), int. parse (cb_stopBit.Text), int. parse (cb_timeout.Text);} FreshBtnState (pchSend. portState & pchReceive. portState); pchReceive. onComReceiveDataHandler + = new PortControlHelper. comReceiveDataHandler (ComReceiveData); Btn_receive.Text = "stop receiving"; ReceiveState = true ;}/// <summary> /// received data, write in the text box /// </summary> /// <param name = "data"> </param> private void ComReceiveData (string data) {this. invoke (new EventHandler (delegate {tb_receive.AppendText ($ "receipt: {data} \ n") ;}); # endregion }}
View Code

 

Summary

With the help classes provided by the framework, it is not difficult for us to implement serial communication, but there are still many details to pay attention. Writing everything is not easy. Come on!

Appendix

Build a tool for the serial port debugging environment and the source code address of this article. If you need a boot package, pick it up (strong • Strong _ • strong ).

Serial Port debugging Demo Source Code address: https://files.cnblogs.com/files/ElijahZeng/PortControlDemo.rar

Virtual serial port tool vspd: https://files.cnblogs.com/files/ElijahZeng/VSPD%E8%99%9A%E6%8B%9F%E4%B8%B2%E5%8F%A3%E5%B7%A5%E5%85%B7.rar

 

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.