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);}); } } }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
