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

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

时间:2023-02-08 03:56:37

相关推荐

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 1:ovalShape1.FillColor = Color.Green;ovalShape2.FillColor = Color.Red;ovalShape3.FillColor = Color.Red;break;case 2:ovalShape1.FillColor = Color.Red;ovalShape2.FillColor = Color.Green;ovalShape3.FillColor = Color.Red;break;case 3:ovalShape1.FillColor = Color.Red;ovalShape2.FillColor = Color.Red;ovalShape3.FillColor = Color.Green;break;case 4:ovalShape1.FillColor = Color.Green;ovalShape2.FillColor = Color.Green;ovalShape3.FillColor = Color.Green;break;default:break;}}//串口中断private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e){//单片机中常用的类型是无符号型(在取反的时候不做无符号处理),而C#默认数据类型是整型,所以前面加(byte)强制转换byte DataReceived = (byte)(~serialPort1.ReadByte()); //单字节读取。(取反校验的优点是不破坏原始数据)try{timer1.Stop();//关定时器}catch { }if (DataSended == 0)//防止下位机乱发,不处理return;SetOvlShape(DataReceived);//灯try{if (DataToSend[DataSended - 1] == DataReceived) //校验数据{MessageBox.Show("数据校验成功", "成功!");//弹出提示}else{MessageBox.Show("数据校验失败", "数据校验失败");}}catch{}}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); //发数据timer1.Interval = 3 * 1000; //设定超时时间(3S)timer1.Start();//定时器}catch{MessageBox.Show("串口数据写入错误", "错误");}}}//三个按键共用一个处理函数private void Button_Click(object sender, EventArgs e) {Button MyButton = (Button)sender; //定义一个按键对象//通过tag属性来区分DataSended = Convert.ToByte(MyButton.Tag); //字符串 -》数字型 (用tag的值来区分是那个按键)SendDataToSerialPort(serialPort1, DataToSend[DataSended - 1]); //向串口发送单字节数据}//定时器事件(3s后会执行此函数)private void timer1_Tick(object sender, EventArgs e){string MyStr = DataSended.ToString() + "路数据校验超时,请检查"; //Messagebox内容 timer1.Stop();MessageBox.Show(MyStr, "错误");}}}

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

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