文章目录
第一步:加入串口控件
第二步:加入模块
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);
}
}