S7协议是西门子私有协议。基于OSI模型
因为平时对S7协议研究不多,所以直接使用第三方的DLL, Snap7
这次用的第一个,win32的dll,需要声明引入 public class Snap7
{
[DllImport("Snap7.dll")]
public static extern int Cli_Create();
[DllImport("Snap7.dll")]
public static extern void Cli_Destroy(int Client);
[DllImport("Snap7.dll")]
public static extern int Cli_ConnectTo(int Client, string Address,int Rack,int Slot);
[DllImport("Snap7.dll")]
public static extern int Cli_SetConnectionParams(int Client, string Address, int LocalTSAP, int RemoteTSAP);
[DllImport("Snap7.dll")]
public static extern int Cli_Connect(int Client);
[DllImport("Snap7.dll")]
public static extern int Cli_Disconnect(int Client);
[DllImport("Snap7.dll")]
public static extern int Cli_DBRead(int Client,int DBNumber,int Start,int Size,int Buffer);
[DllImport("Snap7.dll")]
public static extern int Cli_DBWrite(int Client, int DBNumber, int Start, int Size, int Buffer);
[DllImport("Snap7.dll")]
public static extern int Cli_ErrorText(int Error, string Text, int TextLen);
}
使用方法也特别简单, 第1步,启动程序时先创建一个对象 int Client = Cli_Create() int Result = Cli_ConnectTo(Client, "192.168.0.1", 0, 1) //插槽1if(Result ==0) //连接成功{cmdConnect.Enabled = False;cmdClose.Enabled = True;} ShowResult (Result)第3步,读写PLC, 例如DB220.DBB10读1位 Result = Cli_DBRead(Client, 220, 10, 1, Buffer)
Result = Cli_DBWrite(Client, 220, 10, 1, Buffer)
第4步,退出程序时,销毁对象 Cli_Destroy (Client)
|