using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace SerialPortAgent
{
public class LogicSerialPort
{
public delegate void ReceivedCommandEventHandler(int transceiverIndex, string commandText);
public event ReceivedCommandEventHandler ReceivedCommand;
private System.IO.Ports.SerialPort serialPort;
public bool Cts { get {return serialPort.CtsHolding; } }
public bool Dtr { get { return serialPort.DtrEnable; } }
public bool Dsr { get { return serialPort.DsrHolding; } }
public bool Rts { get { return serialPort.RtsEnable; } }
public System.IO.Ports.Handshake Handshake
{
get { return serialPort.Handshake; }
set { serialPort.Handshake = value; }
}
int _TransceiverIndex;
public int TransceiverIndex
{
get { return _TransceiverIndex; }
set { _TransceiverIndex = value; }
}
public LogicSerialPort() { }
public LogicSerialPort(int ComIndex)
{
try
{
_ComIndex = ComIndex;
this.serialPort = new System.IO.Ports.SerialPort();
//this.serialPort.DtrEnable = true;
//this.serialPort.RtsEnable = true;
this.serialPort.DataReceived +=
new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
this.serialPort.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort_ErrorReceived);
this.serialPort.PortName = "COM" + _ComIndex.ToString();
this.serialPort.ReceivedBytesThreshold = 1;
this.serialPort.Open();
}catch(Exception exp)
{
string m = exp.Message;
this.serialPort.Close();
}
}
///
/// 断开串口
///
public void CloseSerialPort()
{
if (this.serialPort.IsOpen)
{
this.serialPort.Close();
}
}
///
/// 向串口发送命令
///
///
public void SendCommand(string commandText)
{
try
{
if (!this.serialPort.IsOpen)
{
this.serialPort.Open();
}
byte[] writebuffer = Encoding.ASCII.GetBytes(commandText );
this.serialPort.Write(writebuffer, 0, writebuffer.Length);
}
catch (Exception exp)
{
this.ReceivedCommand(_TransceiverIndex, "命令发送出错:"+exp.Message);
this.serialPort.Close();
}
}
///
/// 从串口得到命令
///
///
///
void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[serialPort.BytesToRead];
serialPort.Read(readBuffer, 0, readBuffer.Length);
ReceivedCommand(0, Encoding.ASCII.GetString(readBuffer));
}
///
/// 从串口得到错误信息
///
///
///
void serialPort_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
byte[] readBuffer = new byte[serialPort.BytesToRead];
serialPort.Read(readBuffer, 0, readBuffer.Length);
string CommandText = Encoding.ASCII.GetString(readBuffer);
ReceivedCommand(0, Encoding.ASCII.GetString(readBuffer));
}
}
}
1 楼 说的“现在的电脑都没有提供串口的”?
带串口的机器还是有的,只是不太多而已
现在用的 Dell Op 360 就有 一串一并
前面说的 很对,“调试的时候最好使用虚拟串口工具”
请看 武汉鸿伟光电
有 虚拟串口 下载
using System.IO.Ports;
使用里面的SerialPort 类即可实现串口通信。
在调试的时候最好使用虚拟串口工具,据我所知现在的电脑都没有提供串口的了。