VS上利用C#實現一個簡單的串口程序記錄


一、背景

  工作上需要利用串口往下位機寫入數據,VC太老,正好借此機會來熟悉一直很想接觸的VS之C#。

  感謝Tony托尼哥的串口通信代碼,感謝夢真的C#的技術支持。

二、正文

  1、項目架構:(以我現有的知識認知來說)

    一共有3個文件:

    a、"Program.cs"保存的是主程序入口。

    b、"Form1.Designer.cs"圖形控件的實現。

    c、"Form1.cs"里面實現的既是用戶邏輯。

    典型代碼結構如下:

最先運行文件"Program.cs"內的主程序                                                          
namespace TB528E4PSE_APP                                                                         
{
    static class Program
    {
        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new VOUTCTRL());-----------------------|
        }                                                          |                
    }                                                              |        
}                                                                  |                    
然后接着運行"Form1.cs" 文件內的"VOUTCTRL()".                          |
namespace TB528E4PSE_APP                                           |        
{                                                                  |                        
    public partial class VOUTCTRL : Form                           |                
    {                                                              |                        
        SerialPort serialPort;                                     |                            
                                                                   |                                        
        public VOUTCTRL()  <---------------------------------------|                            
        {
            //IntializeComponent()函數在"Form1.Designer.cs"里實現,
       //功能是初始化圖形界面
//在圖形界面操作時,該代碼會被VS自動更改 InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; //獲取串口 String[] serialPortArray = SerialPort.GetPortNames(); if (serialPortArray != null && serialPortArray.Length != 0) { //對串口進行排序 Array.Sort<String>(serialPortArray); foreach (String port in serialPortArray) { //添加到combox的item if (port != null && port.Length != 0) comboBox_SPort.Items.Add(port); } } //設置初始顯示的值 comboBox_SPort.SelectedIndex = 0; serialPort = new SerialPort(); } private void button_SPort_Click(object sender, EventArgs e) { // 在圖形界面編輯時,雙擊Button控件,該函數由VS自動生成 // 打開窗口 if (button_SPort.Text == "Open") { if (serialPort.IsOpen) serialPort.Close(); try { setPort(); serialPort.Open(); button_SPort.Text = "Close"; } catch (Exception ex) { MessageBox.Show("Uable to open this serial port!\n"); } } else { button_SPort.Text = "Open"; serialPort.Close(); } } private void trackBar_VOUT1_Scroll(object sender, EventArgs e) { // 在圖形界面編輯時,雙擊trackBar類控件,該函數由VS自動生成 // 拖動trackBar_VOUT1控件實現的邏輯 /* 一些代碼邏輯,就不詳細貼了。 ... setSerialVOUT(_Channel_1, _LV0); ... */ } private void trackBar_VOUT2_Scroll(object sender, EventArgs e) { // 在圖形界面編輯時,雙擊trackBar類控件,該函數由VS自動生成 // 拖動trackBar_VOUT2控件實現的邏輯 /* 一些代碼邏輯,就不詳細貼了。 ... setSerialVOUT(_Channel_2, _LV0); ... */ } private void setPort() // 初始化串口 { try { serialPort.PortName = (String)(comboBox_SPort.SelectedItem); serialPort.BaudRate = 115200; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Parity = Parity.None; } catch (Exception ex) { Console.WriteLine(ex); } } private void setSerialVOUT(byte channel, byte level) { byte[] buf = new byte[3]; // C#創建數組的方法 buf[0] = channel; buf[1] = level; buf[2] = (byte)'0'; if (serialPort != null && serialPort.IsOpen) { serialPort.Write(buf,0,3); // 向串口寫入數據 } } } } 文件"Form1.Designer.cs"里包含的函數"InitializeComponent();" namespace TB528E4PSE_APP { partial class VOUTCTRL { /// <summary> /// 必需的設計器變量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的資源。 /// </summary> /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗體設計器生成的代碼 /// <summary> /// 設計器支持所需的方法 - 不要 /// 使用代碼編輯器修改此方法的內容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = \
          new System.ComponentModel.ComponentResourceManager(typeof(VOUTCTRL)); this.trackBar_VOUT2 = new System.Windows.Forms.TrackBar(); this.trackBar_VOUT1 = new System.Windows.Forms.TrackBar(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.textBox_VOUT1 = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.textBox_VOUT2 = new System.Windows.Forms.TextBox(); this.comboBox_SPort = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.button_SPort = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)\
        (
this.trackBar_VOUT2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)\
        (
this.trackBar_VOUT1)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // trackBar_VOUT2 // this.trackBar_VOUT2.LargeChange = 1; this.trackBar_VOUT2.Location = new System.Drawing.Point(0, 60); this.trackBar_VOUT2.Maximum = 11; this.trackBar_VOUT2.Name = "trackBar_VOUT2"; this.trackBar_VOUT2.Size = new System.Drawing.Size(400, 56); this.trackBar_VOUT2.TabIndex = 0; this.trackBar_VOUT2.Scroll += new \
          System.EventHandler(this.trackBar_VOUT2_Scroll); // // trackBar_VOUT1 // this.trackBar_VOUT1.BackColor = System.Drawing.SystemColors.Control; this.trackBar_VOUT1.LargeChange = 1; this.trackBar_VOUT1.Location = new System.Drawing.Point(0, 60); this.trackBar_VOUT1.Maximum = 11; this.trackBar_VOUT1.Name = "trackBar_VOUT1"; this.trackBar_VOUT1.Size = new System.Drawing.Size(400, 56); this.trackBar_VOUT1.TabIndex = 1; this.trackBar_VOUT1.Scroll += new \
          System.EventHandler(this.trackBar_VOUT1_Scroll); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)\
          ((System.Windows.Forms.AnchorStyles.Bottom | \
            System.Windows.Forms.AnchorStyles.Left)));
this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.textBox_VOUT1); this.groupBox1.Controls.Add(this.trackBar_VOUT1); this.groupBox1.Location = new System.Drawing.Point(27, 81); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(400, 116); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "VOUT1"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(23, 31); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(47, 15); this.label1.TabIndex = 3; this.label1.Text = "LEVEL"; // // textBox_VOUT1 // this.textBox_VOUT1.Location = new System.Drawing.Point(142, 28); this.textBox_VOUT1.Name = "textBox_VOUT1"; this.textBox_VOUT1.ReadOnly = true; this.textBox_VOUT1.Size = new System.Drawing.Size(121, 25); this.textBox_VOUT1.TabIndex = 2; this.textBox_VOUT1.Text = "LV 0"; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)\
          ((System.Windows.Forms.AnchorStyles.Bottom | \
            System.Windows.Forms.AnchorStyles.Left)));
