用户登陆 用户注册
您的位置:首页>
技术文章>内容正文
如何用VB实现Modbus串行通讯
[正文]:在一些应用中可能需要使用诸如vb来进行上位机监控程序的开发,而modbus协议是这类应用中首选的通讯协议;modbus协议以其简单易用,在工业领域里已广泛的为其他第三方设备所支持。
这里对vb和twido plc间的通讯进行说明。
对于大部分应用,twido plc作为从站,它不需要编制通讯程序,只要把通讯口的参数设置好即可,例如下图表示此twido通过编程口和上位机连接,其站号地址为2;波特率、数据位、校验、停止位和上位机设置保持一致。
vb程序通过利用mscomm控件很容易就能够实现。
1. 通讯口初始化: mscomm1.settings = "9600,n,8,1" mscomm1.commport = 1 mscomm1.sthreshold = 0 if not mscomm1.portopen then mscomm1.portopen = true 2. crc校验码的计算方法,如以下函数,可以得到字节数组变量cmdstring指向的字符串的crc校验码。
function crc16_1(byref cmdstring() as byte, byval j as integer) dim data as integer dim i as integer addressreg_crc = &hffff for i = 0 to j addressreg_crc = addressreg_crc xor cmdstring(i) for j = 0 to 7 data = addressreg_crc and &h1 if data then addressreg_crc = int(addressreg_crc / 2) addressreg_crc = addressreg_crc and &h7fff addressreg_crc = addressreg_crc xor &ha001 else addressreg_crc = addressreg_crc / 2 addressreg_crc = addressreg_crc and &h7fff end if next j next i if addressreg_crc < 0 then addressreg_crc = addressreg_crc - &hffff0000 end if hibyte = addressreg_crc and &hff lobyte = (addressreg_crc and &hff00) / &h100 end function 3. 读多个字的命令(本例是从2号站读%mw10起始的4个字): dim sendstr(7) as byte dim rcvstr() as byte sendstr(0) = 2 ,从站号是2 sendstr(1) = &h3 ,读多个字的命令代码 sendstr(2) = 0 ,起始地址高字节 sendstr(3) = 10,起始地址低字节 sendstr(4) = &h0,数据长度高字节 sendstr(5) = 4 ,数据长度低字节 call crc16(sendstr(), 5) ,crc计算 sendstr(6) = hibyte sendstr(7) = lobyte ,读命令发送后,当接收 5 + sendstr(5) * 2 个字节时产生中断 cmdlenth = 5 + sendstr(5) * 2 mscomm1.rthreshold = cmdlenth mscomm1.output = sendstr ,发送命令 4. 写多个字的命令(本例是写2号站%mw20起始的3个字): dim writestr() as byte k = 6 ,写6个字节 redim writestr(8 + k) writestr(0) = 2 ,从站号是2 writestr(1) = &h10 ,写多个字的命令代码 writestr(2) = 0 ,起始地址高字节 writestr(3) = 20 ,起始地址低字节 writestr(4) = &h0 ,数据长度高字节<字的个数> writestr(5) = k / 2 ,数据长度低字节<字的个数> writestr(6) = k ,数据长度<字节的个数> writestr(7) = &h12,写的第1个字的高字节 writestr(8) = &h34,写的第1个字的低字节 writestr(9) = &h56,写的第2个字的高字节 writestr(10) = &h78,写的第2个字的低字节 writestr(11) = &h9a,写的第3个字的高字节 writestr(12) = &hbc,写的第3个字的低字节 call crc16(writestr(), 6 + k) writestr(9 + (k / 2 - 1) * 2) = hibyte writestr(10 + (k / 2 - 1) * 2) = lobyte mscomm1.inbuffercount = 0 mscomm1.output = writestr ,写命令发送后,当接收到8个字节时中断 cmdlenth = 8 mscomm1.rthreshold = cmdlenth 5. 通讯事件中断产生时的数据处理: private sub mscomm1_oncomm() dim inx() as byte select case mscomm1.commevent case comevreceive ,判断为接收事件 mscomm1.inputlen = cmdlenth ,接收数据的长度 inx = mscomm1.input ,接收数据 mscomm1.inbuffercount = 0 for k = 3 to cmdlenth - 3 tmpstr = tmpstr & "/" & hex(inx(k)) next text1.text = tmpstr ,以十六进制显示所接收长度的数据 beep end select end sub
网站首页
培训课程
维修指南
技术文章
家电专栏
供应信息
求购信息
培训资讯
展会信息
电脑专栏
教程下载
资料下载
常用软件
PLC教程
PLC资料
变频伺服
低压电器
维修资料
人机界面
自控仪表
工控机类
文章标题:
中国工控资源网手机版 2012
电话:010-67577139 13811659603
培训咨询QQ:657167934 471895637 销售咨询QQ:623769457
联系邮箱:zggkzyw@163.com
京ICP备11002135号
报时(2026-04-04 04:01:19)