资源描述:
《通过MODBUS TCP读写PLC数据源码》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、通过MODBUSTCP读写PLC源码功能模块一:读写PLC主模块usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Windows.Forms;//////通过modbusTCP读写PLC数据,//////设计:张东启,2011.4.9///2011.5.13更新,加入Application.DoEvents();以防连续读写时引起前台反应迟顿,同时让PLC有处理等待时间////////////publicclassPLC
2、Function{publicstaticboolConnected=false;publicstaticinttrytimes=0;//内部使用变量privatestaticbyte[]sendBuf={0,0,0,0,0,06,255,0,0,0,0,0,0,0,0,0,0,0,0,0};//共20个字节privatestaticbyte[]recBuf={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//共20个字节privatestaticinthi,low,bytes,hi1,low1;p
3、rivatestaticSocketzdqSocket;privatestaticstringtiaoshi="N";privatestaticstringplcAddress="127.0.0.1";publicstaticintReadWord(intmwAddress){intrtValue=-99;if(init_plc()==0){try{hi=mwAddress/256;low=mwAddress-hi*256;sendBuf[7]=3;sendBuf[8]=(byte)hi;sendBuf[9]=(byte)low;se
4、ndBuf[10]=0;sendBuf[11]=1;//发送查询zdqSocket.Send(sendBuf,12,0);Application.DoEvents();bytes=zdqSocket.Receive(recBuf,11,0);//返回11个字节if(bytes==11){hi=recBuf[9];low=recBuf[10];rtValue=hi*256+low;}trytimes=0;}catch(Exceptionte){if(tiaoshi=="Y")MessageBox.Show(te.ToString());
5、trytimes++;}}returnrtValue;}publicstaticvoidWriteWord(intmwAddress,intmwValue){if(init_plc()==0){try{hi=mwAddress/256;low=mwAddress-hi*256;hi1=mwValue/256;low1=mwValue-hi*256;sendBuf[7]=6;sendBuf[8]=(byte)hi;sendBuf[9]=(byte)low;sendBuf[10]=(byte)hi1;sendBuf[11]=(byte)l
6、ow1;zdqSocket.Send(sendBuf,12,0);Application.DoEvents();bytes=zdqSocket.Receive(recBuf,recBuf.Length,0);//写一个字返回几个?trytimes=0;}catch(Exceptionte){if(tiaoshi=="Y")MessageBox.Show(te.ToString());trytimes++;}}}publicstaticintGetMemory(intmwAddress){intrtValue=-99;if(init_p
7、lc()==0){try{hi=mwAddress/256;low=mwAddress-hi*256;sendBuf[7]=2;sendBuf[8]=(byte)hi;sendBuf[9]=(byte)low;sendBuf[10]=0;sendBuf[11]=1;//发送查询zdqSocket.Send(sendBuf,12,0);Application.DoEvents();bytes=zdqSocket.Receive(recBuf,10,0);//返回11个字节if(bytes==10){hi=recBuf[9];rtValu
8、e=hi;}trytimes=0;}catch(Exceptionte){if(tiaoshi=="Y")MessageBox.Show(te.ToString());trytimes++;}}returnrtValue