预览加载中,请您耐心等待几秒...
1/6
2/6
3/6
4/6
5/6
6/6

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

通过MODBUSTCP读写PLC源码 功能模块一:读写PLC主模块 usingSystem; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Windows.Forms; ///<summary> ///通过modbusTCP读写PLC数据, /// ///设计:张东启,2011.4.9 ///2011.5.13更新,加入Application.DoEvents();以防连续读写时引起前台反应迟顿,同时让PLC有处理等待时间 /// /// /// ///</summary> publicclassPLCFunction { 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; privatestaticSocketzdqSocket; 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; sendBuf[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()); 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)low1; 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_plc()==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[