串口助手控制设备的开关
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace 串口控制
{
public partial class Form1 : Form
{
//device 1
const byte DeviceOpen1 = 0x01;//开
const byte DeviceClose1 = 0x81;//关
//device 2
const byte DeviceOpen2 = 0x02;
const byte DeviceClose2 = 0x82;
//device 3
const byte DeviceOpen3 = 0x03;
const byte DeviceClose3 = 0x83;
//SerialPort Write Buffer
byte[] SerialPortDataBuffer = new byte[1];
public Form1()
{
InitializeComponent(); //窗口构造
}
private void Form1_Load(object sender, EventArgs e)
{
ovalShape1.FillColor = Color.Gray;//灯变灰
SearchAndAddSerialToComboBox(serialPort1, comboBox1);
}
private void button1_Click(object sender, EventArgs e)//打开、关闭按键
{
if (serialPort1.IsOpen) //串口打开就关闭
{
try
{
serialPort1.Close();
}
catch { } //确保万无一失
ovalShape1.FillColor = Color.Gray;//灯变灰(当button按钮为“打开串口”)
button1.Text = "打开串口";
}
else
{
try
{
serialPort1.PortName = comboBox1.Text; //端口号
serialPort1.Open(); //打开端口
ovalShape1.FillColor = Color.Green;//灯变绿(当button按钮为“关闭串口”)
button1.Text = "关闭串口";
}
catch
{
MessageBox.Show("串口打开失败","错误");
}
}
}
private void WriteByteToSerialPort(byte data) //单字节写入串口
{
byte[] Buffer = new byte [2]{0x00, data }; //定义数组
if (serialPort1.IsOpen) //传输数据的前提是端口已打开
{
try
{
serialPort1.Write(Buffer, 0, 2); //写数据
}
catch
{
MessageBox.Show("串口数据发送出错,请检查.", "错误");//错误处理
}
}
else
{
MessageBox.Show("串口没有打开!","错误");//如果串口没有打开,弹出提示窗口
}
}
/*****************扫描封装函数******************/
private void SearchAndAddSerialToComboBox(SerialPort MyPort,ComboBox MyBox)
{ //将可用端口号添加到ComboBox
//string[] MyString = new string[20]; //最多容纳20个,太多会影响调试效率
string Buffer; //缓存
MyBox.Items.Clear(); //清空ComboBox内容
//int count = 0;
for (int i = 1; i < 20; i++) //循环
{
try //核心原理是依靠try和catch完成遍历
{
Buffer = "COM" + i.ToString();
MyPort.PortName = Buffer;
MyPort.Open(); //如果失败,后面的代码不会执行
// MyString[count] = Buffer;
MyBox.Items.Add(Buffer); //打开成功,添加至下俩列表
MyPort.Close(); //关闭
//count++;
}
catch
{
//count--;
}
}
//MyBox.Text = MyString[0]; //初始化
}
private void button2_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen1); //器件一开
}
private void button3_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose1); //器件一关
}
private void button5_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen2); //器件二开
}
private void button4_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose2); //器件二关
}
private void button7_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen3); //器件三开
}
private void button6_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose3); //器件三关
}
private void button8_Click(object sender, EventArgs e)
{
SearchAndAddSerialToComboBox(serialPort1, comboBox1); //扫描并讲课用串口添加至下拉列表
}
private void ovalShape1_Click(object sender, EventArgs e)
{
}
}
}
www.DoYoung.net(部分代码来至杜洋工作室)