public static ParaService Install() { if (ps == null) { ps = new ParaService(); } return(ps); }
/// <summary> /// 打开串口 /// </summary> /// <returns></returns> public SerialPort OpenPort(SerialPara serialPara) { if (ParaService.Install().GetPort().Length == 0) { MessageBox.Show("打开串口错误,本机没有串口!", "警告"); return(null); } if (!sp.IsOpen) { try { string port = serialPara.Port; string baudRate = serialPara.BaudRate; string dataBits = serialPara.DataBits; string stopBits = serialPara.StopBit; string parity = serialPara.Parity; sp.PortName = port; sp.BaudRate = int.Parse(baudRate); sp.DataBits = int.Parse(dataBits); sp.StopBits = (StopBits)int.Parse(stopBits); switch (parity) //校验位 { case "none": sp.Parity = Parity.None; break; case "odd": sp.Parity = Parity.Odd; break; case "even": sp.Parity = Parity.Even; break; } //sp.ReadTimeout = 1000; //sp.WriteTimeout = 1000; sp.ReceivedBytesThreshold = 1; sp.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); sp.Open(); return(sp); } catch (Exception ex) { MessageBox.Show("串口参数设置错误!" + ex.Message, "错误"); return(null); } } return(sp); }