C#四路继电器usb转com口编程

时间:2022-08-31 00:12:00

用到C#在名字空间System.IO.Ports下的SerialPort类来实现功能


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.IO.Ports;

namespace ComLibrary
{
public class EleRelay
{
#region 四路继电器属性区域
private SerialPort mycom = new SerialPort(); //com接口
private string portName; //com号
private bool flag = false;
private int numFlashing;
//设置几号灯闪烁
public int NumFlashing
{
set { this.numFlashing = value; }
get { return this.numFlashing; }
}
public Timer tickTimer;
public string PortName
{
set { this.portName = value; }
get { return this.portName; }
}
//控制开关量的指令
string[] str = {
"5501010200000059",
"5501010100000058",
"5501010002000059",
"5501010001000058",
"5501010000020059",
"5501010000010058",
"5501010000000259",
"5501010000000158",
"550101020202025F",
"550101010101015B",
"5501010000000057" //查询当前四个继电器的运行状态
};
#endregion

#region 四路继电器方法区
public EleRelay(string PortName)
{
mycom.PortName = PortName; //四路继电器com口名字
mycom.Parity = Parity.None; //校验位0位
mycom.StopBits = StopBits.One; //停止位1位
mycom.BaudRate = 9600;
mycom.DataBits = 8;
tickTimer = new Timer(20);
tickTimer.Elapsed +=new ElapsedEventHandler(tickTimer_Elapsed);
//tickTimer.Enabled = true;
numFlashing = 4; //默认一号灯完成闪烁功能
}

//委托在本线程上完成的闪烁功能
private void tickTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!flag)
{
byte[] data = sendByte(str[(numFlashing - 1) * 2]);
try
{

mycom.Write(data, 0, data.Length);
flag = true;
}
catch
{
throw new Exception("四路继电器写命令出错");
}
}
else
{
byte[] data = sendByte(str[(numFlashing - 1) * 2 + 1]);
try
{
mycom.Write(data, 0, data.Length);
flag = false;
tickTimer.Stop();
}
catch
{
throw new Exception("四路继电器写命令出错");
}
}
}

//获得向串口发送的16进制数据
private byte[] sendByte(string temps)
{
byte[] tempb = new byte[50];
int j = 0;
for (int i = 0; i < temps.Length; i = i + 2, j++)
tempb[j] = Convert.ToByte(temps.Substring(i, 2), 16);
byte[] send = new byte[j];
Array.Copy(tempb, send, j);
return send;
}

//打开或者关闭某开关
private void Switch(int num, bool flag)
{
int numInstruct = 0;
if (flag)
{
numInstruct = (num - 1) * 2;
}
else
{
numInstruct = (num - 1) * 2 + 1;
}
byte[] data = sendByte(str[numInstruct]);
try
{
mycom.Write(data, 0, data.Length);
}
catch
{
throw new Exception("四路继电器写命令出错");
}
}

//打开串口
public void Open()
{
if (mycom.IsOpen)
{
mycom.DiscardInBuffer();
mycom.DiscardOutBuffer();
}
else
{
try
{
mycom.Open();
mycom.DiscardOutBuffer();
mycom.DiscardInBuffer();
}
catch
{
throw new Exception("继电器串口打开失败");
}
}
}

//关闭串口
public void Close()
{
if (mycom.IsOpen)
{
try
{
mycom.Close();
}
catch
{
//不用做进一步的处理
}
}
}
#endregion
}
}

转自: http://blog.csdn.net/duksom/article/details/17583081