当前位置:网站首页>Sending and receiving of C serialport
Sending and receiving of C serialport
2022-07-26 09:10:00 【InfoQ】
Preface :
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

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 :


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
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 .


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
}

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
summary :

边栏推荐
猜你喜欢
论文笔记: 知识图谱 KGAT (未完暂存)
Qtcreator reports an error: you need to set an executable in the custom run configuration
Nuxt - Project packaging deployment and online to server process (SSR server rendering)
CSDN TOP1“一个处女座的程序猿“如何通过写作成为百万粉丝博主?
数据库操作技能7
Matlab 绘制阴影误差图
Database operation skills 7
Clean the label folder
Study notes of automatic control principle -- correction and synthesis of automatic control system
对标注文件夹进行清洗
随机推荐
Hbuilderx runs the wechat developer tool "fail to open ide" to solve the error
多项式开根
力扣题DFS
Learning notes of automatic control principle - Performance Analysis of continuous time system
Zipkin安装和使用
Day06 homework -- skill question 2
原根与NTT 五千字详解
CSDN TOP1“一个处女座的程序猿“如何通过写作成为百万粉丝博主?
Grain College of all learning source code
CSDN Top1 "how does a Virgo procedural ape" become a blogger with millions of fans through writing?
垂直搜索
本地缓存
HBuilderX 运行微信开发者工具 “Fail to open IDE“报错解决
NTT(快速数论变换)多项式求逆 一千五百字解析
Original root and NTT 5000 word explanation
2022流动式起重机司机考试题模拟考试题库模拟考试平台操作
Unity topdown character movement control
堆外内存的使用
数据库操作 题目二
Database operation topic 2