【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);
     }
}
相关推荐
长安第一美人5 小时前
C 语言可变参数(...)实战:从 logger_print 到通用日志函数
c语言·开发语言·嵌入式硬件·日志·工业应用开发
Larry_Yanan5 小时前
Qt多进程(一)进程间通信概括
开发语言·c++·qt·学习
superman超哥5 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
csdn_aspnet5 小时前
浅谈 C# 与 Data URI
c#
不爱吃糖的程序媛5 小时前
Ascend C开发工具包(asc-devkit)技术解读
c语言·开发语言
bu_shuo5 小时前
MATLAB奔溃记录
开发语言·matlab
你的冰西瓜6 小时前
C++标准模板库(STL)全面解析
开发语言·c++·stl
做cv的小昊6 小时前
【TJU】信息检索与分析课程笔记和练习(1)认识文献
经验分享·笔记·学习·搜索引擎·全文检索
徐先生 @_@|||6 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
利剑 -~6 小时前
jdk源码解析
java·开发语言