一、步骤描述
- 硬件连接:将 RS-485 转换器连接到计算机(通常是通过 USB 转 RS-485 转换器)。
- 安装相关库:如果使用 USB 转串口适配器,可能需要安装对应的驱动。
- 串口配置:配置串口参数,如波特率、数据位、停止位、校验位等。
- 数据收发:通过串口进行数据的发送与接收。
RS-485 通常是半双工或全双工通信协议,因此我们需要根据实际硬件配置来设置串口的相关参数。
二、代码实现
注意:先引入类库 System.IO.Ports
public void Init()
{
// 配置串口
SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
// 打开串口
serialPort.Open();
//将发送指令转字节
byte[] hexArray = HexStringToByteArray("01 24 00 05 02 32");
serialPort.Write(hexArray, 0, hexArray.Length);
Thread.Sleep(100);//延迟几毫秒获取回传数据,避免设备没收到信号就去查收回收数据
// 读取串口数据
int byteLength = serialPort.BytesToRead;
if (byteLength <= 0)
return;//没有读取到数据长度
// 创建缓冲区并读取所有字节
byte[] readBuffer = new byte[byteLength + 1];
serialPort.Read(readBuffer, 1, byteLength);
//关闭串口
serialPort.Close();
}
/// <summary>
/// 字符串转换为字节数组
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] HexStringToByteArray(string hex)
{
hex = hex.Replace(" ", "");
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
实现以上方法即可实现485串口通讯发送、接收数据功能!!!