上位机发送与接收下位机数据
用自带的SeriPort控件或者可以用seriport类,根据上位机与下位机同行寻得协议发送接收数据。 设置buttion控件,点击buttion 发送相应数据: private void send_buttion_click(object sender,EventArgs e) { Display_text.Text+=DataTime.Now.TOString(“yyyy-MM-dd HH:mm:ss”)+“发送数据”+" ";//在某一时刻,执行了"发送数据指令" Seriport1.ReceiveBytesThreshold=5;//没接收5个字节产生一个接收中断; command=0x01;//发送指令0 标志位; byte[] send=new byte[5]; send[0]=0xFF;//起始 send[1]=0x01;//命令 send[2]=0x0E;//编号 send[3]=0x00;//异或校验字节 send[4]=0xFA;//结束 for(int i=0;i<3;i++) { send[3]^=send[i]; } Seripo1.write(send,0,5);//将send数组中的数据,从0开始发,发到5; } 在load中添加接受处理事件: serialport1.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceive); 接收处理: private void Port_DataReceive(object sender, SerialDataReceivedEventArgs e) { switch(command) { case 0x01: byte[] receive01=new byte[5]; Seriport1.read(receive01,0,5); byte jiaoyan=0x00; for(int i=0;i<3;i++) { jiaoyan^=receive01[i]; } if(jiaoyan==receive01[3]; { String display=bitConvert.ToString(receive01);//将接受到的数组数据转换成字符串 Display_text.Text+=DataTime.Now.TOString(“yyyy-MM-dd HH:mm:ss”)+“j接收数据”+" "+display+" ";//在某一时刻,执行了"发送数据指令" } }
}
