【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);
     }
}
相关推荐
蚰蜒螟14 分钟前
深入解析JVM字节码解释器执行流程(OpenJDK 17源码实现)
开发语言·jvm·python
keke1021 分钟前
Java【14_2】接口(Comparable和Comparator)、内部类
java·开发语言
思茂信息25 分钟前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
CN.LG31 分钟前
Java 乘号来重复字符串的功能
java·开发语言
川川菜鸟35 分钟前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模
萌新下岸多多关照36 分钟前
Java中synchronized 关键字
java·开发语言
醍醐三叶39 分钟前
C++文件操作--2 二进制文件操作
开发语言·c++
剽悍一小兔43 分钟前
linux,我启动一个springboot项目, 用java -jar xxx.jar & ,但是没多久这个java进程就会自动关掉
开发语言
li星野1 小时前
C++:C++内存管理
开发语言·c++
溟洵1 小时前
【C++ Qt】布局管理器
开发语言·c++·qt