你好呀!
我有一个带有以太网屏蔽 (W5100) 的 Arduino UNO,代码如下,用于从我的 PLC 读取数据
代码:
全选#include
#include
#include "Settimino.h"
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //MAC
IPAddress ip(192,168,127,14); // Local Address
IPAddress PLC(192,168,127,110); // PLC Address
S7Client Client;
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// Start the Ethernet Library
Ethernet.begin(mac, ip);
delay(200);
Serial.println(Ethernet.localIP());
}
bool Connect()
{
int Result=Client.ConnectTo(PLC,
0, // Rack (see the doc.)
0); // Slot (see the doc.)
Serial.print("Connecting to ");Serial.println(PLC);
if (Result==0)
{
Serial.print("Connected ! PDU Length = ");
Serial.println(Client.GetPDULength());
}
else
Serial.println("Connection error");
return Result==0;
}
void CheckError(int ErrNo)
{
Serial.print("Error No. 0x");
Serial.println(ErrNo, HEX);
// Checks if it's a Severe Error => we need to disconnect
if (ErrNo & 0x00FF)
{
Serial.println("SEVERE ERROR, disconnecting.");
Client.Disconnect();
}
}
byte Empfangen(int Zeile) //einzelne Bytes empfangen
{
int Result;
byte Receive;
// Verbinden
while (!Client.Connected)
{
if (!Connect())
delay(500);
}
Result=Client.ReadArea(S7AreaDB, //DB Zugriff
53, // DB Number = 53
Zeile, // Start ab Byte x
1, // Anzahl der Bytes
&Receive); // Ziel
if (Result==0)
{
return Receive;
}
else
CheckError(Result);
}
void loop()
{
Serial.print("Daten aus SPS: ");
Serial.println(Empfangen(20)); //Lese Byte aus DB Zeile 20
Serial.println("");
delay(500);
}