读取串口数据
/// <summary> /// 压力 传感器 /// </summary> public class ForceSensor { private static SerialPort _serialPort = new SerialPort(); /// <summary> /// 初始化参数 /// </summary> public static void InitForceSensor() { //设定串口参数 _serialPort.PortName = Global._forceSensor_Port.PortName; _serialPort.BaudRate = Global._forceSensor_Port.BaudRate; _serialPort.Parity = Global._forceSensor_Port.PortParity; _serialPort.DataBits = Global._forceSensor_Port.DataBit; _serialPort.StopBits = Global._forceSensor_Port.PortStop; _serialPort.ReadBufferSize = 1024; //注册接收数据的事件 _serialPort.DataReceived += _serialPort_DataReceived; if (_serialPort != null) { try { //打开连接 _serialPort.Open(); } catch (Exception) { } } } public static void CloseForceSensor() { if (_serialPort != null) { //关闭 _serialPort.Close(); } } public static void ReadForce() { byte[] read = new byte[] { 01, 03, 06, 06, 00, 02, 24, 82 }; } /// <summary> /// 读取(接收)串口数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { //Thread.Sleep(5); //读取串口缓冲区的字节数据 if (_serialPort.BytesToRead >= 32) { byte[] buffer = new byte[_serialPort.BytesToRead];//_serialPort.BytesToRead _serialPort.Read(buffer, 0, _serialPort.BytesToRead); DataHandle(buffer); } } catch (Exception) { } } /// <summary> /// 数据处理 /// </summary> /// <param name="buffer"></param> public static void DataHandle(byte[] buffer) { double res = 0; string str = Encoding.ASCII.GetString(buffer); string[] reslut = str.Split('\r'); int n = reslut.Length; string tmp = reslut[n / 2]; res = Convert.ToInt32(tmp); // Global._forceIns.ForceValue = Math.Round(res / 10.0-Global._forceIns.Force_pz, 1); } }