在下是位大四的电子专业的学生,考虑到嵌入式上位机的重要性,所以学习一下用C#写上位机,这也是我全靠看网上各位前辈的帖子和资料,才完成的,感谢各位前辈大佬!
首先,确定一下功能,正常的数据收发、十六进制收发、添加回车换行、自动发送,这些是经常会用到的功能。
犹豫再三还是从头开始吧,毕竟可能大家也和我一样,目前都是小白。
1.创建项目,及工程(我用的是Visual Studio 2019)选择windows 窗体应用;
2. 设置项目名、保存路径、还有框架,框架这里我选择的是.NET XXX 4.6.1因为后面程序设计完成,打包成.exe文件时,还需要用到这里的框架,最后点击创建;
3.创建项目完成后,进入工程管理器,左边白色部分就是Form编辑窗口;
4. 点击打开视图–》》工具箱,左边栏就出现了,各控件列表,这就是我们做上位机最基本的部分,点开公共控件、容器等就可以看到我们常用到的各个组件了;
5. 从工具箱中拖出Button等控件,并用鼠标点击选中,界面右下角则显示出其属性;
6. 现在添加我们需要的控件,从工具箱中
拖出4个GroupBox 分别将属性中的Text改为串口设置、定时发送、发送数据、接收数据。GroupBox 控件是将其它的控件放入其中,形成一个控件组。
拖出6个Label分别Text设置为: 串口号:、波特率:、数据位:、停止位:、奇偶校验: 、时间;
拖出5个ComboBox,分别将name(属性窗口往上拉就可以找到)设置为cbxCOMPort、cbxBaudRate、cbxDataBits、cbxStopBits、cbxParity;
拖出2个RadioButton,Text分别设置为:字符显示、HEX显示
name分别设置为rbnChar、rbnHex Checked分别为:True、False(将这2个放在同一个GroupBox中,RadioButton控件只能被选中一个)
拖出4个Button,Text分别设置为检测串口、打开串口、发送数据、清除数据,name分别设置为btnCheckCom、btnOpenCom、btnSendData、btnClearData
拖出3个CheckBox,Text分别设置为HEX发送、回车换行、自动发送;
拖出一个NumericUpDown;
拖出2个TextBox,name分别设置为tbxRecvData、tbxSendData,接收的ReadOnly属性设置为True。点击框上面的黑色小三角,选中MultiLine可任意伸缩大小。属性中的Font可修改字体大小等,ScrollBars设置为Both可垂直、水平拉伸信息;
拖出一个StatusStrip;
拖出2个Timer;
点击Form1面板上边沿部分,选中面板,在属性中BackColor可修改背景颜色,AcceptButton设置为btnSendData,在窗体上回车关联到发送数据按钮,Text可修改左上方名称,Icon可设置图标;
7. 双击控件可跳转到事件程序中,外框架搭好了,接下来就是写程序,完善其功能。
在Form1.cs中添加using System.IO.Ports;
using System.Text.RegularExpressions;//正则表达式,加入命名空间。
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.Ports;
using System.Text.RegularExpressions;//正则表达式
namespace uart_app
{
public partial class Form1 : Form
{
SerialPort sp = null;
bool isOpen = false;
bool isSetProperty = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
for (int i = 0; i < 20; i++)
{
cbxCOMPort.Items.Add("COM" + (i + 1).ToString());
}
cbxCOMPort.SelectedIndex = 0;
cbxBaudRate.Items.Add("1200");
cbxBaudRate.Items.Add("2400");
cbxBaudRate.Items.Add("4800");
cbxBaudRate.Items.Add("9600");
cbxBaudRate.Items.Add("19200");
cbxBaudRate.Items.Add("38400");
cbxBaudRate.Items.Add("115200");
cbxBaudRate.SelectedIndex = 6;
cbxStopBits.Items.Add("0");
cbxStopBits.Items.Add("1");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("2");
cbxStopBits.SelectedIndex = 1;
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = 0;
cbxDataBits.Items.Add("8");
cbxDataBits.Items.Add("7");
cbxDataBits.Items.Add("6");
cbxDataBits.Items.Add("5");
cbxDataBits.SelectedIndex = 0;
rbnChar.Checked = true;
/*添加时间显示*/
timer1.Interval = 1000;
timer1.Start();
}
private void btnCheckCom_Click(object sender, EventArgs e)
{
bool comExistence = false;
cbxCOMPort.Items.Clear();
for (int i = 0; i < 20; i++)
{
try
{
SerialPort sp = new SerialPort("COM" + (i + 1).ToString());
sp.Open();
sp.Close();
cbxCOMPort.Items.Add("COM" + (i + 1).ToString());
comExistence = true;
}
catch (Exception)
{
continue;
}
}
if (comExistence)
{
cbxCOMPort.SelectedIndex = 0;
}
else
{
MessageBox.Show("没有找到可用串口!", "错误提示!");
}
}
private bool CheckPortSetting()
{
if (cbxCOMPort.Text.Trim() == "") return false;
if (cbxBaudRate.Text.Trim() == "") return false;
if (cbxStopBits.Text.Trim() == "") return false;
if (cbxParity.Text.Trim() == "") return false;
if (cbxDataBits.Text.Trim() == "") return false;
return true;
}
private bool CheckSendData()
{
if (tbxSendData.Text.Trim() == "") return false;
return true;
}
private void SetProperty()
{
sp = new SerialPort();
sp.PortName = cbxCOMPort.Text.Trim();
sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());
if (cbxStopBits.Text.Trim() == "0")
{
sp.StopBits = StopBits.None;
}
else if (cbxStopBits.Text.Trim() == "1.5")
{
sp.StopBits = StopBits.OnePointFive;
}
else if (cbxStopBits.Text.Trim() == "2")
{
sp.StopBits = StopBits.Two;
}
else
{
sp.StopBits = StopBits.One;
}
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
if (cbxParity.Text.Trim() == "奇校验")
{
sp.Parity = Parity.Odd;
}
else if (cbxParity.Text.Trim() == "偶校验")
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}
sp.ReadTimeout = -1;
sp.RtsEnable = true;
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs eg)
{
System.Threading.Thread.Sleep(100);
this.Invoke((EventHandler)delegate//异步执行 一个线程
{
if (!rbnHex.Checked)//如果未选中name为rbnHex的控件
{
//tbxRecvData.Text += sp.ReadLine();
StringBuilder sb = new StringBuilder();
long rec_count = 0;
int num = sp.BytesToRead;
byte[] recbuf = new byte[num];
rec_count += num;
sp.Read(recbuf, 0, num);
sb.Clear();
try
{
Invoke((EventHandler)(delegate
{
sb.Append(Encoding.ASCII.GetString(recbuf)); //将整个数组解码为ASCII数组
tbxRecvData.AppendText(sb.ToString());
}
)
);
}
catch
{
MessageBox.Show("请勾选换行", "错误提示");
}
}
else if (rbnHex.Checked)//如果选中
{
Byte[] ReceivedData = new Byte[sp.BytesToRead];
sp.Read(ReceivedData, 0, ReceivedData.Length);
String RecvDataText = null;
for (int i = 0; i < ReceivedData.Length; i++)
{
RecvDataText += (ReceivedData[i].ToString("X2") + " ");//数组里接收到的数据转化为16进制
}
tbxRecvData.Text += RecvDataText;
}
sp.DiscardInBuffer();
});
}
private void btnOpenCom_Click(object sender, EventArgs e)
{
if (isOpen == false)
{
if (!CheckPortSetting())
{
MessageBox.Show("串口未设置", "错误提示");
return;
}
if (!isSetProperty)
{
SetProperty();
isSetProperty = true;
}
try
{
sp.Open();
isOpen = true;
btnOpenCom.Text = "关闭串口";
cbxCOMPort.Enabled = false;
cbxBaudRate.Enabled = false;
cbxDataBits.Enabled = false;
cbxParity.Enabled = false;
cbxStopBits.Enabled = false;
rbnChar.Enabled = false;
rbnHex.Enabled = false;
}
catch (Exception)
{
isSetProperty = false;
isOpen = false;
MessageBox.Show("串口无效或已被占用", "错误提示");
}
}
else if(isOpen ==true)
{
try
{
if (!timeBox3.Checked)
{
sp.Close();//关闭端口
isOpen = false;
btnOpenCom.Text = "打开串口";
cbxCOMPort.Enabled = true;
cbxBaudRate.Enabled = true;
cbxDataBits.Enabled = true;
cbxParity.Enabled = true;
cbxStopBits.Enabled = true;
rbnChar.Enabled = true;
rbnHex.Enabled = true;
}
else
{
MessageBox.Show("请先关闭自动发送", "错误提示");
}
}
catch (Exception)
{
MessageBox.Show("关闭串口时发生错误", "错误提示");
}
}
}
private void btnSendData_Click(object sender, EventArgs e)
{
byte[] textchar = new byte[1];
int num2 = 0;
if (isOpen)
{
try
{
if (!checkBox1.Checked)//如果没有选中十六进制发送
{
if (!checkBox2.Checked)//未选中回车换行
{
sp.Write(tbxSendData.Text);//串口发送 (发送框里的东西)
}
else
{
sp.WriteLine(tbxSendData.Text);
}
}
else//选择十六进制发送的时候
{
string buf = tbxSendData.Text;
string bartenm = @"\s";//正则表达式
string replace = "";
Regex rgx = new Regex(bartenm);
string senddata = rgx.Replace(buf, replace);
num2 = (senddata.Length - senddata.Length % 2) / 2;
for (int a = 0; a < num2; a++)
{
textchar[0] = Convert.ToByte(senddata.Substring(a * 2, 2), 16);
sp.Write(textchar, 0, 1);
}
if (senddata.Length % 2 != 0)
{
textchar[0] = Convert.ToByte(senddata.Substring(tbxSendData.Text.Length - 1, 2), 16);
sp.Write(textchar, 0, 1);
num2++;
}
}
}
catch
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
return;
}
}
else
{
MessageBox.Show("串口未打开错误提示!", "错误提示");
}
if (!CheckSendData())
{
MessageBox.Show("请输入要发送的数据", "错误提示");
}
}
private void btnClearData_Click(object sender, EventArgs e)
{
if (!timeBox3.Checked)
{
tbxRecvData.Text = "";
tbxSendData.Text = "";
}
else
{
MessageBox.Show("请先关闭自动发送", "错误提示");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
this.toolStripStatusLabel1.Text = "当前时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
private void timeBox3_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.Timer txTimer = new System.Windows.Forms.Timer();
if (timeBox3.Checked)
{
if (numericUpDown1.Value != 0)
{
if (CheckSendData())
{
txTimer.Enabled = false;
timer2.Interval = (int)numericUpDown1.Value; //定时器赋初值
timer2.Start();
}
else if(!CheckSendData())
{
timer2.Stop();
}
}
else if (numericUpDown1.Value == 0)
{
timer2.Stop();
}
}
else
{
txTimer.Enabled = true;
timer2.Stop();
}
}
private void timer2_Tick(object sender, EventArgs e)
{
btnSendData_Click(btnSendData, new EventArgs());
}
}
}