用跳线使串口的第2、3针连接,可以在本地计算机上实现串口通信,所以,通过串口的第2、3针的连接可以对程序进行检测。串口截面图如图左所示。
串口编程核心:
² 打开串口: SerialPort serialPort1; // 一般定义为全局的 if ( serialPort1 == null ) serialPort1 = new SerialPort ( ); else if ( serialPort1.IsOpen ) serialPort1.Close ( ); …// 参数定义 serialPort1.RtsEnable = true; //该值指示在串行通信中是否启用请求发送 (RTS) 信号。 serialPort1.DataReceived += new SerialDataReceivedEventHandler ( serialPort1_DataReceived ); // 自定义一个接收方法,委托给串口接收数据的方法,处理接收的数据。 serialPort1.Open ( ); ² 发送字符串:一次可以发送多少个字符,由自定义: byte [ ] bytes = StringMethod.SendInfoToByteArray ( sInfo.Trim ( ) ) serialPort1.Write ( bytes , 0 , bytes.Length ); //发送的字符串逐位转换 public static byte [ ] SendInfoToByteArray ( string sInfo ) { byte [ ] bytes = null; string [ ] strs = sInfo.Trim ( ).Split ( ' ' ); if ( strs.Length > 0 ) { bytes = new byte [ strs.Length ]; for ( int i = 0 ; i < strs.Length ; i++ ) { bytes [ i ] = Convert.ToByte ( strs [ i ].Trim ( ) , 16 ); } } return bytes; } ² 接收数据:一次收不完(一般是一次接受8个字符),要做相应的处理: 接收方法在打开串口前委托给了serialPort1.DataReceived,当有数据返回时进入此方法。 public void serialPort1_DataReceived ( object sender , SerialDataReceivedEventArgs e ) if ( serialPort1.IsOpen )//判断串口是否打开 { int ibr = serialPort1.BytesToRead; if ( ibr <= 0 ) return; this.serialPort1.Read ( buffer , 0 , ibr ); byte [ ] bReceive = new byte [ ibr ]; Array.Copy ( buffer , bReceive , ibr ); //缓冲区数据转换为字符串 string strTmp = StringMethod.ReceiveByteArrayToString ( bReceive ); …//处理字符串 }
390

被折叠的 条评论
为什么被折叠?



