找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 10316|回復(fù): 7
打印 上一主題 下一主題
收起左側(cè)

單片機(jī)串口通訊收發(fā)數(shù)據(jù)C#上位機(jī)界面顯示出來

  [復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
ID:540742 發(fā)表于 2019-5-17 15:35 | 只看該作者 回帖獎(jiǎng)勵(lì) |倒序?yàn)g覽 |閱讀模式
如果,翻看我之前的博客,會(huì)找到一篇用I/O模擬IIC通信的程序文章。好吧,如果找不到可以點(diǎn)擊這里,這里就不在贅述了,系統(tǒng)也已經(jīng)完全調(diào)試通過了。
今天的任務(wù)是,把測試得到的數(shù)據(jù)在上位機(jī)的界面上顯示出來,于是鍵盤手花了兩天的時(shí)間模仿著巨人的肩膀通過了用C#編寫的界面程序,界面很簡單就像下面顯示的一樣。
下面就一步一步給大伙展示一下我的程序吧。
C#非常的強(qiáng)大而且友好,串口的通信可以通過編程環(huán)境(這里我用的是Visual Studio 2010),如果有需要的話可以給我信息,我有完整版的安裝包。如下圖,簡單的調(diào)用和選擇就完成了串口的基本配置。
下面主要就是編程的問題了,在窗體Load的進(jìn)程中可以完成串口的啟動(dòng)

而后就是讀取數(shù)據(jù)的操作,這時(shí)候用到事件
1 private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
在這個(gè)事件里面編程就可以了,但是在對窗體內(nèi)文本進(jìn)行操作的時(shí)候會(huì)發(fā)現(xiàn)出現(xiàn)了線程的沖突和錯(cuò)誤。網(wǎng)上給出的一種解決方法是采用代理的方式具體的程序如下:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.IO.Ports;
  11. using System.Net.Http;
  12. using System.Collections;

  13. namespace SerialPortDataUploader
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         public Form1()
  18.         {
  19.             InitializeComponent();
  20.         }

  21.         private void comboBoxSerialPort_SelectedIndexChanged(object sender, EventArgs e)
  22.         {
  23.             serialPort1.PortName = comboBoxSerialPort.Items[comboBoxSerialPort.SelectedIndex].ToString();
  24.         }

  25.         private void comboBoxSerialPort_MouseClick(object sender, MouseEventArgs e)
  26.         {
  27.             comboBoxSerialPort.Items.Clear();
  28.             comboBoxSerialPort.Items.AddRange(SerialPort.GetPortNames());
  29.         }

  30.         private void listBoxLog_SelectedIndexChanged(object sender, EventArgs e)
  31.         {
  32.             if (listBoxLog.SelectedItem != null)
  33.                 textBoxLog.Text = listBoxLog.SelectedItem.ToString();
  34.         }

  35.         Queue<char> DataQueue = new Queue<char>();
  36.         volatile private int lightZ = 50, tempZ = 28, wetZ = 30;
  37.         volatile private int lightX = 50, tempX = 28, wetX = 30;
  38.         volatile private int lightL = 50, tempL = 28, wetL = 30;

  39.         private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  40.         {
  41.             char[] tmp = new char[1000];
  42.             int count = serialPort1.BytesToRead;
  43.             serialPort1.Read(tmp, 0, count);
  44.             for (int i = 0; i < count; i++)
  45.                 DataQueue.Enqueue(tmp[i]);

  46.             while (DataQueue.Count >= 11)
  47.             {
  48.                 switch (DataQueue.Peek())
  49.                 {
  50.                     case 'z':
  51.                     case 'l':
  52.                     case 'x':
  53.                         {
  54.                             char[] tmp1 = new char[100];
  55.                             for (int i = 0; i < 11; i++)
  56.                                 tmp1[i] = DataQueue.Dequeue();
  57.                             try
  58.                             {
  59.                                 int light = (tmp1[2] - 0x30) * 10 + (tmp1[3] - 0x30);
  60.                                 int temp = (tmp1[5] - 0x30) * 10 + (tmp1[6] - 0x30);
  61.                                 int wet = (tmp1[8] - 0x30) * 10 + (tmp1[9] - 0x30);
  62.                                 switch (tmp1[0])
  63.                                 {
  64.                                     case 'z': lightZ = light; tempZ = temp; wetZ = wet; break;
  65.                                     case 'x': lightX = light; tempX = temp; wetX = wet; break;
  66.                                     case 'l': lightL = light; tempL = temp; wetL = wet; break;
  67.                                 }
  68.                             }
  69.                             catch (Exception) { }
  70.                             break;
  71.                         }
  72.                     default:
  73.                         DataQueue.Dequeue();
  74.                         break;
  75.                 }
  76.             }
  77.         }

  78.         private void Form1_Load(object sender, EventArgs e)
  79.         {
  80.             comboBoxSerialPort.Items.Clear();
  81.             comboBoxSerialPort.Items.AddRange(SerialPort.GetPortNames());
  82.         }

  83.         private void buttonConnect_Click(object sender, EventArgs e)
  84.         {
  85.             serialPort1.Open();
  86.             buttonConnect.Enabled = false;
  87.             comboBoxSerialPort.Enabled = false;
  88.             labelStatu.ForeColor = Color.Green;
  89.             timer1.Start();
  90.         }
  91.         private string HTTPGet(string url)
  92.         {
  93.             using (var client = new HttpClient())
  94.             {
  95.                 var responseString = client.GetStringAsync(url);
  96.                 return responseString.Result;
  97.             }
  98.         }
  99.         private async Task<string> HTTPPost(string url, Dictionary<string, string> values)
  100.         {
  101.             using (var client = new HttpClient())
  102.             {
  103.                 var content = new FormUrlEncodedContent(values);

  104.                 var response = await client.PostAsync(url, content);

  105.                 var responseString = await response.Content.ReadAsStringAsync();
  106.                 return responseString.ToString();
  107.             }
  108.         }

  109.         delegate void listBoxLogAddMessage_Callback(string mwssage);
  110.         private void listBoxLogAddMessage(string message)
  111.         {
  112.             if (listBoxLog.InvokeRequired)
  113.             {
  114.                 listBoxLogAddMessage_Callback d = new listBoxLogAddMessage_Callback(listBoxLogAddMessage);
  115.                 this.Invoke(d, new object[] { message });
  116.             }
  117.             else
  118.             {
  119.                 listBoxLog.Items.Add(message);
  120.                 listBoxLog.SelectedIndex = listBoxLog.Items.Count - 1;
  121.             }
  122.         }

  123.         bool Timer1Flag = false;
  124.         int timer = 0, TimeSet = 5;
  125.         private void timer1_Tick(object sender, EventArgs e)
  126.         {
  127.             timer++;
  128.             if (Timer1Flag)
  129.                 return;
  130.             string tmp = HTTPGet(BaseURL + "API.aspx?api=contralget1");
  131.             try
  132.             {
  133.                 TimeSet = int.Parse(tmp);
  134.             }
  135.             catch (Exception) { }
  136.             if (TimeSet > 0 && timer >= TimeSet)
  137.             {
  138.                 timer -= TimeSet;
  139.                 Timer1Flag = true;
  140.                 try
  141.                 {
  142.                     string url = BaseURL + "API.aspx?api=upload&lightZ={LIGHTZ}&lightX={LIGHTX}&lightL={LIGHTL}&tempZ={TEMPZ}&tempX={TEMPX}&tempL={TEMPL}&wetZ={WETZ}&wetX={WETX}&wetL={WETL}".Replace("{LIGHTZ}", lightZ.ToString()).Replace("{LIGHTX}", lightX.ToString());
  143.                     url = url.Replace("{LIGHTL}", lightL.ToString()).Replace("{TEMPZ}", tempZ.ToString()).Replace("{TEMPX}", tempX.ToString()).Replace("{TEMPL}", tempL.ToString()).Replace("{WETZ}", wetZ.ToString()).Replace("{WETX}", wetX.ToString()).Replace("{WETL}", wetL.ToString());

  144.                     string message = HTTPGet(url);
  145.                     if (!message.Equals("{\"statu\":\"ok\"}"))
  146.                         listBoxLogAddMessage(DateTime.Now.ToString() + "  服務(wù)器返回異常:" + message);
  147.                     else
  148.                         listBoxLogAddMessage(DateTime.Now.ToString() + "  已上傳至服務(wù)器。");
  149.                 }
  150.                 catch (Exception ext)
  151.                 {
  152.                     listBoxLogAddMessage(DateTime.Now.ToString() + "  上傳至服務(wù)器失。" + ext.Message);
  153.                 }
  154.                 Timer1Flag = false;
  155.             }
  156.         }
  157.     }
  158. }
