C#之windows桌面软件第二课:向单片机发信息的串口工具
生活随笔
收集整理的這篇文章主要介紹了
C#之windows桌面软件第二课:向单片机发信息的串口工具
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? 設計一個串口工具向單片機發送信息
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;namespace SerialTest {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e)//窗口創建初始化函數{string str;//用來臨時存儲i大寫的十六進制格式字符串for (int i = 0; i < 256; i++)//256個{str = i.ToString("x").ToUpper();//ToString("x")是將數字轉轉換為16進制字符串,ToUpper是將字符串所有字符大寫//comboBox1.Items.Add("0x" + (str.Length == 1 ? "0" + str : str));if (str.Length == 1)str = "0" + str;//如果是一位的(0xA),此時為了對齊,在數據前加一個字符“0”(0x0A)comboBox1.Items.Add("0x"+ str);//統一添加"0x"}comboBox1.Text = "0X00";//初始值}private void button1_Click(object sender, EventArgs e)//按鍵單擊事件{string data = comboBox1.Text;//存儲當前下拉框的內容string convertdata = data.Substring(2, 2);//把字符分開byte[] buffer = new byte[1];//數據一個字節就夠用了buffer[0] = Convert.ToByte(convertdata, 16);//將字符串轉化為byte型變量(byte相當于單片機中的unsigned char(0-255))try//防止出錯{serialPort1.Open();serialPort1.Write(buffer, 0, 1);serialPort1.Close();}catch {//如果出錯就執行此塊代碼if (serialPort1.IsOpen)serialPort1.Close();//如果是寫數據時出錯,此時窗口狀態為開,就應關閉串口,防止下次不能使用,串口是不能重復打開和關閉的MessageBox.Show("端口錯誤","錯誤");}}} }www.DoYoung.net(部分代碼來至杜洋工作室)
總結
以上是生活随笔為你收集整理的C#之windows桌面软件第二课:向单片机发信息的串口工具的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#之windows桌面软件第一课:倒时
- 下一篇: C#之windows桌面软件第四课:串口