【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);
     }
}
相关推荐
神仙别闹18 分钟前
基于C语言开发的捕捉流星小游戏
c语言·开发语言
dadaobusi19 分钟前
学习:BPU
学习
程序员Sunday30 分钟前
Promise.all、allSettled、race、any 怎么选,失败后其他请求会怎样
开发语言·前端·javascript
ab1237681 小时前
OpenCV 学习笔记
笔记·opencv·学习
daxiangxm1 小时前
GEO策略:让AI直接引用你的内容
开发语言·团队开发·运维开发·个人开发·数据库开发
泡海椒1 小时前
JQuick-Excel 实战:用 VALIDATION 建立可维护的 Excel 导入校验
开发语言·python·excel
longlongzihan1 小时前
前缀积与后缀积 —— LeetCode 238. 除了自身以外数组的乘积
开发语言·c++·leetcode
szial1 小时前
JavaScript 的 call、apply 和 bind:如何控制函数调用
开发语言·前端·javascript
weixin_307779131 小时前
C++代码实现MATLAB中的cvpartition函数功能
开发语言·c++·算法·matlab
磁场转动100万匹1 小时前
Hive 学习第一天:搞懂它是什么,并搭好可用的环境
hive·hadoop·学习