当前位置:网站首页>Sending and receiving of C serialport
Sending and receiving of C serialport
2022-07-26 09:10:00 【InfoQ】
Preface :
Last time, the blogger explained the serial port control Serialport Configuration of , In this issue, I will explain Serialport Send and receive of , This SerialPort The control of serial communication provides the communication between host computer and MCU , There are many ways , It can be convenient for everyone to use , It's also easy to use .
Once a day , Prevent puppy love :

1.SerialPort Serial port control sending configuration
1.1 Take the project of the last article , I set up the children's shoes on the basis of that project. You can see the previous article of the blogger , We need to set up the interface first , Send box , Receiving frame , Send button

1.2 So let's see serialPort Send several interfaces it provides :
public void Write(byte[] buffer, int offset, int count);
Writes a specified number of bytes to the serial port using the data in the buffer .
// buffer: An array of bytes containing the data to be written to the port .
// offset: buffer Zero based byte offset in parameter , Start copying bytes to port... From here .
// count: Number of bytes to write .
public void Write(string text);
Writes the specified string to the serial port .
text: Output string .
public void Write(char[] buffer, int offset, int count);
Writes a specified number of characters to the serial port using the data in the buffer .
// buffer: The character array containing the data to be written to the port .
// offset: buffer Zero based byte offset in parameter , Start copying bytes to port... From here .
// count: The number of characters to write .
public void WriteLine(string text);
// The specified string and System.IO.Ports.SerialPort.NewLine Write value to output buffer .
// text: The string to write to the output buffer .
- 3 Double click the send button to automatically generate the method function , Write the method we sent :


1.4 The code is as follows : It can be used directly , The premise is that your interface is the same as that of the blogger , Note whether the interface controls correspond to the blogger function trigger , Not to change the trigger of the interface , Refer to the previous article for details .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Serilport
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void SearchAndAddSerialToComboBox(object sender, EventArgs e)
{
string Buffer;
comboBox1.Items.Clear(); // Records scanned before the beginning of the Qing Dynasty
for (int i = 0; i < 20; i++)
{
try
{
Buffer = "COM" + i.ToString(); // get COM1-20
serialPort1.PortName = Buffer; // obtain COM Information
serialPort1.Open(); // Open the serial port
comboBox1.Items.Add(Buffer);
comboBox1.Text = Buffer; // Add serial port to get recordset
serialPort1.Close(); // Turn off the serial port
}
catch { }
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text, 10);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text, 10);
if (comboBox4.Text == "None") { serialPort1.Parity = Parity.None; }
else if (comboBox4.Text == " Odd check ") { serialPort1.Parity = Parity.Odd; }
else if (comboBox4.Text == " Even check ") { serialPort1.Parity = Parity.Even; }
else if (comboBox4.Text == "Mark") { serialPort1.Parity = Parity.Mark; }
else if (comboBox4.Text == " Space check ") { serialPort1.Parity = Parity.Space; }
if (comboBox5.Text == "1")
{
serialPort1.StopBits = StopBits.One;
}
else if (comboBox5.Text == "1.5")
{
serialPort1.StopBits = StopBits.OnePointFive;
}
else if (comboBox5.Text == "1.5")
{
serialPort1.StopBits = StopBits.Two;
}
//serialPort1.ReadTimeout(2000);
serialPort1.Open();
button2.Enabled = false;// The open serial port button is not available
//button3.Enabled = true;// Turn off the serial port
}
catch
{
MessageBox.Show(" Port error , Please check the serial port ", " error ");
}
}
private void button1_Click(object sender, EventArgs e)
{
string str = textBox2.Text;// Get the data of the sending box
byte[] Data = new byte[1];// As a container for sending
if (serialPort1.IsOpen)// Judge whether our serial port is open
{
for (int j = 0; j < str.Length; j++)// Traverse our send statement , Bloggers now send one by one
{
if (str[j] == ' ')// Our send statements are separated by spaces , We're going to traverse
{
continue;
}
else
{
try
{
Data[0] = Convert.ToByte(str.Substring(j, 2), 16);//substring It's from j The location of the take str character string 2 Bytes ,16 Hexadecimal number
}
catch
{
MessageBox.Show(" Please check the hexadecimal data format error ");
}
try
{
serialPort1.Write(Data, 0, 1);// This means sending ,data data , from 0 The position begins , Take a value .
j++;
}
catch
{
MessageBox.Show(" Port send failed , The system will close the current serial port error ");
serialPort1.Close();// Turn off the serial port
}
}
}
}
}
}
}
2.SarilPort Serial port control receiving configuration
2.1 In understanding SerialPort Interface of receiving method
public int Read(char[] buffer, int offset, int count);
from System.IO.Ports.SerialPort Read some characters from the input buffer , These characters are then written to the character array at the specified offset .
// buffer: An array of bytes into which input is written .
// offset: The number of bytes to write buffer Offset in .
// count: The maximum number of bytes read . If count Greater than the number of bytes in the input buffer , Read fewer bytes .
public int Read(byte[] buffer, int offset, int count);
from System.IO.Ports.SerialPort The input buffer reads some bytes and writes those bytes to the offset specified in the byte array .
// buffer: An array of bytes into which input is written .
// offset: The number of bytes to write buffer Offset in .
// count: The maximum number of bytes read . If count Greater than the number of bytes in the input buffer , Read fewer bytes .
public int ReadByte();
from System.IO.Ports.SerialPort A byte is synchronously read from the input buffer .
public int ReadChar();
from System.IO.Ports.SerialPort Read a character synchronously from the input buffer .
public string ReadExisting();
On the basis of coding , Read System.IO.Ports.SerialPort Object and all immediately available bytes in the input buffer .
public string ReadLine();
Read all the way to... In the input buffer System.IO.Ports.SerialPort.NewLine value .
public string ReadTo(string value);
Read until the specified... In the input buffer value String .
value: A value indicating the stop position of the read operation .
2.2, Create the receiving function according to the screenshot ,SerialPort Automatically receive data


