歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C#下串口編程測試

C#下串口編程測試

日期:2017/3/1 10:38:52   编辑:Linux編程

軟件平台:C# + WINCE6.0

硬件平台:tiny6410

界面設計:


設計思路:

1.點擊發送鍵則發送文本

2.串口接收到數據包則啟動一個事件,在事件中處理數據包

注意:

1.接收事件中調用主線程的控件會導致不安全,所以用了托管的方式調用

2.直接調用了C#中的串口控件,波特率等在屬性頁面中設置

源代碼:

[csharp]
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.IO.Ports;
  9. using System.Threading;
  10. namespace test_serialport
  11. {
  12. public partial class Form1 : Form
  13. {
  14. //接收數組
  15. Byte[] recv_bytes;
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. //打開串口
  20. serialPort1.Open();
  21. //開啟接收線程
  22. //Thread recv_udp = new Thread(new ThreadStart(recv_udp_func));
  23. //recv_udp.Start();
  24. //添加事件注冊
  25. serialPort1.DataReceived += recv_udp_func;
  26. }
  27. //發送按鍵按下
  28. private void button1_Click(object sender, EventArgs e)
  29. {
  30. serialPort1.Write(textBox1.Text);
  31. }
  32. //接收事件
  33. void recv_udp_func(object sender, SerialDataReceivedEventArgs e)
  34. {
  35. //獲取緩沖區字節數
  36. int n = serialPort1.BytesToRead;
  37. //聲明一個臨時數組存儲當前來的串口數據
  38. byte[] buf = new byte[n];
  39. serialPort1.Read(buf, 0, n);//讀取緩沖數據
  40. this.Invoke((EventHandler)delegate { this.textBox2.Text = Encoding.Default.GetString(buf, 0, n);});
  41. }
  42. }
  43. }
Copyright © Linux教程網 All Rights Reserved