vb.net串口通信(SerialPort控件)
'加载本机所有的com Sub GetSerialPortNames() '打开串口 If SerialPort1.IsOpen Then Try .Parity = IO.Ports.Parity.None '奇偶校验 Label1.Text = "Connected" '关闭串口 SerialPort1.close() '发送数据 一般的数据 dim data as string=textbox1.text SerialPort1.write(data) 十六进制字符串 发送十六进制字符串时,我们用数组保存要发送的信息 比如发送数据为:FF 01 00 00 01 00 00 FE Try 接收数据 SerialPort有个DataReceived事件,我们可以在里面写接受数据代码 接受字符串:SerialPort.ReadExisting 接受流数据: dim byteToRead as int16=SerialPort.bytestoread(读取缓冲区的字节长度) dim ch(byteToRead) as byte dim bytesRead as int16=0 bytesRead=SerialPort.read(ch,bytetoread) for i as int16=0 to bytesRead-1 indata=indata & DecToHex(ch(i)) next indata 就是读取到的数据 自定义函数:DecToHex (返回十六进制字符) Public Function DecToHex(ByVal DecNumber As Byte) As String '转换成十六进制字符串 If DecNumber <= 15 Then DecToHex = " 0" & Hex(DecNumber) Else : DecToHex = " " & Hex(DecNumber) End If End Function (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |