程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> c# 2.0 serial port communication

c# 2.0 serial port communication

編輯:.NET實例教程
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace ConsoleApplication3
...{
    class SerialPortTest
    ...{
        public string MessageStr = "";
        public bool IsMessageFlag = false;

        SerialPort port1;
        
        /**////<summary>
        ///function:initial serial port
        ///</summary>
        ///<param name="PortName">port number</param>
        ///<param name="BaudRate">port speed</param>

        public void InitCOM(string PortName, int BaudRate)
        ...{
            port1 = new SerialPort(PortName, BaudRate);
            port1.Handshake = Handshake.RequestToSend;

            port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
        }
        /**//// <summary>
        ///function:deal with the data receive 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        ...{
            StringBuilder currentline = new StringBuilder();
            if (!IsMessageFlag)
            ...{
                while (port1.BytesToRead > 0)
                ...{
                    char ch = (char)port1.ReadByte();
                    currentline.Append(ch);
                }
                MessageStr = currentline.ToString();
                IsMessageFlag = true;
                currentline = new StringBuilder();
            }
            //throw new Exception("The method or Operation is not implemented.");
        }
        /**//// <summary>
        /// function:send the instruction
        /// </summary>
        /// <param name="CommandString"></param>
        public void SendCommand(string CommandString)
        ...{
            byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
            port1.Write(WriteBuffer, 0, WriteBuffer.Length);
        }
        /**//// <summary>
        /// function:open the closed port
        /// </summary>
        public void OpenPort()
        ...{
            port1.Open();
            if (port1.IsOpen)
            ...{
                Console.WriteLine("the port is opened!");
            }
            else
            ...{
                Console.WriteLine("failure to open the port!");
            }
        }
        /**//// <summary>
        /// function:close the opened port
        /// </summary>
        public void ClosePort()
        ...{
            port1.Close();
            if (port1.IsOpen)
            ...{
                Console.WriteLine("the port is already closed!");
            }
        }
        
    }
}
 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved