c# 2.0 serial port communication

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!");
            }

        }

        
    }

}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值