C# 串口调式工具简单开发
在玩单片机和嵌入式开发中。经常会用到一个工具。那就是串口。这个是做开发经常会用到的工具。而且在现实中很多的设备在使用中也会使用到串口来输出调试数据或者使用串口来升级软件。
而在使用中使用上位机的开发中也经常要使用到串口。现在我就来使用C# 对串口的数据通信做一个简单的开发。
首先上效果图
没有什么看头非常的简单。以后有空在进一步进行功能的添加和补充。
使用的是控件方式,没有使用多线程来操作。
代码也非常简单几十行代码搞定。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; namespace WindowsFormsApplication1 { public partial class Form1 : Form { Dictionary <string, StopBits> stoplist; public Form1() { InitializeComponent(); } private void toolStripDropDownButton1_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { string [] comseting={"1200","2400","4800","9600","19200","38400","57600","115200","460800","921600"}; toolStripComboBox1.Items.AddRange(comseting); stoplist = new Dictionary<string, StopBits>(); stoplist.Add("1", StopBits.One); stoplist.Add("1.5", StopBits.OnePointFive); stoplist.Add("2", StopBits.Two); for (int i = 0; i < 20; i++) { toolStripComboBox2.Items.Add("COM"+i.ToString()); } } private void toolStripComboBox2_Click(object sender, EventArgs e) { serialPort1.PortName = this.toolStripComboBox2.Text; } private void toolStripComboBox1_Click(object sender, EventArgs e) { serialPort1.BaudRate = int.Parse(this.toolStripComboBox1.Text); } private void toolStripComboBox3_Click(object sender, EventArgs e) { serialPort1.DataBits = int.Parse(this.toolStripComboBox3.Text); } private void toolStripComboBox4_Click(object sender, EventArgs e) { serialPort1.StopBits = stoplist[this.toolStripComboBox4.Text]; } private void toolStripButton1_Click(object sender, EventArgs e) { serialPort1.PortName = this.toolStripComboBox2.Text; serialPort1.BaudRate = int.Parse(this.toolStripComboBox1.Text); serialPort1.DataBits = int.Parse(this.toolStripComboBox3.Text); serialPort1.StopBits = stoplist[this.toolStripComboBox4.Text]; try { serialPort1.Open(); this.toolStripButton1.Enabled = false; }catch(Exception err){ MessageBox.Show(err.Message); this.toolStripButton1.Enabled = true; } } private void toolStripButton2_Click(object sender, EventArgs e) { serialPort1.Close(); this.toolStripButton1.Enabled = true; } private void button1_Click(object sender, EventArgs e) { try { byte[] sendbytes = Encoding.Default.GetBytes(textBox2.Text); serialPort1.Write(sendbytes, 0, sendbytes.Length); textBox1.Text +="\r\n[发送:]" + textBox2.Text; textBox2.Text = ""; } catch (Exception err) { MessageBox.Show(err.Message); } } private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { int len = serialPort1.BytesToRead; if (len == 0) return; byte[] receiveMsg = new byte[len]; serialPort1.Read(receiveMsg, 0, len); textBox1.Text += "\r\n[收到:]" + Encoding.Default.GetString(receiveMsg); ; } } }
源码:WindowsFormsApplication1.rar