前言
C#为我们更好的与设备进行通讯,提供了SerialPort类于我们进行设备通讯,我们只需要将参数给与这个类并且实例化该类就可以通讯
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.IO.Ports; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 using System.Windows.Interop; 9 using System.Windows.Markup; 10 using System.Windows.Threading; 11 12 namespace Test 13 { 14 public class EleCommandHelper 15 16 { 17 private SerialPort serialPort; 18 private const Parity DefaultParity = Parity.None; 19 private const int DefaultDataBits = 8; 20 private const StopBits DefaultStopBits = StopBits.One; 21 22 public bool IsOrNotOpen() 23 { 24 return serialPort.IsOpen; 25 } 26 public void Close() 27 { 28 if (serialPort.IsOpen == true) 29 { 30 serialPort.Close(); 31 } 32 } 33 34 //实例化该类,需要填两个参数,一个波特率,一个串口名字 35 public EleCommandHelper(string portName, int baudRate) 36 { 37 serialPort = new SerialPort(portName, baudRate, DefaultParity, DefaultDataBits, DefaultStopBits); 38 //serialPort.DataReceived += SerialPort_DataReceived; 39 serialPort.Open(); 40 41 42 } 43 44 //通用 带返回值 45 public string GetSendModbus(string hexCommand) 46 { 47 48 byte[] commandBytes = HexStringToByteArray(hexCommand); 49 50 serialPort.Write(commandBytes, 0, commandBytes.Length); 51 // 等待响应 52 System.Threading.Thread.Sleep(500); 53 54 byte[] responseBytes = new byte[serialPort.BytesToRead]; 55 serialPort.Read(responseBytes, 0, responseBytes.Length); 56 57 string responseHex = BitConverter.ToString(responseBytes).Replace("-", " ").ToUpper().Trim(); 58 59 return responseHex; 60 } 61 62 private byte[] HexStringToByteArray(string hexString) 63 { 64 hexString = hexString.Replace(" ", "").Replace("-", "").ToUpper().Trim(); 65 int bytesCount = hexString.Length / 2; 66 byte[] bytes = new byte[bytesCount]; 67 68 for (int i = 0; i < bytesCount; i++) 69 { 70 string byteString = hexString.Substring(i * 2, 2); 71 bytes[i] = Convert.ToByte(byteString, 16); 72 } 73 74 return bytes; 75 } 76 } 77 }
标签:string,System,SerialPort,Modbus,串口,using,byte,serialPort From: https://www.cnblogs.com/ting1024/p/17662273.html