最近在做系统的监控,想到能不能做一个酷点的功能,当收到异常消息时桌面上的红色小灯(或报警灯)会亮起来。于是在淘宝上找了一下,有这种小设备,插入USB设备,通过串口控制这个设备的继电器来实现,成本也很低,只需要20元人民币。

找了几个卖家,都只能提供C++的程序,现在都什么年代了,C#早已经大行其道。终于博主找一个卖家,他提供了这个设备的C#源程序代码。今天小开关到货了,博主试了一下,用程序简单的控制一路电源开关是可行的,而且很方便和简单。

一、小开关是USB方式接入电脑,接入后,WIN10会自动识别成一个带串口的设备CH341A,并且自动分配一个串口。

二、C#程序VS2022安装后,自带窗口控制类,无需其他类库,全部是系统原生的。
只需要引入 using System.IO.Ports
三、开关的实现就是向设备的串口写一串编码,设备就可以自动控制继电器完成电源的开关。

全部代码如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.IO.Ports;
-
- namespace WindowsFormsApp1
- {
- public partial class Form1 : Form
- {
- //USB继电器端口
- public SerialPort wport;
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- foreach (string vPortName in SerialPort.GetPortNames())
- {
- this.comboBox1.Items.Add(vPortName);
- }
- }
-
- //连接COM
- private void button1_Click(object sender, EventArgs e)
- {
- 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);
- this.label1.Text = "连接成功";
-
- }
- catch (Exception ex)
- {
- wport = null;
- MessageBox.Show(ex.ToString());
- }
- }
- else
- {
- this.label1.Text = "连接失败";
- }
- }
-
- private void wport_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- int n = wport.BytesToRead;
- byte[] buf = new byte[n];
- wport.Read(buf, 0, n);
-
- //因为要访问ui资源,所以需要使用invoke方式同步ui。
- this.Invoke((EventHandler)(delegate
- {
-
- //追加的形式添加到文本框
- for (int index = 0; index < buf.Length; index++)
- {
- this.label1.Text = (((int)buf[index]).ToString("X2") + " ");
- }
- }));
- }
- //开
- private void button2_Click(object sender, EventArgs e)
- {
- try
- {
- Byte[] cmd = new Byte[4];
- cmd[0] = 0xA0;
- cmd[1] = 0x01;
- cmd[2] = 0x01;
- cmd[3] = 0xA2;
- wport.Write(cmd, 0, 4);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
-
- }
- }
- //关闭
- private void button3_Click(object sender, EventArgs e)
- {
- try
- {
- Byte[] cmd = new Byte[4];
- cmd[0] = 0xA0;
- cmd[1] = 0x01;
- cmd[2] = 0x00;
- cmd[3] = 0xA1;
- wport.Write(cmd, 0, 4);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
- }