示例代码功能有:搜索全部串口,搜索可用串口,串口打开与关闭,字符串发送,字符串中断接收。发送接收用的是同一串口,测试时端接串口2、3脚即可。中断接收时无法直接显示收到字符(涉及到跨线程问题),用了个定时器定时刷新显示收到的字符串。
程序界面:
http://blog.gkong.com/uploadfile4/201115135815473.jpg
程序代码:
imports system
imports system.io.ports 使用serialport所引用的命名空间
imports system.threading 使用thread所引用的命名空间
public class form1
dim strrec as string 接收字符串
dim strsend as string 发送字符串
dim intnum as integer 接收字节数=字符数+1(vblf)
private sub button1_click(byval sender as system.object, byval e as system.eventargs) handles button1.click
combobox1.items.clear() 清空列表
combobox2.items.clear()
for each portname as string in my.computer.ports.serialportnames
combobox1.items.add(portname) 显示所有串口
try
serialport1.portname = portname
serialport1.open()
combobox2.items.add(portname) 显示可用串口
serialport1.close()
catch ex as exception
msgbox(可用串口检查 & portname)
end try
next
if combobox1.items.count > 0 then combobox1.selectedindex = 0
if combobox2.items.count > 0 then
combobox2.selectedindex = 0
button2.enabled = true 有可用串口,可以打开操作
end if
end sub
private sub button2_click(byval sender as system.object, byval e as system.eventargs) handles button2.click
if button2.text = 打开串口 then
serialport1.portname = combobox2.text
if not serialport1.isopen then
serialport1.open()
button2.text = 关闭串口
button3.enabled = true 串口打开,可以发送数据
end if
else
if serialport1.isopen then serialport1.close()
button2.text = 打开串口
button3.enabled = false
end if
end sub
private sub button3_click(byval sender as system.object, byval e as system.eventargs) handles button3.click
strsend = textbox1.text
serialport1.writeline(strsend)
end sub
中断接收字符串
private sub serialport1_datareceived(byval sender as object, byval e as system.io.ports.serialdatareceivedeventargs) handles serialport1.datareceived
thread.sleep(100) 根据字符数量及波特率计算延时
intnum = serialport1.bytestoread
strrec = serialport1.readline
end sub
关闭程序时关闭串口
private sub form1_formclosing(byval sender as object, byval e as system.windows.forms.formclosingeventargs) handles me.formclosing
if serialport1.isopen then serialport1.close()
end sub
定时更新显示接收字符串
private sub timer1_tick(byval sender as system.object, byval e as system.eventargs) handles timer1.tick
textbox2.text = strrec
textbox3.text = intnum
end sub
end class
----------------------------------------------
此篇文章从博客转发
原文地址: Http://blog.gkong.com/more.asp?id=131982&Name=zhouchs