復(fù)制代碼
全部資料51hei下載地址:
EngineeringPractice20171_ServerAndUploader-master.zip (28.48 KB, 下載次數(shù): 252)

評分

參與人數(shù) 2黑幣 +55 收起 理由
醬大錘 + 5 贊一個(gè)!
admin + 50 共享資料的黑幣獎(jiǎng)勵(lì)!

查看全部評分

分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏10 分享淘帖 頂 踩
回復(fù)

使用道具 舉報(bào)

沙發(fā)
ID:440747 發(fā)表于 2019-5-31 17:15 | 只看該作者
謝謝分享 好資料,51黑有你更精彩!!!
回復(fù)

使用道具 舉報(bào)

板凳
ID:540397 發(fā)表于 2019-7-24 09:39 | 只看該作者
不錯(cuò)
回復(fù)

使用道具 舉報(bào)

地板
ID:642557 發(fā)表于 2019-11-15 13:05 | 只看該作者
謝謝分享
回復(fù)

使用道具 舉報(bào)

5#
ID:916468 發(fā)表于 2021-5-6 16:58 | 只看該作者
樓主可以發(fā)一下安裝包給大家嗎?
回復(fù)

使用道具 舉報(bào)

6#
ID:731836 發(fā)表于 2023-8-1 18:25 | 只看該作者
下載的文件和展示的文件是2個(gè)不同的,各位要下載的注意下,不是上面文檔介紹的溫濕度。!
回復(fù)

使用道具 舉報(bào)

7#
ID:1075678 發(fā)表于 2023-11-14 21:39 | 只看該作者
感謝樓主分享,最近要做項(xiàng)目剛好要學(xué)習(xí)使用
回復(fù)

使用道具 舉報(bào)

8#
ID:353115 發(fā)表于 2023-11-27 09:16 | 只看該作者
愛學(xué)習(xí)的小菜 發(fā)表于 2023-11-14 21:39
感謝樓主分享,最近要做項(xiàng)目剛好要學(xué)習(xí)使用

STC-ISP軟件有將數(shù)據(jù)接收到文件的功能,你可以試一下。
回復(fù)

使用道具 舉報(bào)

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機(jī)版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表