this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.textBox_VOUT2); this.groupBox2.Controls.Add(this.trackBar_VOUT2); this.groupBox2.Location = new System.Drawing.Point(27, 215); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(400, 116); this.groupBox2.TabIndex = 3; this.groupBox2.TabStop = false; this.groupBox2.Text = "VOUT2"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(23, 32); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(47, 15); this.label2.TabIndex = 5; this.label2.Text = "LEVEL"; // // textBox_VOUT2 // this.textBox_VOUT2.Location = new System.Drawing.Point(142, 29); this.textBox_VOUT2.Name = "textBox_VOUT2"; this.textBox_VOUT2.ReadOnly = true; this.textBox_VOUT2.Size = new System.Drawing.Size(121, 25); this.textBox_VOUT2.TabIndex = 4; this.textBox_VOUT2.Text = "LV 0"; // // comboBox_SPort // this.comboBox_SPort.FormattingEnabled = true; this.comboBox_SPort.Location = new System.Drawing.Point(169, 34); this.comboBox_SPort.Name = "comboBox_SPort"; this.comboBox_SPort.Size = new System.Drawing.Size(121, 23); this.comboBox_SPort.TabIndex = 4; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(24, 37); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(87, 15); this.label3.TabIndex = 5; this.label3.Text = "SerialPort"; // // button_SPort // this.button_SPort.Location = new \
          System.Drawing.Point(329, 33); this.button_SPort.Name = "button_SPort"; this.button_SPort.Size = new \
          System.Drawing.Size(75, 23); this.button_SPort.TabIndex = 6; this.button_SPort.Text = "Open"; this.button_SPort.UseVisualStyleBackColor = true; this.button_SPort.Click += new \
          System.EventHandler(this.button_SPort_Click); // // VOUTCTRL // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(449, 384); this.Controls.Add(this.button_SPort); this.Controls.Add(this.label3); this.Controls.Add(this.comboBox_SPort); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "VOUTCTRL"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "TB528E4PSE"; ((System.ComponentModel.ISupportInitialize)(this.trackBar_VOUT2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBar_VOUT1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TrackBar trackBar_VOUT2; private System.Windows.Forms.TrackBar trackBar_VOUT1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox_VOUT1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox_VOUT2; private System.Windows.Forms.ComboBox comboBox_SPort; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button_SPort; } }

 

  至此,代碼跟蹤至此。

 

  2、更改窗體在屏幕首次出現的位置

    即當APP運行時,窗體會在電腦屏幕的哪個位置彈出。點擊窗體->屬性,

    找到“startposition”,如下圖:

    

    注意以上圖片包含的信息:Text選項,此處則可以表明窗體顯示的信息。

 

  3,更改窗體顯示的圖標。

    即當APP運行時,窗體在Text旁邊的圖片,點擊窗體->屬性,

    找到“Icon”,如下圖:

    

 

  4、如何發布程序:

    點擊項目欄“生成”,點擊“發布”選項即可發布程序了,如下圖:

    

    生成的文件如下圖:

     

    點擊后綴名為".application"即可實現安裝。

 

   5、發布安裝后,程序在桌面顯示的圖標,以及支持的".NET frameworkXX.XX"設置。

    在項目右擊,選擇屬性,會跳出窗體"項目名.csproj"文件,

    里面可進行相應設置,如下圖:

    

三、參考鏈接

  Tony被參考的源代碼github地址:

  https://github.com/TonySudo/SerialPortW    

 

  至此,記錄完畢

 

記錄時間:2016-8-26

記錄地點:深圳WZ


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM