Professional Documents
Culture Documents
com
捌用 VB编 写串 口通信程 序
李 小慧
(
唐山师范学院 计算机系,河北 唐 山 06
300
0)
收稿 日期 :20
02.
12.
22
作者简介:李小慧 (1 9
77.
),女 ,河北唐 山人,唐山师范学 院计算机系助教。
.
84 .
维普资讯 http://www.cqvip.com
字 节数时 ,将会 引 发 OnComm 事 件 中的接 收事件 。默认值 为 0,即 寄存 器 中有多 少字符 均不 引发接收 事件 。
CommEve
nt: 只要有 通信 错误 或事件 发生 都会产 生 OnComm 事件 ,CommEvent属 性存有 该错误 或事
件 的数值 码 。CommEvent会 返 回这些 数值码 中 的一个数值 ,来表示 通信 错误或 事件 。例 如 ,ComEvRe
cei
ve
数值,它的意义就是收到 Rt
hre
shol
d个字符或字节。该事件将持续产生直到用 I
npu
t发生从接收寄存器中删
除数据 。
1.
3 程序 实例
我 们 用一个 简 单读 写的例 子米说 明如何进行 串 口通信 。
建 立一 个 EXE文件 ,在 For
m1中分别添 加 5个对 象 :Te
xtl文本 ,用 来输入 要传输 的信 息;Comma
nd1
按 钮 ,用来 发送数 据 ,将 Te
xtl中 的字 符写入 传输 寄存 器;Comma
nd2按钮 ,J
{j米接收 数据 ,即从 串 口的
寄存器 中读 取数 据并 删除 字符 ;Li
stl列表框 ,依 次显示 从 串 口寄存器 中读取 的数据 ;Ms
comml控件 ,利
用 它 的属性 进行 串 口通讯 。
程 序如 下 :
Pdva
te
Sub Command1 Cl
ick()
‘ 发送 数据 函数
Ms comml。Out
put=Text1.
Text ‘
将 Te
xtl中 的字符 串写入 传输 寄存器
End
Sub
Pr
ivat
e Sub
Command2
Cl
ick(
) ‘
判 断 串 口是否打 开,
如果没 有打 开,
打开 串 口并 初始化
I
f Ms
comm
1。Por
tOpen= Fal
se
Then
M scomm
l。Por
tOpen True
Ms
comm1.
Set
ti
ngs=”
9600,
n,8,
1” ’
9600波 特率 ,
无校 验,
8位数据 位,
1位 停 止位
Ms
comm1.
Input
Len=1‘
设 定 串 口读入 的字符 串长度 为 1
Ms
comm 1
.RThr
eshol
d=1
‘
当接收 寄存器 达到 1个字符 时,
引发接 收事 件
End I
f
FndSub
Pr
ivat
e Sub
Form Lo
_ ad(
) ‘
窗体装 载 函数
M scomm
1.Com m Por
t= l
’
设 定 Com1.
用 来进行 串 口通 讯
.
85-
维普资讯 http://www.cqvip.com
第 26卷第 2期 唐 山 师 范 学 院 学 报 2
004年第 2期
If
M scomm
1.Port
Open= Fal
se
Then
M seomm
1.
Por
tOpen=Tr
ue
End
If
Ms
commI
.Out
Bufe
rCount=0 情 空发送 缓冲 区
Ms
comm1.
InBufe
rCount=0 ’
清 空 接收缓 冲 区
End
Sub
Pf
iv ̄e
Sub
Msc
omml
OnComm0 ‘
_
显 示接 收数据 函数
Di
m buferAs
St
ring ‘
定 义 bufe
r为字符 串
bufer=Ms
comm1
.Input
‘
将 接收 寄存器 中 的字符赋值 给 bufe
r
Li
st1
.Addl
tem
bufer
・
将 bufe
r的值 加 入到列 表框 中显示 出来
End
Sub
Use
VB
to
Program
Seri
al
Com m uni
cat
ion
Program
LI
Xi
ao.
hui
(
Depar
tment
of
Comput
er
Sci
ence,Ta
ngs
han
Teac
her
s Col
lege,Hebe
i T ̄gs
ha
n 063000,Chi
na)
Abst
ract:I
ntroduce
the
appl
icat
ion
of
Mso mm Cont
c rol
and
how
to use
it
s par
amet
ers.I
ntr
oduce
th e
meh od t
t o US
e VB6
to
pr
ogr
am
h e
t ser
ial
communi
cat
ion
prog
ram
thr
ough
exampl
es,mai
nly
in
how
to
use
M sc
o mr
n Cont
rol
to
read
dat
a f
orm
ser
ial
por
t or
wr
ited
atai
nto
ser
ial
por
t.
Key
words:s
eri
al
communi
cat
ion;s
oft
ware;pr
oper
 ̄';event
;por
t
责任 编辑 、校 对 :田敬 军
86 .