C# serial communication example tutorial
Because I participated in a small project and needed to control the relay through the serial port, I learned basic serial port programming in the past two days. A colleague has a JAVA serial communication package, but it was downloaded from the Internet. It is quite messy and it is difficult to accurately grasp the process and content of serial communication. Therefore, I personally implemented basic serial communication programming using C# by learning the methods of online experts. The following is a summary of the learning results, I hope it will be helpful to everyone.
1. Introduction to serial communication
The serial interface (serial port) is a type that can convert parallel data characters received from the CPU into continuous serial The data stream is sent out, and the received serial data stream can be converted into parallel data characters and supplied to the CPU device. Generally, the circuit that completes this function is called a serial interface circuit.
The concept of serial communications (Serial Communications) is very simple. The serial port sends and receives bytes bit by bit. Although slower than byte-by-byte parallel communication, a serial port can send data on one wire while receiving data on another wire. The most important parameters of serial communication are baud rate, data bits, stop bits and parity. For two ports to communicate, these parameters must match.
1. Baud rate: This is a parameter that measures the symbol transmission rate. It refers to the change in unit time after the signal is modulated, that is, the number of carrier parameter changes per unit time. For example, 960 characters are transmitted per second, and each character format contains 10 bits (1 start bit, 1 Stop bit, 8 data bits), the baud rate at this time is 960Bd, and the bit rate is 10 bits * 960 bits/second = 9600bps.
2. Data bits: This is a parameter that measures the actual data bits in communication. When a computer sends a packet of information, the actual data is often not 8 bits; standard values are 6, 7, and 8 bits. The standard ASCII code is 0~127 (7 bits), and the extended ASCII code is 0~255 (8 bits).
3. Stop bit: used to represent the last few bits of a single packet. Typical values are 1, 1.5 and 2 bits. Since the data is timed on the transmission line, and each device has its own clock, it is possible for a small desynchronization between the two devices to occur during the communication. The stop bit therefore not only indicates the end of the transfer, but also provides the computer with an opportunity to correct clock synchronization.
4. Check digit: A simple error detection method in serial communication. There are four error detection modes: even, odd, high and low. Of course, it is also possible to have no check digit.
2. C# serial port programming class
Starting from .NET Framework 2.0, C# provides the SerialPort class for serial port control. Namespace:System.IO.Ports. For detailed member introduction, please refer to the MSDN documentation. The following introduces its commonly used fields, methods and events.
1. Commonly used fields:
Name | Description |
PortName | Get or set the communication port |
BaudRate | Get or set the serial baud rate |
DataBits | Get Or set the standard data bit length per byte |
Parity | Get or set the parity check protocol |
StopBits | Gets or sets the standard number of stop bits per byte |
2. Commonly used methods:
Name | Description |
Close | Close the port connection, set the IsOpen property to false, and release the internal Stream object |
GetPortNames | Get the serial port name array of the current computer |
Open | ## Open a new serial port connection |
## from the | SerialPortinput buffer Read |
Write data to the serial port output buffer |
Description | |
Indicates the method that will handle the data receiving event of the | SerialPortobject |
3. Basic Usage
The following is a combination of an existing relay to give serial communication Basic usage for reference.
1 using System; 2 using System.Windows.Forms; 3 using System.IO.Ports; 4 using System.Text; 5 6 namespace Traveller_SerialPortControl 7 { 8 public partial class Form1 : Form 9 { 10 //定义端口类 11 private SerialPort ComDevice = new SerialPort(); 12 public Form1() 13 { 14 InitializeComponent(); 15 InitralConfig(); 16 } 17 /// <summary> 18 /// 配置初始化 19 /// </summary> 20 private void InitralConfig() 21 { 22 //查询主机上存在的串口 23 comboBox_Port.Items.AddRange(SerialPort.GetPortNames()); 24 25 if (comboBox_Port.Items.Count > 0) 26 { 27 comboBox_Port.SelectedIndex = 0; 28 } 29 else 30 { 31 comboBox_Port.Text = "未检测到串口"; 32 } 33 comboBox_BaudRate.SelectedIndex = 5; 34 comboBox_DataBits.SelectedIndex = 0; 35 comboBox_StopBits.SelectedIndex = 0; 36 comboBox_CheckBits.SelectedIndex = 0; 37 pictureBox_Status.BackgroundImage = Properties.Resources.red; 38 39 //向ComDevice.DataReceived(是一个事件)注册一个方法Com_DataReceived,当端口类接收到信息时时会自动调用Com_DataReceived方法 40 ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); 41 } 42 43 /// <summary> 44 /// 一旦ComDevice.DataReceived事件发生,就将从串口接收到的数据显示到接收端对话框 45 /// </summary> 46 /// <param> 47 /// <param> 48 private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) 49 { 50 //开辟接收缓冲区 51 byte[] ReDatas = new byte[ComDevice.BytesToRead]; 52 //从串口读取数据 53 ComDevice.Read(ReDatas, 0, ReDatas.Length); 54 //实现数据的解码与显示 55 AddData(ReDatas); 56 } 57 58 /// <summary> 59 /// 解码过程 60 /// </summary> 61 /// <param>串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取 62 public void AddData(byte[] data) 63 { 64 if (radioButton_Hex.Checked) 65 { 66 StringBuilder sb = new StringBuilder(); 67 for (int i = 0; i 97 /// 接收端对话框显示消息 98 /// 99 /// <param>100 private void AddContent(string content)101 {102 BeginInvoke(new MethodInvoker(delegate103 {
104 textBox_Receive.AppendText(content);
105 }));106 }107 108 /// <summary>109 /// 串口开关110 /// </summary>111 /// <param>112 /// <param>113 private void button_Switch_Click(object sender, EventArgs e)114 {115 if (comboBox_Port.Items.Count 168 /// 将消息编码并发送169 /// 170 /// <param>171 /// <param>172 private void button_Send_Click(object sender, EventArgs e)173 {174 if (textBox_Receive.Text.Length > 0)175 {176 textBox_Receive.AppendText("\n");177 }178 179 byte[] sendData = null;180 181 if (radioButton_Hex.Checked)182 {183 sendData = strToHexByte(textBox_Send.Text.Trim());184 }185 else if (radioButton_ASCII.Checked)186 {187 sendData = Encoding.ASCII.GetBytes(textBox_Send.Text.Trim());188 }189 else if (radioButton_UTF8.Checked)190 {191 sendData = Encoding.UTF8.GetBytes(textBox_Send.Text.Trim());192 }193 else if (radioButton_Unicode.Checked)194 {195 sendData = Encoding.Unicode.GetBytes(textBox_Send.Text.Trim());196 }197 else198 {199 sendData = strToHexByte(textBox_Send.Text.Trim());200 }201 202 SendData(sendData);203 }204 205 /// <summary>206 /// 此函数将编码后的消息传递给串口207 /// </summary>208 /// <param>209 /// <returns></returns>210 public bool SendData(byte[] data)211 {212 if (ComDevice.IsOpen)213 {214 try215 {216 //将消息传递给串口217 ComDevice.Write(data, 0, data.Length);218 return true;219 }220 catch (Exception ex)221 {222 MessageBox.Show(ex.Message, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Error);223 }224 }225 else226 {227 MessageBox.Show("串口未开启", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);228 }229 return false;230 }231 232 /// <summary>233 /// 16进制编码234 /// </summary>235 /// <param>236 /// <returns></returns>237 private byte[] strToHexByte(string hexString)238 {239 hexString = hexString.Replace(" ", "");240 if ((hexString.Length % 2) != 0) hexString += " ";241 byte[] returnBytes = new byte[hexString.Length / 2];242 for (int i = 0; i
The above is the detailed content of C# serial communication example tutorial. For more information, please follow other related articles on the PHP Chinese website!

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software