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

边栏推荐
- JS - DataTables control on the number of displays per page
- tornado之多进程服务
- Pytoch realizes logistic regression
- 力扣——二叉树剪枝
- Datax的学习笔记
- 数据库操作 技能6
- 李沐d2l(五)---多层感知机
- Hbuilderx runs the wechat developer tool "fail to open ide" to solve the error
- The child and binary tree- open root inversion of polynomials
- Innovus卡住,提示X Error:
猜你喜欢
随机推荐
pycharm 打开多个项目的两种小技巧
MySQL strengthen knowledge points
PAT 甲级 A1076 Forwards on Weibo
力扣题DFS
(1) CTS tradefed test framework environment construction
Day06 homework -- skill question 1
《Datawhale熊猫书》出版了!
Database operation skills 6
围棋智能机器人阿法狗,阿尔法狗机器人围棋
Sklearn machine learning foundation (linear regression, under fitting, over fitting, ridge regression, model loading and saving)
深度学习常用激活函数总结
数据库操作 题目二
数据库操作 技能6
Summary of common activation functions for deep learning
The Child and Binary Tree-多项式开根求逆
Pytoch realizes logistic regression
SQL入门——组合表
Pytoch learning - from tensor to LR
2022年上海市安全员C证考试试题及模拟考试
[eslint] Failed to load parser ‘@typescript-eslint/parser‘ declared in ‘package. json » eslint-confi









