C# 串口通信
2021/5/11 22:55:12
本文主要是介绍C# 串口通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
串口通信
- 1. 基本概念
- 2.C#代码实现串口通信
- 3. 资源下载地址
1. 基本概念
- 数据是串行发送的,比如RS232、RS422、RS485,一位一位地发送数据,就是串口通信。串口通信分为同步和异步。
- 串口通信要设置以下参数:
- 串口号:com1,com2…
- 波特率:9600,115200…
- 数据位:8,7,6
- 校验位:None,Even,Odd
- 停止位:1,2
- 9针脚,2针脚收数据,3针脚发数据
2.C#代码实现串口通信
- 串口实例化
- 设置串口参数
- 打开串口
- 发送数据
- 接收数据(事件响应)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Ports; namespace SerialPortCom { public partial class SerialPortForm : Form { //public delegate void DEL(byte[] buffer);//定义了一个委托 DEL #region 接收数据事件响应 /// <summary> /// 事件响应函数:每当有串口数据进入就响应 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DataRecv(object sender, SerialDataReceivedEventArgs e) { int counts = sp.BytesToRead; byte[] buffer = new byte[counts]; //读入(接收)数据 sp.Read(buffer, 0, counts); //DEL changeTextDelegate = new DEL(ChangeText);//实例化委托 委托类型 DEL 把 changeText函数转为DEL类型的委托 //显示(16进制/字符串) if (radioButtonString.Checked)//字符串 { //textBoxRec.Invoke(changeTextDelegate, buffer); //匿名委托 Invoke(new MethodInvoker(delegate () { textBoxRec.Text += Encoding.Default.GetString(buffer); labelReceByte.Text = buffer.Length.ToString(); })); } else//16进制 { Invoke(new MethodInvoker(delegate() { textBoxRec.Text += HexByteToString(buffer); labelReceByte.Text = buffer.Length.ToString(); })); //textBoxRec.Invoke(changeTextDelegate, buffer); } } #endregion #region 串口实例化 SerialPort sp = new SerialPort(); public SerialPortForm() { InitializeComponent(); } #endregion #region 设置串口参数 private void SerialPortForm_Load(object sender, EventArgs e) { string[] comNames = SerialPort.GetPortNames(); for(int i=0; i < comNames.Length; i++) { comboBoxPortNum.Items.Add(comNames[i]); } if(comNames.Length>0) { comboBoxPortNum.SelectedIndex = 0; } comboBoxBaudRate.SelectedIndex = 1; comboBoxDataBit.SelectedIndex = 0; comboBoxCheckBit.SelectedIndex = 0; comboBoxStopBit.SelectedIndex = 0; } #endregion #region 打开串口 private void buttonOpenPort_Click(object sender, EventArgs e) { if(!sp.IsOpen) { sp.PortName = comboBoxPortNum.Text;//配置串口号 sp.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);//配置波特率 sp.DataBits = Convert.ToInt32(comboBoxDataBit.Text);//配置数据位 //两种string转枚举的方式 sp.Parity = (Parity)Enum.Parse(typeof(Parity),comboBoxCheckBit.Text);//校验位 sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBoxStopBit.Text); //sp.StopBits = (StopBits)int.Parse(comboBoxStopBit.Text);//停止位 sp.Open();//打开串口 buttonOpenPort.Text = "关闭串口"; buttonOpenPort.BackColor = Color.Green; sp.DataReceived += new SerialDataReceivedEventHandler(DataRecv); } else { sp.Close();//关闭窗口 buttonOpenPort.Text = "打开串口"; buttonOpenPort.BackColor = Color.White; } } #endregion #region 发送 private void buttonSend_Click(object sender, EventArgs e) { if (sp.IsOpen) { byte[] buffer; if (radioButtonString.Checked)//字符串发送 { buffer = Encoding.Default.GetBytes(textBoxSend.Text);//string转ASCCII sp.Write(buffer, 0, buffer.Length); } else//16进制发送 { buffer = StringToHexByte(textBoxSend.Text); sp.Write(buffer, 0, buffer.Length); } labelSendByte.Text = Convert.ToString(buffer.Length); } else { MessageBox.Show(""); } } #endregion #region 字符串转16进制 public byte[] StringToHexByte(string str) { str.Replace(" ", ""); str.Replace("0x", ""); str.Replace("0X", ""); if (str.Length % 2 != 0) { str = "0" + str; } byte[] newbuffer = new byte[str.Length / 2]; for (int i = 0; i < str.Length / 2; i++) { newbuffer[i] = Convert.ToByte(str.Substring(i * 2, 2), 16); } return newbuffer; } #endregion #region 16进制转字符串 public string HexByteToString(byte[] buffer) { string str = ""; if(buffer==null) { return "0"; } for(int i=0;i<buffer.Length;i++) { str += buffer[i].ToString("X2"); } return str; } #endregion #region 清空发送字节 private void buttonClearSendByte_Click(object sender, EventArgs e) { labelSendByte.Text = "0"; } #endregion #region 清空接收字节 private void buttonClearRecvByte_Click(object sender, EventArgs e) { labelReceByte.Text = "0"; } #endregion #region 清空发送区 private void buttonClearSend_Click(object sender, EventArgs e) { textBoxSend.Text = ""; } #endregion #region 清空接收区 private void buttonClearRecv_Click(object sender, EventArgs e) { textBoxRec.Text = ""; } #endregion //private void ChangeText(byte[] buffer) //{ // if (radioButtonString.Checked) // { // textBoxRec.Text += Encoding.Default.GetString(buffer); // labelReceByte.Text = buffer.Length.ToString(); // } // else // { // textBoxRec.Text += HexByteToString(buffer); // labelReceByte.Text = buffer.Length.ToString(); // } //} } }
3. 资源下载地址
https://download.csdn.net/download/weixin_38566632/18594094
这篇关于C# 串口通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#