軟件平台:C# + WINCE6.0
硬件平台:tiny6410
界面設計:
設計思路:
1.點擊發送鍵則發送文本
2.串口接收到數據包則啟動一個事件,在事件中處理數據包
注意:
1.接收事件中調用主線程的控件會導致不安全,所以用了托管的方式調用
2.直接調用了C#中的串口控件,波特率等在屬性頁面中設置
源代碼:
[csharp]
- 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);});
- }
- }
- }