private void SetPortProperty()//设置串口的属性
{
sp = new SerialPort(); //新建
sp.PortName = COMPort.Text.Trim();//设置串口名
sp.BaudRate = Convert.ToInt32(BaudRate.Text.Trim());//设置串口的波特率
float f = Convert.ToSingle(StopBits1.Text.Trim());//设置停止位
if (f == 0)
{
sp.StopBits = StopBits.None;
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;
}
else if (f == 1)
{
sp.StopBits = StopBits.One;
}
else if (f == 2)
{
sp.StopBits = StopBits.Two;
}
else
{
sp.StopBits = StopBits.One;
}
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());//设置数据位
string s = cbxParity.Text.Trim(); //设置奇偶校验位
if (s.CompareTo("无") == 0)
{
sp.Parity = Parity.None;
}
else if (s.CompareTo("奇校验") == 0)
{
sp.Parity = Parity.Odd;
}
else if (s.CompareTo("偶校验") == 0)
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}
sp.ReadTimeout = -1;//设置超时读取时间
sp.RtsEnable = true;
//定义DataReceived 事件,当串口收到数据后触发事件
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
if (rbnHex.Checked)
{
isHex = true;
}
else
{
isHex = false;
}
}