2.3 If you don't want to use loops , Data can be read out at one time , So it won't be so troublesome , Read its own interface carefully , Find your own interface , I'll send my code to you for reference :
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte data = 0;
int len = 0;
int bufsize = (int)serialPort1.BytesToRead;// Get the number of cache bytes
while (len < bufsize)// Get one after another
{
data = (byte)serialPort1.ReadByte();// Get the value of the serial port , You can also use read The whole method is not read one by one
len++;
string str = Convert.ToString(data, 16).ToUpper();// After obtaining it, we will TextBox Medium output
if (str.Length == 1)// If the value we get is a bit, we fill in the front 0
{
textBox1.AppendText(" 0" + str);
}
else
{
textBox1.AppendText(" " + str);// The two values are separated by a space in front
}
}
textBox1.AppendText(System.Environment.NewLine);// Line break
serialPort1.DiscardInBuffer();// Clear the previous cache
}
3. show ,SerialPort Send and receive , Blogger here happens to have a single chip microcomputer , Let me show you , If you're interested in this , Virtual serial port can also be used , Simulate and play .

notes : Bloggers report a thread error when running C# abnormal : Has triggered : " Invalid inter thread operation : Never create controls “textBox1” Thread access it ." (System.InvalidOperationException), Need to be in Form1 Add code inside
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; Disable capturing calls to the wrong thread .
summary :
The blogger just briefly introduced ,C# SerialPort Sending and receiving of serial port control , And demonstrated , Students interested in this aspect can learn , Bloggers are just beginners , I learned it because I was working on a project recently , learn C# Very few students , I hope you don't like it , It's not easy to create , give the thumbs-up , Focus on , Comments .

边栏推荐
猜你喜欢
随机推荐
Introduction to excellent verilog/fpga open source project (30) - brute force MD5
js闭包:函数和其词法环境的绑定
Mutual transformation of array structure and tree structure
Pat grade a a1076 forwards on Weibo
2022化工自动化控制仪表操作证考试题模拟考试平台操作
tornado之多进程服务
Uploading pictures on Alibaba cloud OSS
Grain College of all learning source code
聪明的美食家 C语言
PHP 之 Apple生成和验证令牌
语音聊天app源码——钠斯直播系统源码
基于序的评价指标 (特别针对推荐系统和多标签学习)
十大蓝筹NFT近半年数据横向对比
187. Repeated DNA sequence
力扣题DFS
机器学习中的概率模型
JDBC database connection pool (Druid Technology)
公告 | FISCO BCOS v3.0-rc4发布,新增Max版,可支撑海量交易上链
Day06 operation -- addition, deletion, modification and query
PAT 甲级 A1034 Head of a Gang









