foreach (DictionaryEntry item in m_serialport)
{
SerialPort serialport = (SerialPort)item.Value;
if (serialport.IsOpen)
{
serialport.Close();
}
}
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
SerialPort serialport = new SerialPort();
serialport.PortName = ports[i];
serialport.Open();
serialport.ReadExisting();
serialport.DataReceived += new SerialDataReceivedEventHandler(m_serialport_DataReceived); m_serialport.Add(ports[i], serialport);
}
public void m_serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serialport = (SerialPort)sender;
int num = serialport.BytesToRead;
if (num ==8)
{
Byte[] mybyte = new Byte[num];
serialport.Read(mybyte, 0, num);
}}
{
SerialPort serialport = (SerialPort)item.Value;
if (serialport.IsOpen)
{
serialport.Close();
}
}
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
SerialPort serialport = new SerialPort();
serialport.PortName = ports[i];
serialport.Open();
serialport.ReadExisting();
serialport.DataReceived += new SerialDataReceivedEventHandler(m_serialport_DataReceived); m_serialport.Add(ports[i], serialport);
}
public void m_serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serialport = (SerialPort)sender;
int num = serialport.BytesToRead;
if (num ==8)
{
Byte[] mybyte = new Byte[num];
serialport.Read(mybyte, 0, num);
}}
using System.Runtime.InteropServices;
using System.IO;
namespace Common
{
/// <summary>
/// POSPrinter 的摘要说明。
/// </summary>
public class POSPrinter
{
const int OPEN_EXISTING = 3;
string prnPort ="COM1";
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr CreateFile(string lpFileName,
int dwDesiredAccess,
int dwShareMode,
int lpSecurityAttributes,
int dwCreationDisposition ,
int dwFlagsAndAttributes ,
int hTemplateFile);
public POSPrinter()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public POSPrinter(string prnPort)
{
this.prnPort=prnPort;//打印机端口
}
public string PrintLine(string str)
{
IntPtr iHandle = CreateFile(prnPort, 0x40000000, 0, 0, OPEN_EXISTING, 0, 0);
if(iHandle.ToInt32() == -1)
{
return "打开COM1失败";
}
else
{
FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
//sw.WriteLine(str)//写数据
//开钱箱
sw.Write(((char)27).ToString()+"p"+((char)0).ToString()+((char)60).ToString()+((char)255).ToString());
sw.Close();
fs.Close();
return "";
}
}
}
}C#开钱箱的代码
2005已经封装了serialPort类。处理串口通讯。
以及2003和2005的串口通信源码。
using System.Collections.Generic;
using System.Text;using System.IO;
using System.IO.Ports;
namespace DirectionControl
{
/// <summary>
/// 云台运动方向
/// </summary>
[Serializable]
public enum Direction
{
top,
down,
left,
right,
topLeft,
topRight,
downLeft,
downRight,
auto,
stop
} /// <summary>
/// 云台控制类
/// </summary>
[Serializable]
public class PelcoD
{
#region 成员变量 #region private #region 串口
/// <summary>
/// 串口对象
/// </summary>
private SerialPort serial;
/// <summary>
/// 串口号,默认为COM1
/// </summary>
private string portName = "COM1";
/// <summary>
/// 波特率,默认为2400
/// </summary>
private int baudRate = 2400;
/// <summary>
/// 奇偶校验位,默认为None
/// </summary>
private Parity parity = Parity.None;
/// <summary>
/// 数据位,默认为8
/// </summary>
private int dataBits = 8;
/// <summary>
/// 停止位,默认为One
/// </summary>
private StopBits stopBits = StopBits.One;
/// <summary>
/// 当前计算机上所有的串行端口名称
/// </summary>
private static string[] portNames;
#endregion /// <summary>
/// 错误信息
/// </summary>
private string lastErrorMessage = "";
/// <summary>
/// 是否正确初始化
/// </summary>
private bool isInit = false;
/// <summary>
/// 当前运动方向
/// </summary>
private Direction currentDirection;
/// <summary>
/// 地址
/// </summary>
private byte currentAddress;
/// <summary>
/// 水平运动速度
/// </summary>
private byte horizontalSpeed = 0x1F;
/// <summary>
/// 垂直运动速度
/// </summary>
private byte verticalSpeed = 0x1F;
#endregion #region public #endregion #endregion #region 构造 static PelcoD()
{
try
{
portNames = System.IO.Ports.SerialPort.GetPortNames();
}
catch (System.ComponentModel.Win32Exception ex)
{
System.Windows.Forms.MessageBox.Show("无法查询当前计算机串行端口名称或当前计算机无可用串行端口!\n错误信息:" + ex.Message, "读取计算机串口设备错误!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
} public PelcoD():this("COM1")
{ }
public PelcoD(string portName):this(portName,2400,Parity.None,8,StopBits.One)
{
}
public PelcoD(SerialPort serialPort)
{
if (serialPort != null)
{
this.serial = serialPort;
this.isInit = true;
}
}
public PelcoD(string portName,int baudRate,Parity parity, int dataBits,StopBits stopBits)
{
try
{
serial = new SerialPort(portName, baudRate, Parity.None, dataBits, StopBits.One);
this.portName = portName;
this.baudRate = baudRate;
this.parity = parity;
this.dataBits = dataBits;
this.stopBits = stopBits;
this.isInit = true;
}
catch (System.IO.IOException ex)
{
this.lastErrorMessage = ex.Message;
this.isInit = false;
}
} #endregion #region 析构
~PelcoD()
{
if (this.serial != null)
{
if (serial.IsOpen)
serial.Close();
serial.Dispose();
}
}
#endregion #region 方法 #region private #endregion
#region public /// <summary>
/// 云台转动
/// </summary>
/// <param name="address"></param>
/// <param name="direction"></param>
public void Move(byte address, Direction direction)
{
if (!this.isInit || serial == null || address < 1)
{
return;
}
byte[] senderMessage = new byte[7]; if (direction == Direction.stop)
{
Stop(address);
return;
}
else
{
#region 要发送的数据处理
senderMessage[0] = 0xFF;
senderMessage[1] = address; switch (direction)
{
case Direction.auto:
senderMessage[2] = 0x00;
senderMessage[3] = 0x07;
senderMessage[4] = 0x00;
senderMessage[5] = 0x63;
break;
case Direction.top:
senderMessage[2] = 0x00;
senderMessage[3] = 0x08;
senderMessage[4] = 0x00;
senderMessage[5] = this.verticalSpeed;
break;
case Direction.down:
senderMessage[2] = 0x00;
senderMessage[3] = 0x10;
senderMessage[4] = 0x00;
senderMessage[5] = this.verticalSpeed;
break;
case Direction.left:
senderMessage[2] = 0x00;
senderMessage[3] = 0x04;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = 0x00;
break;
case Direction.right:
senderMessage[2] = 0x00;
senderMessage[3] = 0x02;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = 0x00;
break;
case Direction.downLeft:
senderMessage[2] = 0x00;
senderMessage[3] = 0x14;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = this.verticalSpeed;
break;
case Direction.downRight:
senderMessage[2] = 0x00;
senderMessage[3] = 0x12;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = this.verticalSpeed;
break;
case Direction.topLeft:
senderMessage[2] = 0x00;
senderMessage[3] = 0x0C;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = this.verticalSpeed;
break;
case Direction.topRight:
senderMessage[2] = 0x00;
senderMessage[3] = 0x0A;
senderMessage[4] = this.horizontalSpeed;
senderMessage[5] = this.verticalSpeed;
break;
}
//校验码是指Byte2到Byte6这5个数的和(若超过255则除以256然后取余数)
if (!Byte.TryParse((senderMessage[1] + senderMessage[2] + senderMessage[3] + senderMessage[4] + senderMessage[5]).ToString(), out senderMessage[6]))
{
senderMessage[6] = byte.Parse(((senderMessage[1] + senderMessage[2] + senderMessage[3] + senderMessage[4] + senderMessage[5]) % 256).ToString());
}
#endregion
}
//打开串口并发送数据,延时100毫秒
try
{
if (serial.IsOpen)
serial.Close();
serial.Open();
serial.Write(senderMessage, 0, 7);
serial.Close();
this.currentDirection = direction;
System.Threading.Thread.Sleep(100);
}
catch (System.Exception ex)
{
this.lastErrorMessage = ex.Message;
return;
}
} /// <summary>
/// 停止转动
/// </summary>
public void Stop(byte address)
{
if (!this.isInit || address < 0 || address > 32 || serial == null)
{
return;
} //打开串口并发送数据,延时100毫秒
try
{
if (serial.IsOpen)
serial.Close();
serial.Open();
serial.Write(new byte[] { 0xFF, address, 0x00, 0x00, 0x00, 0x00, address }, 0, 7);
serial.Close();
this.currentDirection = Direction.stop;
System.Threading.Thread.Sleep(100);
}
catch (System.Exception ex)
{
this.lastErrorMessage = ex.Message;
return;
}
this.currentDirection = Direction.stop;
}
#endregion #endregion #region 属性 #region 串口 /// <summary>
/// 获取当前计算机上的所有串行端口名称
/// </summary>
public string[] PortNames
{
get { return portNames; }
} /// <summary>
/// 获取或设置串口对象
/// </summary>
public SerialPort SerialPort
{
get { return this.serial; }
set { this.serial = value; }
}
#endregion /// <summary>
/// 获取最后一次错误信息
/// </summary>
public string LastErrorMessage
{
get { return this.lastErrorMessage; }
} /// <summary>
/// 获取是否正确初始化串口
/// </summary>
public bool IsInit
{
get { return this.isInit; }
}
/// <summary>
/// 获取当前运动方向
/// </summary>
public Direction CurrentDirection
{
get { return this.currentDirection; }
} /// <summary>
/// 获取当前控制的地址
/// </summary>
public byte CurrentAddress
{
get { return this.currentAddress; }
}
/// <summary>
/// 水平运动速度,默认为0x1F
/// </summary>
public byte HorizontalSpeed
{
get { return this.horizontalSpeed; }
set
{
if (value >= 0x3F)
{
this.horizontalSpeed = 0x3F;
}
else
{
this.horizontalSpeed = value;
}
}
}
/// <summary>
/// 垂直运动速度,默认为0x1F
/// </summary>
public byte VerticalSpeed
{
get { return this.verticalSpeed; }
set
{
if (value > 0x3F)
{
this.verticalSpeed = 0x3F;
}
else
{
this.verticalSpeed = value;
}
}
} #endregion }
}