1、构思功能
串口助手在单片机开发中经常被用来调试,最基本的功能就是接收功能和发送功能,其次,串口在打开前需要进行一些设置:串口列表选择、波特率、数据位、校验位、停止位,这样就有了一个基本的雏形;然后我们在下一篇中在此功能上添加:ASCII/HEX显示,发送,发送新行功能,重复自动发送功能,显示接收数据时间这几项扩展功能;
2、设计布局
根据以上功能,将整个界面分为两块:设置界面(不可缩放)+ 接收区和发送区(可缩放),下面就来依次拖放控件实现:
1)容器控件(Panel)
2)文本标签控件(Lable)
3)下拉组合框控件(ComboBox)
4)按钮控件(Button)
5)文本框控件(TextBox)
6)串口组件(SerialPort)
//获取电脑当前可用串口并添加到选项列表中
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
public partial class Form1 : Form
{
private long receive_count = 0; //接收字节计数
private StringBuilder sb = new StringBuilder(); //为了避免在接收处理函数中反复调用,依然声明为一个全局变量
private StringBuilder s = new StringBuilder();
private DateTime current_time = new DateTime(); //为了避免在接收处理函数中反复调用,依然声明为一个全局变量
private StringBuilder builder = new StringBuilder(); //避免在事件处理方法中反复创建,定义为全局
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox_portname.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());//添加到串口框
button_clear.Enabled = false;
button_sent.Enabled = false;
comboBox_BaudRate.Text = "9600";
comboBox_datebit.Text = "8";
comboBox_parity.Text = "None";
comboBox_stopdit.Text = "1";
}
private void button_openport_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
button_openport.Text = "打开串口";
button_clear.Enabled = false;
button_sent.Enabled = false;
comboBox_BaudRate.Enabled = true;
comboBox_datebit.Enabled = true;
comboBox_parity.Enabled = true;
comboBox_portname.Enabled = true;
comboBox_stopdit.Enabled = true;
}
else
{
button_clear.Enabled = true;
button_sent.Enabled = true;
serialPort1.PortName = comboBox_portname.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox_BaudRate.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox_datebit.Text);
if (comboBox_parity.Text=="None")
serialPort1.Parity= System.IO.Ports.Parity.None;
else if(comboBox_parity.Text == "Odd")
serialPort1.Parity = System.IO.Ports.Parity.Odd;
else if(comboBox_parity.Text == "Even")
serialPort1.Parity = System.IO.Ports.Parity.Even;
else if(comboBox_parity.Text == "Mark")
serialPort1.Parity = System.IO.Ports.Parity.Mark;
else if (comboBox_parity.Text == "Space")
serialPort1.Parity = System.IO.Ports.Parity.Space;
if(comboBox_stopdit.Text=="1")
serialPort1.StopBits = System.IO.Ports.StopBits.One;
else if(comboBox_stopdit.Text == "1.5")
serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
else
serialPort1.StopBits = System.IO.Ports.StopBits.Two;
serialPort1.Open();
button_openport.Text = "关闭串口";
comboBox_BaudRate.Enabled = false;
comboBox_datebit.Enabled = false;
comboBox_parity.Enabled = false;
comboBox_portname.Enabled = false;
comboBox_stopdit.Enabled = false;
radioButton_hex.Checked = true;
radioButton2.Checked = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
comboBox_portname.Items.Clear();
comboBox_portname.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
button_openport.Text = "打开串口";
}
}
private void button_clear_Click(object sender, EventArgs e)
{
textBox_receiver.Text = "";
textBox_sent.Text = "";
}
private void button_sent_Click(object sender, EventArgs e)
{
byte[] temp = new byte[1];
byte[] adc = new byte[1];
try
{
if (serialPort1.IsOpen)
{
if (radioButton_hex.Checked)
{
int num = 0;
string[] send_data_group = textBox_sent.Text.Split(' ');
for (int j = 0; j < send_data_group.Length; j++)
{
string send_data = send_data_group[j];
num = (send_data.Length - send_data.Length % 2) / 2;//需要发送的组数
for (int i = 0; i < num; i++)
{
adc[0] = Convert.ToByte(send_data.Substring(i * 2, 2),16);
temp[0] = Convert.ToByte(send_data.Substring(i * 2, 2), 16);
serialPort1.Write(temp, 0, 1);
s.Append(adc[0].ToString("X2") +" ");//循环发送从temp中0位开始选取一个当成字符串
}
if (send_data.Length % 2 != 0)
{
adc[0] = Convert.ToByte(send_data.Substring(send_data.Length - 1, 1),16);
temp[0] = Convert.ToByte(send_data.Substring(send_data.Length - 1, 1), 16);
serialPort1.Write(temp, 0, 1);
s.Append(adc[0].ToString("X2")+" "); //将byte型数据转化为2位16进制文本显示,并用空格隔开
}
current_time = System.DateTime.Now; //获取当前时间
}
textBox_receiver.AppendText(current_time.ToString("[yyyy:MM:dd:HH:mm:ss:fff]") + "【发送】 " + s.ToString());
textBox_receiver.AppendText("\n");
textBox_sent.Text = "";
s.Clear();
}
else
{
current_time = System.DateTime.Now; //获取当前时间
textBox_receiver.AppendText(current_time.ToString("[yyyy:MM:dd:HH:mm:ss:fff]") + "【发送】 " + textBox_sent.Text.ToString());
textBox_receiver.AppendText("\n");
textBox_sent.Text = "";
serialPort1.Write(textBox_sent.Text);
}
}
else
{
MessageBox.Show("串口未打开!");
}
}
catch (Exception ex)
{
serialPort1.Close();
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox_portname.Items.Clear();
comboBox_portname.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button_openport.Text = "打开串口";
MessageBox.Show(ex.Message);
button_clear.Enabled = true;
button_sent.Enabled = true;
button_clear.Enabled = false;
button_sent.Enabled = false;
comboBox_BaudRate.Enabled = true;
comboBox_datebit.Enabled = true;
comboBox_parity.Enabled = true;
comboBox_portname.Enabled = true;
comboBox_stopdit.Enabled = true;
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
Thread.Sleep(60);
int num = serialPort1.BytesToRead; //获取接收缓冲区中的字节数
byte[] received_buf = new byte[serialPort1.BytesToRead]; //声明一个大小为num的字节数据用于存放读出的byte型数据
receive_count += num; //接收字节计数变量增加nun
serialPort1.Read(received_buf, 0, num); //读取接收缓冲区中num个字节到byte数组中
sb.Clear(); //防止出错,首先清空字符串构造器
if (radioButton2.Checked)
{
//选中HEX模式显示
foreach (byte b in received_buf)
{
sb.Append(b.ToString("X2") + ' '); //将byte型数据转化为2位16进制文本显示,并用空格隔开
}
}
else
{
//选中ASCII模式显示
sb.Append(Encoding.ASCII.GetString(received_buf)); //将整个数组解码为ASCII数组
}
try
{
//因为要访问UI资源,所以需要使用invoke方式同步ui
Invoke((EventHandler)(delegate
{
//显示时间
current_time = System.DateTime.Now; //获取当前时间
textBox_receiver.AppendText(current_time.ToString("[yyyy:MM:dd:HH:mm:ss:fff]") + "【接收】 " + sb.ToString());
textBox_receiver.AppendText("\n");
}));
}
catch (Exception ex)
{
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(ex.Message);
}
}
private void comboBox_portname_DropDown(object sender, EventArgs e)
{
//获取电脑当前可用串口并添加到选项列表中
comboBox_portname.Items.Clear();
comboBox_portname.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
}
}