In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article "c # analog serial communication SerialPort how to achieve" most people do not understand, so the editor summed up the following content, detailed, clear steps, with a certain reference value, I hope you can get something after reading this article, let's take a look at this "c # analog serial communication SerialPort how to achieve" article.
First, leading knowledge
Serial port is the standard interface of computer, now PC (personal computer) generally has at least two serial ports COM1 and COM2. Serial port is widely used in data communication, computer network and distributed industrial control system. Serial communication is often used to exchange data and information.
Electrical standards and protocols include RS-232-C, RS-422, RS485, USB (Universal Serial Bus), etc.
The necessary settings to realize serial communication
The most important parameters of serial communication are baud rate, data bit, stop bit and parity.
For two ports that pass through, these parameters must match:
Baud rate
This is a parameter that measures the speed of communication. It represents * * the number of bit transmitted per second * *. For example, 300 baud means that 300 bit are sent per second, and the baud rate is inversely proportional to the distance. High baud rate is often used for communication between instruments placed very close to each other. A typical example is the communication of GPIB devices.
Data bit
This is a parameter that measures the actual data bits in the communication. When the computer sends a packet, the actual data will not be 8 bits, the standard values are 5, 7, and 8 bits, depending on the message you want to send. For example, the standard ASCII code is 0,127 (7 digits). The extended ASCII code is 0x255 (8 bits). If the data uses simple text (standard ASCII codes), then each packet uses 7 bits of data. Each packet refers to one byte, including start / stop bits, data bits and parity bits. Since the actual data bits depend on the choice of communication protocol, the term "packet" refers to any communication situation.
Stop bit
Used to represent the last bit of a single package. The typical values are 1 min 1.5 and 2 digits. Because the data is timed on the transmission line, and each device has its own clock, there is likely to be a small out-of-sync between the two devices in communication. Therefore, the stop bit not only indicates the end of the transmission, but also provides the computer with the opportunity to correct clock synchronization. The more bits applicable to stop bits, the greater the tolerance of different clock synchronization, but the slower the data transfer rate.
Parity bit
A simple error detection method in serial communication. There are four ways of error detection: even, odd, high and low. Of course, it is OK without a check bit. In the case of even and odd parity, the serial port sets the parity bit (the bit after the data bit) and uses a value to ensure that the transmitted data has even or odd logical high bits. For example, if the data is 011, then for even parity, the parity bit is 0, ensuring that the number of logically high digits is even. If it is odd, check bit 1, so there are 3 logical high bits. High and low bits do not really check the data, simple setting logic is high or logic is low. This enables the receiving device to know the status of a bit and has the opportunity to determine whether noise interferes with the communication or whether the transmitted and received data are out of sync.
2. Experiment
We will interact with two serial ports (COM1 and COM2) on a PC by simulating serial communication.
The software you need to use:
Launch Virtual Serial Port Driver Pro: virtual serial port. Use it to simulate the connection of two serial ports
Draw window
Code implementation
1. Use SerialPort to control serial port
Private SerialPort sp1 = new SerialPort ()
two。 Open the serial port
Private void button2_Click (object sender, EventArgs e) {if (! sp1.IsOpen) {try {/ / string slogans sp1.PortName = "COM1"; / / baud rate sp1.BaudRate = 115200 / / data bit sp1.DataBits = 8; / / stop bit sp1.StopBits = StopBits.One; / / parity bit sp1.Parity = Parity.Even Before the / / DataReceived event is sent, the number of characters in the internal buffer sp1.ReceivedBytesThreshold = 1; sp1.RtsEnable = true; sp1.DtrEnable = true; sp1.ReadTimeout = 3000; / / Control.CheckForIllegalCrossThreadCalls = false; / / indicates the method that will handle the data receiving event for the System.IO.Ports.SerialPort object. Sp1.DataReceived + = new System.IO.Ports.SerialDataReceivedEventHandler (sp1_DataReceived_1); / / Open serial port sp1.Open (); MessageBox.Show ("COM1 opened successfully!") ;} catch (Exception ex) {MessageBox.Show ("COM1 opened failed!") ;}} else {MessageBox.Show ("COM1 opened successfully") ;}}
3. Close the serial port
Private void button3_Click (object sender, EventArgs e) {if (sp1.IsOpen) {sp1.Close (); MessageBox.Show ("COM1 closed successfully!") ;}}
Opening and closing of Serial Port 2 and realization of homologous Serial Port 1
4. Send
Private void button1_Click (object sender, EventArgs e) {if (sp1.IsOpen) {if (! string.IsNullOrEmpty (this.textBox1.Text)) {sp1.WriteLine (this.textBox1.Text+ "\ r\ n") } else {MessageBox.Show ("send data is empty");}} else {MessageBox.Show ("COM1 is not open!") ;}}
5. Receive
StringBuilder builder1 = new StringBuilder (); / / public void sp1_DataReceived_1 (object sender, SerialDataReceivedEventArgs e) {Console.WriteLine ("receiving...") is triggered when the number of characters set by ReceivedBytesThreshold or the end of file character is received and placed in the input buffer; int n = sp1.BytesToRead / / record it first to avoid some reason, man-made reason, long time between several operations, cache inconsistent byte [] buf = new byte [n]; / declare a temporary array to store the current serial data sp1.Read (buf, 0, n); / / read buffer data builder1.Remove (0, builder1.Length) / / clear the contents of the string constructor builder1.Append (Encoding.ASCII.GetString (buf)); string comdata = builder1.ToString (); Console.WriteLine ("data: +" + comdata); this.Invoke (settextevent,comdata);}
Only the general receiving mode is realized here, and it is not rigorous and robust.
test
Use software to simulate serial connection
Open two programs
Open serial port 1 in one program, open serial port 2 in two programs, and send messages
Enter the character "hello,HanHanCheng!" in one program and find that it is received in two programs. Similarly, input in two programs can also be received in one program.
III. Summary
1. Because it is received by an asynchronous thread, you need to use a delegate to invoke the component across threads.
Public delegate void settext (string text); public event settext settextevent; public void set (string text) {this.textBox2.Text = text;} / / re-register settextevent + = set
The 2.DataReceived event trigger condition needs to be noted that it may not be triggered so that it cannot be received when implemented.
The trigger condition is that it is triggered when the number of characters set by ReceivedBytesThreshold or the end-of-file character is received and placed in the input buffer
4. Attachment complete code 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;using System.IO.Ports; namespace Training_USBCOM {public partial class Form1: Form {public Form1 () {InitializeComponent (); settextevent + = set;} private SerialPort sp1 = new SerialPort () StringBuilder builder = new StringBuilder (); private void button1_Click (object sender, EventArgs e) {if (sp1.IsOpen) {if (! string.IsNullOrEmpty (this.textBox1.Text)) {sp1.WriteLine (this.textBox1.Text+ "\ r\ n") } else {MessageBox.Show ("send data is empty");}} else {MessageBox.Show ("COM1 is not open!") ;} public delegate void settext (string text); public event settext settextevent; public void set (string text) {this.textBox2.Text = text;} StringBuilder builder1 = new StringBuilder () / / public void sp1_DataReceived_1 (object sender, SerialDataReceivedEventArgs e) {Console.WriteLine ("receiving...") is triggered when the number of characters set by ReceivedBytesThreshold or the end of file character is received and placed in the input buffer; int n = sp1.BytesToRead / / record it first to avoid some reason, man-made reason, long time between several operations, cache inconsistent byte [] buf = new byte [n]; / declare a temporary array to store the current serial data sp1.Read (buf, 0, n); / / read buffer data builder1.Remove (0, builder1.Length) / / clear the contents of the string constructor builder1.Append (Encoding.ASCII.GetString (buf)); string comdata = builder1.ToString (); Console.WriteLine ("data: +" + comdata); this.Invoke (settextevent,comdata) } private void button2_Click (object sender, EventArgs e) {if (! sp1.IsOpen) {try {/ / string slogans sp1.PortName = "COM1"; / / baud rate sp1.BaudRate = 115200 / / data bit sp1.DataBits = 8; / / stop bit sp1.StopBits = StopBits.One; / / parity bit sp1.Parity = Parity.Even Before the / / DataReceived event is sent, the number of characters in the internal buffer sp1.ReceivedBytesThreshold = 1; sp1.RtsEnable = true; sp1.DtrEnable = true; sp1.ReadTimeout = 3000; / / Control.CheckForIllegalCrossThreadCalls = false; / / indicates the method that will handle the data receiving event for the System.IO.Ports.SerialPort object. Sp1.DataReceived + = new System.IO.Ports.SerialDataReceivedEventHandler (sp1_DataReceived_1); / / Open serial port sp1.Open (); MessageBox.Show ("COM1 opened successfully!") ;} catch (Exception ex) {MessageBox.Show ("COM1 opened failed!") ;}} else {MessageBox.Show ("COM1 opened successfully") ;} private void button3_Click (object sender, EventArgs e) {if (sp1.IsOpen) {sp1.Close (); MessageBox.Show ("COM1 closed successfully!") ;} private void button5_Click (object sender, EventArgs e) {if (! sp1.IsOpen) {try {/ / string slogan sp1.PortName = "COM2" / / Baud rate sp1.BaudRate = 115200; / / data bit sp1.DataBits = 8; / / stop bit sp1.StopBits = StopBits.One; / / parity bit sp1.Parity = Parity.Even Sp1.ReceivedBytesThreshold = 1; sp1.RtsEnable = true; sp1.DtrEnable = true; sp1.ReadTimeout = 3000; Control.CheckForIllegalCrossThreadCalls = false; / / represents the method that will handle the data receive event for the System.IO.Ports.SerialPort object. Sp1.DataReceived + = new System.IO.Ports.SerialDataReceivedEventHandler (sp1_DataReceived_1); / / Open serial port sp1.Open (); MessageBox.Show ("COM2 opened successfully!") ;} catch (Exception ex) {MessageBox.Show ("COM2 opened failed!") ;}} else {MessageBox.Show ("COM2 opened successfully") ;} private void button4_Click (object sender, EventArgs e) {if (sp1.IsOpen) {sp1.Close (); MessageBox.Show ("COM2 closed successfully!") The above is the content of this article on "how to realize C # Analog Serial Communication SerialPort". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.