/// <summary> /// 打开串口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOpenCom_Click(object sender, EventArgs e) { if (spu != null) { if (spu.IsOpen) { spu.ClosePort(); btnOpenCom.Text = "连接"; } else { spu.OpenPort(); btnOpenCom.Text = "断开"; btnSend.Enabled = true; } } else { spu = new SerialPortUtil(combComList.Text, combBaudList.Text, combParityList.Text, combDataBit.Text, combStopbitList.Text); //数据接收 spu.DataReceived += new DataReceivedEventHandler(serial_DataReceived); spu.OpenPort(); btnOpenCom.Text = "断开"; btnSend.Enabled = true; } showSate(); }
/// <summary> /// 初始化串口数据 /// </summary> public void init() { btnSend.Enabled = false; //串口号初始化 SerialPortUtil.SetPortNameValues(combComList); if (combComList.Items.Count > 0) { combComList.SelectedIndex = 0; } //波特率初始化 SerialPortUtil.SetBauRateValues(combBaudList); combBaudList.SelectedIndex = 8; //数据位 SerialPortUtil.SetDataBitsValues(combDataBit); combDataBit.SelectedIndex = 3; //校验位 SerialPortUtil.SetParityValues(combParityList); combParityList.SelectedIndex = 0; //停止位 SerialPortUtil.SetStopBitValues(combStopbitList); combStopbitList.SelectedIndex = 1; }
/// <summary> /// 数据发送 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSend_Click(object sender, EventArgs e) { txtLogs.AppendText("手动发送!" + Environment.NewLine); //按16进制发送 if (radHEXSend.Checked) { string hexStr = txtSend.Text.Replace("0x", ""); if (SerialPortUtil.IsHexadecimal(hexStr)) { txtLogs.AppendText("……>发送数据:" + txtSend.Text + Environment.NewLine); spu.WriteData(SerialPortUtil.HexToByte(hexStr)); } else { MessageBox.Show("16进制数格式不正确,请使用0xFF与FF格式"); } } else { txtLogs.AppendText("……>发送数据:" + txtSend.Text + Environment.NewLine); spu.WriteData(txtSend.Text); } beforDT = DateTime.Now; }