串口调试助手预源代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using DevExpress.XtraEditors;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication3
{
public partial class Form1 : XtraForm
{
SerialPort sp1 = new SerialPort();
int Flag = 0;
int StateChanged = 0;
int StateChanged_Ascii = 1;
int StateChanged_16 = 0;
string Temp = null;
string Temp_memoSend = null;
private void memoSend_EditValueChanged(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
sp1.DataReceived += sp1_DataReceived;
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
//检查是否有串口
string[] str = SerialPort.GetPortNames();
if (str == null)
{
MessageBox.Show("本机没有串口!", "error");
return;
}
//添加串口项目
foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
{
cbSerial.Properties.Items.Add(port);
}
//串口设置默认选择项
cbSerial.SelectedIndex = 0;
Control.CheckForIllegalCrossThreadCalls = false;
sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived); //订阅委托
}
private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void OpenSerial_Click(object sender, EventArgs e)
{
sp1.Close();
//SerialPort sp1 = new SerialPort();
if (!sp1.IsOpen)//串口是关闭的,设置参数,打开串口
{
try
{
//获取串口号
string serialName = cbSerial.SelectedItem.ToString();
sp1.PortName = serialName;
//设置各参数
string strBaudRate = cbBaudRate.Text;
string strDateBits = cbDataBits.Text;
string strStopBits = cbStop.Text;
sp1.BaudRate = Convert.ToInt32(strBaudRate);//波特率
sp1.DataBits = Convert.ToInt32(strDateBits);//数据位
switch (cbStop.Text) //停止位
{
case "1":
sp1.StopBits = StopBits.One;
break;
case "1.5":
sp1.StopBits = StopBits.One;
break;
case "2":
sp1.StopBits = StopBits.Two;
break;
default:
MessageBox.Show("Error:参数不正确!", "Error");
break;
}
switch (cbParity.Text) //校验位
{
case "无":
sp1.Parity = Parity.None;
break;
case "奇校验":
sp1.Parity = Parity.Odd;
break;
case "偶校验":
sp1.Parity = Parity.Even;
break;
default:
MessageBox.Show("Error:参数不正确!", "Error");
break;
}
if (sp1.IsOpen == true)
{
sp1.Close();
}
16进制字符串转16进制数组 sp1.Open();
//btnOpen.Enabled = false;
labSerial.Text = "串口号:" + sp1.PortName;
labState.Text = "状 态:打开";
}
catch (System.Exception ex)
{
MessageBox.Show("Error:" + ex.Message, "Error");
return;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论