【C#学习】串口编程

文章目录

第一步:加入串口控件

第二步:加入模块

csharp 复制代码
using System.IO.Ports;

第三步:编写相关函数功能

获取所有串口资源

csharp 复制代码
SerialPort.GetPortNames();

设置和打开

csharp 复制代码
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox3.SelectedItem.ToString());
serialPort1.StopBits = (StopBits)Convert.ToInt32(comboBox4.SelectedItem.ToString());
serialPort1.Parity = (Parity)Convert.ToInt32(comboBox5.SelectedIndex.ToString());

关闭串口

csharp 复制代码
serialPort1.Close();

发送字符串(string)

csharp 复制代码
serialPort1.WriteLine(data[i].ToString());

发送byte

csharp 复制代码
serialPort1.Write(data, 0, 13);

提示

  • 参数1:pointer to a byte array
  • 参数2:offset
  • 参数3:number of these bytes

检查串口状态

csharp 复制代码
if (serialPort1.IsOpen == true)
{
    ...
}

接受byte

csharp 复制代码
//receive data
byte[] rbuf=new byte[13];
serialPort1.Read(rbuf, 0, 13);

查询所有可用串口

csharp 复制代码
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
if (keyCom != null)
{
    string[] sSubKeys = keyCom.GetValueNames();
    scom.Items.Clear();
    foreach (string sName in sSubKeys)
    {
      string sValue = (string)keyCom.GetValue(sName);
       scom.Items.Add(sValue);
     }
}
相关推荐
hello kitty w16 分钟前
Python学习(11) ----- Python的泛型
windows·python·学习
讽刺人生Yan24 分钟前
RFSOC学习记录(五)带通采样定理
学习·fpga·rfsoc
weixin_445476681 小时前
Java并发编程——synchronized的实现原理与应用
java·开发语言·并发·synchronized
加号31 小时前
【C#】获取电脑网卡MAC地址
windows·c#
yi碗汤园1 小时前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
sali-tec1 小时前
C# 基于halcon的视觉工作流-章49-网面破损
开发语言·图像处理·算法·计算机视觉·c#
YuanlongWang1 小时前
c# ABP vNext 框架详解及其模块化开发思想介绍
开发语言·c#
报错小能手1 小时前
linux学习笔记(49)Redis详解(1)
linux·笔记·学习
QT 小鲜肉1 小时前
【个人成长笔记】在本地Windows系统中如何正确使用adb pull命令,把Linux系统中的文件或文件夹复制到本地中(亲测有效)
linux·windows·笔记·学习·adb
张人玉2 小时前
WPF布局控件(界面骨架核心)
开发语言·c#·wpf·布局控件