使用C# 控制串口继电器
基于.Net/c#的继电器控制代码
主题采用的是串口继电器,使用的技术为winform窗体应用程序
// 定义全局变量 USB继电器端口
public SerialPort wport;
// 页面初始化调用方法
private void test2_Load(object sender, EventArgs e)
{
// 页面初始化触发事件 获取电脑上所有可用COM口
foreach (string vPortName in SerialPort.GetPortNames())
{
this.comboBox1.Items.Add(vPortName);
}
}
#region // 连接继电器代码
private void OpenRelay()
{
if (wport == null)
{
try
{
wport = new SerialPort(this.comboBox1.Text, 9600);
wport.DataBits = 8;
wport.Parity = Parity.None;
wport.StopBits = StopBits.One;
wport.Open();
wport.DataReceived += new SerialDataReceivedEventHandler(this.wport_DataReceived);
AddItem("继电器连接成功!", Color.Green);
}
catch (Exception ex)
{
wport = null;
AddItem("继电器连接异常!", Color.Red);
WriterLog("继电器连接异常=====》》》" + ex.Message);
}
}
else
{
AddItem("继电器处于打开状态!", Color.Yellow);
}
}
#endregion
#region // 启动继电器代码
private void StartRelay()
{
try
{
Byte[] cmd = new Byte[4];
cmd[0] = 0xA0;
cmd[1] = 0x01;
cmd[2] = 0x01;
cmd[3] = 0xA2;
wport.Write(cmd, 0, 4);
AddItem("继电器触发打开!", Color.Blue);
}
catch (Exception ex)
{
AddItem("继电器启动异常!", Color.Red);
WriterLog("继电器启动异常=====》》》" + ex.Message);
}
}
#endregion
#region // 关闭继电器代码
private void CloseRelay()
{
try
{
Byte[] cmd = new Byte[4];
cmd[0] = 0xA0;
cmd[1] = 0x01;
cmd[2] = 0x00;
cmd[3] = 0xA1;
wport.Write(cmd, 0, 4);
AddItem("继电器触发关闭!", Color.Brown);
}
catch (Exception ex)
{
AddItem("继电器关闭异常!", Color.Red);
WriterLog("继电器关闭异常=====》》》"+ex.Message);
}
}
#endregion
// 回写错误日志
private void WriterLog(string message)
{
string directoryPath = @"C:\NETLog\ELogInFor\";
string filePath = directoryPath + DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
using (StreamWriter sw = new StreamWriter(filePath, true))
{
sw.WriteLine(message);
}
}
// 页面信息展示提示
private void AddItem(string value, Color color)
{
// richTextBox1是winform控件
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = color;
richTextBox1.SelectedText = $"{value}\n";
richTextBox1.SelectionColor = richTextBox1.ForeColor;
}