参考网上C#串口通信的程序,窗体winform,按下图添加按钮、文本框、下拉列表等控件,并在属性中修改名称。
用虚拟串口工具虚拟出一对串口com3和com4,然后用本软件连接com3,串口调试精灵连接com4,发送数据等其他功能还好,数据接收部分有问题。
只要一点击 串口调试精灵的发送按钮,发送数据,程序就被锁死。
经分析后,发现部分代码有错误,下边是经更正后的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports; //串口操作必备
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 串口通讯1
{
public partial class Form1 : Form
{
SerialPort sp = null;//声明一个串口类
bool isOpen = false;//打开串口标志位
bool isSetProperty = false; //串口属性标志位
bool isHex = false; //十六进制显示标志位
private int i;
public Form1()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e) //窗体加载后接下来要执行的操作
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
this.MaximizeBox = false;//最大化框不显示
for (int i = 0; i < 10; i++)//添加串口号,支持最大串口数是10
{
cbxCOMPort.Items.Add("COM" + (i + 1).ToString()); //向名为cbxCOMPort的列表框中用Add方法,添加条目,转化成字符串
}
; cbxCOMPort.SelectedIndex = 0;//设定默认串口
//列出波特率
cbxBaudBate.Items.Add("1200");
cbxBaudBate.Items.Add("2400");
cbxBaudBate.Items.Add("4800");
cbxBaudBate.Items.Add("9600");
cbxBaudBate.Items.Add("19200");
cbxBaudBate.Items.Add("38400");
cbxBaudBate.Items.Add("43000");
cbxBaudBate.Items.Add("56000");
cbxBaudBate.Items.Add("57600");
cbxBaudBate.Items.Add("115200");
cbxBaudBate.SelectedIndex = 3; //设定默认波特率
//列出停止位
cbxStopBits.Items.Add("0");
cbxStopBits.Items.Add("1");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("2");
cbxStopBits.SelectedIndex = 1; //设定默认停止位
//列出数据位
cbxDataBits.Items.Add("8");
cbxDataBits.Items.Add("7");
cbxDataBits.SelectedIndex = 0; //设定默认数据位
// 列出奇偶校验
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = 0; //设定默认校验方式
rbnChar.Checked = true; // 显示类型,rbnChar被选中
}
private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cbxBaudBate_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void tbxRecvData_TextChanged(object sender, EventArgs e)
{
}
private void tbxSendData_TextChanged(object sender, EventArgs e)
{
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void btnCheckCOM_Click(object sender, EventArgs e) //按下串口检测按钮,检测可用串口
{
bool comExistence = false;//设置有无可用串口志位,并初始化该标志位
cbxCOMPort.Items.Clear();//清除cbxCOMPort列表框中所有串口名称
for (int i = 0; i < 10; i++)
{
try
{
SerialPort sp = new SerialPort("COM" + (i + 1).ToString());//依次赋值COM1至COM10
sp.Open();//成对出现,检测可用串口
sp.Close();//串口可以打开和关闭证明串口可用,否则跳到异常处理
cbxCOMPort.Items.Add("COM" + (i + 1).ToString());
comExistence = true;
}
catch (Exception)
{
continue; //串口1不存在,则继续串口2,依次循环到COM10
}
}
if (comExistence)
{
cbxCOMPort.SelectedIndex = 0;//设置cbxCOMPort列表框首默认值
}
else
{
MessageBox.Show("没有找到可用串口!", "错误提示");
}
}
private bool CheckPortSetting() //私有函数颜色暗淡
{
if (cbxCOMPort.Text.Trim() =="") return false; //Trim()删除开头和结尾的空白字符
if (cbxBaudBate.Text.Trim() =="") return false;
if (cbxDataBits.Text.Trim() =="") return false;
if (cbxStopBits.Text.Trim() =="") return false;
if (cbxParity.Text.Trim() =="") return false;
return true; //串口号、波特率、数据位、停止位、校验同时不为空,则返回true
}
private bool CheckSendData()//检查发送数据是否为空
{
if (tbxRecvData.Text.Trim() == "") return false;
return true;
}
private void SetPortProperty()//设置串口属性
{
sp = new SerialPort();
sp.PortName = cbxCOMPort.Text.Trim();
sp.BaudRate = Convert.ToInt32(cbxBaudBate.Text.Trim());//设置波特率,波特率是把字符串转换为32位整型
float f = Convert.ToSingle(cbxStopBits.Text.Trim());
if(f==0)
{
sp.StopBits = StopBits.None;
}
else if (f == 1)
{
sp.StopBits = StopBits.One;
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;
}
else
{
sp.StopBits = StopBits.Two;
}
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());//设置数据位
if(cbxParity .Text .Trim ()=="奇校验")
{
sp.Parity = Parity.Odd;
}
if (cbxParity.Text.Trim() == "偶校验")
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}
sp.ReadTimeout = -1;//设置超时读取时间
sp.RtsEnable = true;//请求发送使能
//定义sp_DataReceived接收数据触发事件
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
if(rbnHex .Checked )
{
isHex = true;
}
else
{
isHex = false;
}
}
private void btnOpenCom_Click(object sender, EventArgs e)
{
if (isOpen == false)
{
if (!CheckPortSetting())//检查串口设置
{
MessageBox.Show("串口未设置!", "错误提示");
return;
}
if (!isSetProperty)//检查串口设置
{
SetPortProperty();
isSetProperty = true;
}
try
{
sp.Open();
isOpen = true;
btnCheckCOM.Text = "关闭串口";
//串口打开后则相关的串口设置按钮便不可再用
cbxCOMPort.Enabled = false;
cbxBaudBate.Enabled = false;
cbxDataBits.Enabled = false;
cbxParity.Enabled = false;
cbxStopBits.Enabled = false;
rbnChar.Enabled = false;
rbnChar.Enabled = false;
}
catch (Exception)
{
//打开串口失败后,相应标志位取消
isSetProperty = false;
isOpen = false;
MessageBox.Show("串口无效或已被占用!", "错误提示");
}
}
else
{
try //打开串口
{
sp.Close();
isOpen = false;
isSetProperty = false;
btnOpenCom.Text = "打开串口";
//关闭串口后,串口设置选项便可以继续使用
cbxCOMPort.Enabled = true;
cbxBaudBate.Enabled = true;
cbxDataBits.Enabled = true;
cbxParity.Enabled = true;
cbxStopBits.Enabled = true;
rbnChar.Enabled = true;
rbnHex.Enabled = true;
}
catch (Exception)
{
//lblStatus.Text = "关闭串口时发生错误";
}
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(100);//延时100ms等待接收完数据
//this.Invoke就是跨线程访问ui的方法,也是本文的范例Invoke
this.Invoke((EventHandler)(delegate
{
if (isHex == false)
{
tbxRecvData.Text += sp.ReadLine();
}
else
{
Byte[] ReceivedData = new Byte[sp.BytesToRead]; //创建接收字节数组
sp.Read(ReceivedData, 0, ReceivedData.Length); //读取所接收到的数据
String RecvDataText = null;
for (int i = 0; i < ReceivedData.Length - 1; i++)
{
RecvDataText += ("0x" + ReceivedData[i].ToString("X2") + "");
}
tbxRecvData.Text += RecvDataText;
}
sp.DiscardInBuffer(); //丢弃接收缓冲区数据
}));
}
private void btnCleanData_Click(object sender, EventArgs e)
{
tbxSendData.Text = "";
tbxRecvData.Text = "";
}
private void btnSend_Click(object sender, EventArgs e)
{
if (isOpen)//写串口数据
{
try
{
sp.WriteLine(tbxSendData.Text);//edit by xugang
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
return;
}
}
else
{
MessageBox.Show("串口没有打开!", "错误提示");
return;
}
if(!CheckSendData())//检查要发送的数据
{
MessageBox.Show("请输入要发送的数据!","错误提示");
return;
}
}
private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cbxParity_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
}
}
这里缺少几行代码,留给各位研究,补齐代码本程序还是可用的。