基于VB的PLC与计算机间串行通信实现
*input:将对方传送至输入缓冲区的字符读入到程序。
*output:将字符写入输出缓冲区。
*inbuffercount:传回接收缓冲区中的字符数。
*outbuffercount:传回输出缓冲区中的字符数。
*inputlen:设定串行端口读入字符串的长度。
*inputmode:设定接收数据的方式。
*rthreshold:设定引发接收事件的字符数。
*commevent:传回ONcomm事件发生时的数值码
*oncomm事件:无论是错误或事件发生,都会触发此事件。
(1) 控件参数的初始化
初始化程序如下:
mscomm.comport=2 `使用串口com2
mscomm.settings=9600, e, 7, 2 `波特率9600,偶校验,7位数据位,2位停止位
mscomm.portopen=true `打开通信端口,准备通信
(2) 计算校验码fcs,计算fcs的vb自定义函数如下:
function fcs(byval inputSTr as string) as string
dim slen, i, xorresult as integer
dim tempfes as string
slen=len(inputstr) `求输入字符串长度
xorresult = 0
for i = 1 to slen
xorresult = xorresult xor asc(mid$(inputstr, i, 1)) `按位异或
next i
tempfes=hex$(xorresult) `转化为16进制
if len(tempfes)=1then tempfes =“0”+tempfes
fcs = tempfes
end function
主要是一个自定义函数。
function readdata(byval inputstr as string, byval num as integer) as string
dim outputstr as string
dim instring as string
dim returnstr as string
dim endstring as string
dim fcsstring as string
dim returnfcsstring as string)
mscomm.inbuffercount=0
utputstr=inputstr+fcs(inputstr)+“*” `给出命令帧
mscomm.output=outputstr+chr$(13) `向PLC传送命令帧
do
doevents
loop while mscomm.inbuffercount 15
instring=mscomm.input `获取PLC的响应帧
`结束码判断
endstring = mid$(instring, len(instring) -
num- 5, 2)
评论