串口数据发送(带数据校验)
- 界面设计
- 上位机&下位机 (注意点)
- 详细代码
①初始化&定义
//定义 DataSended 确定是那个按钮//定义 DataToSend 存放定义好的协议数据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;break;case 2:ovalShape2.FillColor = Color.Green;break;case 3:ovalShape3.FillColor = Color.Green;break;default:break;}}
③打开/关闭串口函数
//****************************************************************////打开串口/关闭串口按钮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 SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e){byte DataReceived = (byte)(~serialPort1.ReadByte()); //因为单片机传回来带符号,所以(byte)强制转换try{timer1.Stop(); //收到了就 关定时器}catch{ }if (DataSended == 0) //防止下位机乱发,不处理return;SetOvlShape(DataReceived);try{if (DataToSend[DataSended - 1] == DataReceived) //校验数据相等{MessageBox.Show(\"数据校验成功\", \"成功!\"); //弹出提示}else{MessageBox.Show(\"数据校验失败\", \"数据校验失败\");}}catch{}}
⑤串口发送数据函数定义
//*********************************************************************************////定义 串口发送事件 函数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; //设定超时时间timer1.Start(); //发送后立即开启 定时器}catch{MessageBox.Show(\"串口数据写入错误\", \"错误\");}}}
⑥三个按钮的单机事件& 定时器函数
//****************************************************************************////三个发送按钮private void Button_Click(object sender, EventArgs e) //三个按键共用一个处理函数{Button MyButton = (Button)sender; //通过tag属性来区分senderDataSended = Convert.ToByte(MyButton.Tag); //确定是那个按钮SendDataToSerialPort(serialPort1, DataToSend[DataSended - 1]); //确定发数据内容}//定时器private void timer1_Tick(object sender, EventArgs e) //定时器事件{string MyStr = DataSended.ToString() + \"路数据校验超时,请检查\"; //Messagebox内容timer1.Stop();MessageBox.Show(MyStr, \"错误\");}private void Form1_Load(object sender, EventArgs e){}
注:参考Doyoung 工作室c#学习教程,学习笔记