当前位置:网站首页>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 :

边栏推荐
- Numpy Foundation
- 力扣链表题
- Pat grade a a1013 battle over cities
- NFT与数字藏品到底有何区别?
- What is the difference between NFT and digital collections?
- jvm命令归纳
- Dynamic SQL and exceptions of pl/sql
- How to quickly learn a programming language
- TCP solves the problem of short write
- Two tips for pycharm to open multiple projects
猜你喜欢

NTT (fast number theory transformation) polynomial inverse 1500 word analysis

NTT(快速数论变换)多项式求逆 一千五百字解析

Horizontal comparison of the data of the top ten blue chip NFTs in the past half year

垂直搜索

Dynamic SQL and exceptions of pl/sql

Day06 operation -- addition, deletion, modification and query

2022茶艺师(中级)特种作业证考试题库模拟考试平台操作

数据库操作技能7

2022年上海市安全员C证考试试题及模拟考试

语音聊天app源码——钠斯直播系统源码
随机推荐
JS closure: binding of functions to their lexical environment
redis原理和使用-基本特性
Day06 homework -- skill question 2
Espressif plays with the compilation environment
Polynomial open root
Where are the laravel framework log files stored? How to use it?
756. 蛇形矩阵
围棋智能机器人阿法狗,阿尔法狗机器人围棋
Matlab 绘制阴影误差图
Pytoch realizes logistic regression
数据库操作技能7
day06 作业--增删改查
Unity topdown character movement control
Apple generated and verified tokens for PHP
李沐d2l(四)---Softmax回归
Day06 homework - skill question 6
公告 | FISCO BCOS v3.0-rc4发布,新增Max版,可支撑海量交易上链
Grain College of all learning source code
ES6 modular import and export) (realize page nesting)
Day06 homework -- skill question 1