C#下串口編程測試
本文博客鏈接: http://blog.csdn.net/jdh99 ,作者:jdh,轉(zhuǎn)載請注明.
軟件平臺: C# + WINCE6.0
硬件平臺:tiny6410
界面設(shè)計(jì):
設(shè)計(jì)思路:
1.點(diǎn)擊發(fā)送鍵則發(fā)送文本
2.串口接收到數(shù)據(jù)包則啟動一個(gè)事件,在事件中處理數(shù)據(jù)包
注意:
1.接收事件中調(diào)用主線程的控件會導(dǎo)致不安全,所以用了托管的方式調(diào)用
2.直接調(diào)用了C#中的串口控件,波特率等在屬性頁面中設(shè)置
源代碼:
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 { //接收數(shù)組 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; } //發(fā)送按鍵按下 private void button1_Click(object sender, EventArgs e) { serialPort1.Write(textBox1.Text); } //接收事件 void recv_udp_func(object sender, SerialDataReceivedEventArgs e) { //獲取緩沖區(qū)字節(jié)數(shù) int n = serialPort1.BytesToRead; //聲明一個(gè)臨時(shí)數(shù)組存儲當(dāng)前來的串口數(shù)據(jù) byte[] buf = new byte[n]; serialPort1.Read(buf, 0, n);//讀取緩沖數(shù)據(jù) this.Invoke((EventHandler)delegate { this.textBox2.Text = Encoding.Default.GetString(buf, 0, n);}); } } }
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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