【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);
     }
}
相关推荐
木易 士心1 天前
Android 开发核心技术深度解析
android·开发语言·python
化作星辰1 天前
深度学习_原理和进阶_PyTorch入门(2)后续语法2
pytorch·深度学习·学习
程序员烧烤1 天前
【Java基础14】函数式接口、lamba表达式、方法引用一网打尽(下)
java·开发语言
lzq6031 天前
Python虚拟环境全指南:venv与conda对比与实践
开发语言·python·conda
小年糕是糕手1 天前
【数据结构】常见的排序算法 -- 插入排序
c语言·开发语言·数据结构·学习·算法·leetcode·排序算法
我先去打把游戏先1 天前
ESP32C3开发指南(基于IDF):console控制台命令行交互功能
笔记·嵌入式硬件·mcu·物联网·学习·esp32·交互
星释1 天前
Rust 练习册 4:Deref trait 与智能指针
开发语言·后端·rust
心随雨下1 天前
Java中将System.out内容写入Tomcat日志
java·开发语言·tomcat
小码编匠1 天前
WPF 绘制图表合集-LiveCharts
后端·c#·.net
AI视觉网奇1 天前
yolo 获取异常样本 yolo 异常
开发语言·python·yolo