/// <summary> /// 创建一个串口通信实例 /// </summary> /// <param name="portName">串口名</param> /// <param name="baudRate">波特率</param> /// <param name="parity">校验,偶校验(2) 无校验(0) 奇校验(1)</param> /// <param name="stopBits">停止位,1停止位(0) 1.5停止位(1) 2停止位(2)</param> /// <param name="flowControl">流量控制类型</param> public XKserialPort(string portName, int baudRate = 9600, byte parity = 0, byte stopBits = 0, FlowControlType flowControl = FlowControlType.None) { this.BaudRate = baudRate; this.Parity = parity; this.StopBits = stopBits; this.PortName = portName; this.FlowControl = flowControl; overlapped = new OVERLAPPED(); Open(); //打开端口 SetupComm((int)(hPort.DangerousGetHandle()), 1024, 1024); //设置端口缓冲区大小 if (portName.ToUpper().IndexOf("COM") != -1) { //如果是串口 SetTimeOuts();//设置默认超时 //配置串口参数,波特率,无校验,1位停止位 DCB dcb = initDCB((int)(hPort.DangerousGetHandle()), BaudRate, Parity, StopBits, flowControl); SetCommState((int)(hPort.DangerousGetHandle()), ref dcb); } //清空缓冲区 PurgeComm((int)(hPort.DangerousGetHandle()), PURGE_TXCLEAR); //关闭端口 hPort.Close(); }
public BehaviorTree_ConditionFuncDecoratorControl(BehaviorTree_ConditionFuncDecoratorControlConstructionParams csParam) : base(csParam) { InitConstruction(); NodeName = csParam.NodeName; Inverse = csParam.Inverse; FlowControl = csParam.FlowControl; BindingTemplateClassInstanceProperties(); }
/// <summary> /// 初始化DCB /// </summary> /// <param name="hComm">串口的句柄</param> /// <param name="BaudRate">波特率</param> /// <param name="Parity">奇偶校验</param> /// <param name="StopBits">停止位</param> /// <returns>初始化后的DCB</returns> private DCB initDCB(int hComm, int BaudRate, byte Parity, byte StopBits, FlowControlType flowControl) { DCB dcbCommPort = new DCB(); // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate = BaudRate; if (Parity > 0) { dcbCommPort.flags |= 2; } switch (flowControl) { case FlowControlType.Hardware: //开启DTR、RTS、CTS和DSR dcbCommPort.flags = 8237; break; case FlowControlType.Software: //开启XON/XOFF dcbCommPort.flags &= 4294963200; dcbCommPort.flags |= 897; break; case FlowControlType.None: //关闭DTR、RTS、CTS和DSR dcbCommPort.flags = 1; break; default: break; } dcbCommPort.Parity = Parity; dcbCommPort.ByteSize = 8; dcbCommPort.StopBits = StopBits; return(dcbCommPort); }