C#下串口编程测试
本文博客链接: http://blog.csdn.net/jdh99 ,作者:jdh,转载请注明.
软件平台: C# + WINCE6.0
硬件平台:tiny6410
界面设计:
设计思路:
1.点击发送键则发送文本
2.串口接收到数据包则启动一个事件,在事件中处理数据包
注意:
1.接收事件中调用主线程的控件会导致不安全,所以用了托管的方式调用
2.直接调用了C#中的串口控件,波特率等在属性页面中设置
源代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Threading; namespace test_serialport { public partial class Form1 : Form { //接收数组 Byte[] recv_bytes; public Form1() { InitializeComponent(); //打开串口 serialPort1.Open(); //开启接收线程 //Thread recv_udp = new Thread(new ThreadStart(recv_udp_func)); //recv_udp.Start(); //添加事件注册 serialPort1.DataReceived += recv_udp_func; } //发送按键按下 private void button1_Click(object sender, EventArgs e) { serialPort1.Write(textBox1.Text); } //接收事件 void recv_udp_func(object sender, SerialDataReceivedEventArgs e) { //获取缓冲区字节数 int n = serialPort1.BytesToRead; //声明一个临时数组存储当前来的串口数据 byte[] buf = new byte[n]; serialPort1.Read(buf, 0, n);//读取缓冲数据 this.Invoke((EventHandler)delegate { this.textBox2.Text = Encoding.Default.GetString(buf, 0, n);}); } } }