700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > C#之windows桌面软件第七课:(下集)串口工具实现数据校验 用灯反应设备状态

C#之windows桌面软件第七课:(下集)串口工具实现数据校验 用灯反应设备状态

时间:2020-06-21 06:19:41

相关推荐

C#之windows桌面软件第七课:(下集)串口工具实现数据校验 用灯反应设备状态

C#之windows桌面软件第七课:(下集)串口工具实现数据校验、用灯反应设备状态

using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO.Ports;namespace Reply{public partial class Form1 : Form{byte DataSended = 0;byte[] DataToSend = new byte[] { 0x01, 0x02, 0x03 }; //数据发送public Form1(){InitializeComponent();System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPortDataReceived); //添加串口中断事件}private void SetOvlShape(int which) //填充颜色 {switch(which){case 0x01:ovalShape1.FillColor = Color.Green;break;case 0x11:ovalShape1.FillColor = Color.Red;break;case 0x02:ovalShape2.FillColor = Color.Green;break;case 0x12:ovalShape2.FillColor = Color.Red;break;case 0x03:ovalShape3.FillColor = Color.Green;break;case 0x13:ovalShape3.FillColor = Color.Red;break;case 0x04:ovalShape1.FillColor = Color.Green;ovalShape2.FillColor = Color.Green;ovalShape3.FillColor = Color.Green;break;case 0x14:ovalShape1.FillColor = Color.Red;ovalShape2.FillColor = Color.Red;ovalShape3.FillColor = Color.Red;break;default:break;}}private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e){byte DataReceived = (byte)(serialPort1.ReadByte()); //单字节读取SetOvlShape(DataReceived);}private void button1_Click(object sender, EventArgs e) //打开/关闭串口{if (serialPort1.IsOpen) //一堆处理……{try{serialPort1.Close();}catch{}button1.Text = "打开串口";}else{try{serialPort1.PortName = comboBox1.Text;//串口号 serialPort1.Open();//打开}catch{MessageBox.Show("串口打开错误,请检查", "串口");}button1.Text = "关闭串口";}}private void SendDataToSerialPort(SerialPort MyPort, byte DataToSend) //单字节发送数据 {byte[] DatasToWrite = new byte[] { DataToSend }; //数据包if (serialPort1.IsOpen){try{MyPort.Write(DatasToWrite, 0, 1);//发数据}catch{MessageBox.Show("串口数据写入错误", "错误");}}}private void Button_Click(object sender, EventArgs e) //三个按键共用一个处理函数{Button MyButton = (Button)sender; //通过tag属性来区分DataSended = Convert.ToByte(MyButton.Tag);SendDataToSerialPort(serialPort1, DataToSend[DataSended - 1]); //发数据}}}

(部分代码来至杜洋工作室)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。