串口调试助手源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
串口调试助手预源代码
using System;
using System.Collections.Generic;
using ponentModel;
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();
}
sp1.Open();
//btnOpen.Enabled = false;
labSerial.Text = "串口号:" + sp1.PortName;
labState.Text = "状态:打开";
}
catch (System.Exception ex)
{
MessageBox.Show("Error:" + ex.Message, "Error");
return;
}
}
}
//private void CloseSerial_Click(object sender, EventArgs e)
//{
// if (sp1.IsOpen)
// {
// sp1.Close();
// labSerial.Text = "串口号:" + sp1.PortName;
// labState.Text = "状态:关闭";
// }