2024年5月11日发(作者:)

VB2005中SerialPort发送与接收16进制数据

上一篇帖子介绍了vb2005中serialport的基本用法,需要注意的是writeline是在发

送字符串后加了个换行符(vblf),readline接收时遇到换行符接收才结束。isopen的用

法只能判断用open方法打开的串口,其他程序已打开的串口是无法判断的,所以判断未

使用的串口还要用try或on error的方法判断。

上位机和单片机通信用16进制比较多,下面是16进制通信的例子,数据发送用write,

数据接收用readbyte。

imports 使用serialport所引用的命名空间

public class form1

dim fx() as byte 待发送数据数组

dim rc() as byte 接收数据数组

private sub button1_click(byval sender as , byval e as

entargs) handles

if = 打开串口 then

me = com1

() 串口打开与关闭

= 关闭串口

d = true

d = true

else

if then ()

= 打开串口

d = false

d = false

end if

end sub

待发送数据处理与发送

private sub button2_click(byval sender as , byval e as

entargs) handles

dim i as integer

dim n as integer

dim cmd as string =

n = len(cmd) 2

redim fx(n)

for i = 1 to n

fx(i) = cbyte(&h & mid(cmd, 2 * i - 1, 2))

next

(fx, 1, n) 发送数组fx第1到n数据

end sub

数据定时接收与显示

private sub timer1_tick(byval sender as , byval e as

args) handles

dim strrc as string

dim i as integer

dim n as integer

n = oread 读缓冲区数据量,有数据则接收

if n > 0 then

redim rc(n)

strrc =

for i = 1 to n

rc(i) = te

strrc += cstr(hex(rc(i))) & 数据转为16进制显示

next

= strrc

end if

end sub

end class