发表于:2011/1/8 21:18:47
#0楼
上一篇帖子介绍了vb2005中serialport的基本用法,需要注意的是writeline是在发送字符串后加了个换行符(vblf),readline接收时遇到换行符接收才结束。isopen的用法只能判断用open方法打开的串口,其他程序已打开的串口是无法判断的,所以判断未使用的串口还要用try或on error的方法判断。
上位机和单片机通信用16进制比较多,下面是16进制通信的例子,数据发送用write,数据接收用readbyte。
imports system.io.ports 使用serialport所引用的命名空间
public class form1
dim fx() as byte 待发送数据数组
dim rc() as byte 接收数据数组
private sub button1_click(byval sender as system.object, byval e as system.eventargs) handles button1.click
if button1.text = 打开串口 then
serialport1.portname = com1
serialport1.open() 串口打开与关闭
button1.text = 关闭串口
button2.enabled = true
timer1.enabled = true
else
if serialport1.isopen then serialport1.close()
button1.text = 打开串口
timer1.enabled = false
button2.enabled = false
end if
end sub
待发送数据处理与发送
private sub button2_click(byval sender as system.object, byval e as system.eventargs) handles button2.click
dim i as integer
dim n as integer
dim cmd as string = textbox1.text
n = len(cmd) \ 2
redim fx(n)
for i = 1 to n
fx(i) = cbyte(&h & mid(cmd, 2 * i - 1, 2))
next
serialport1.write(fx, 1, n) 发送数组fx第1到n数据
end sub
数据定时接收与显示
private sub timer1_tick(byval sender as system.object, byval e as system.eventargs) handles timer1.tick
dim strrc as string
dim i as integer
dim n as integer
n = serialport1.bytestoread 读缓冲区数据量,有数据则接收
if n > 0 then
redim rc(n)
strrc =
for i = 1 to n
rc(i) = serialport1.readbyte
strrc += cstr(hex(rc(i))) & 数据转为16进制显示
next
textbox2.text = strrc
end if
end sub
end class
----------------------------------------------
此篇文章从博客转发
原文地址: Http://blog.gkong.com/more.asp?id=132179&Name=zhouchs
上位机和单片机通信用16进制比较多,下面是16进制通信的例子,数据发送用write,数据接收用readbyte。
imports system.io.ports 使用serialport所引用的命名空间
public class form1
dim fx() as byte 待发送数据数组
dim rc() as byte 接收数据数组
private sub button1_click(byval sender as system.object, byval e as system.eventargs) handles button1.click
if button1.text = 打开串口 then
serialport1.portname = com1
serialport1.open() 串口打开与关闭
button1.text = 关闭串口
button2.enabled = true
timer1.enabled = true
else
if serialport1.isopen then serialport1.close()
button1.text = 打开串口
timer1.enabled = false
button2.enabled = false
end if
end sub
待发送数据处理与发送
private sub button2_click(byval sender as system.object, byval e as system.eventargs) handles button2.click
dim i as integer
dim n as integer
dim cmd as string = textbox1.text
n = len(cmd) \ 2
redim fx(n)
for i = 1 to n
fx(i) = cbyte(&h & mid(cmd, 2 * i - 1, 2))
next
serialport1.write(fx, 1, n) 发送数组fx第1到n数据
end sub
数据定时接收与显示
private sub timer1_tick(byval sender as system.object, byval e as system.eventargs) handles timer1.tick
dim strrc as string
dim i as integer
dim n as integer
n = serialport1.bytestoread 读缓冲区数据量,有数据则接收
if n > 0 then
redim rc(n)
strrc =
for i = 1 to n
rc(i) = serialport1.readbyte
strrc += cstr(hex(rc(i))) & 数据转为16进制显示
next
textbox2.text = strrc
end if
end sub
end class
----------------------------------------------
此篇文章从博客转发
原文地址: Http://blog.gkong.com/more.asp?id=132179&Name=zhouchs
欢迎光临我的BLOG