I use this scatch to send Data to an S7-1215 PLC via Modbus TCP and WiFi. My code is obviusly not correct. After e few minutes MKR1010 WiFi stop processing. I need help from an experienced programmer. Thanks in advance.
// This scatch works not properly!
// Communication Arduino Modbus TCP over WiFi to S7-1215
// 10 times per second the S7 reads the holding register 0 - 9 (10) cycle time S7 is constantly 2 ms
// when connection lost, reconnect works fine
// the Problem:
// works only a few minutes then arduino stop processing
// the faster the intervalls, the shorter this working time
// while processing the arduino stop counting after about 12 s for the duration of about 1 s
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>
#include "arduino_secrets.h"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int keyIndex = 0;
int status = WL_IDLE_STATUS;
WiFiServer wifiServer(502);
ModbusTCPServer modbusTCPServer;
uint16_t course = 5500; // testvalue
unsigned long h_previousMillis = 0; // will store last time for delay updating holdingReisters
const long h_interval = 5; // intervall for update holdingRegisters
unsigned long u_previousMillis = 0; // will store last time for update Data
const long u_interval = 1; // intervall for update Data
void setup() {
while (status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
delay(5000); // wait 5 seconds for connection:
}
wifiServer.begin();
if (!modbusTCPServer.begin()) { // start the Modbus TCP server
while (1);
}
// configure HoldingRegister ab 40001 / start adress 0, 20 Adressen lang
modbusTCPServer.configureHoldingRegisters(0x0, 0x14); // or decimal(0, 20)
}
void loop() {
// attempt to connect to WiFi network: if connection lost
while (WiFi.status() != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
delay(5000);
}
WiFiClient client = wifiServer.available(); // listen for incoming clients
if (client) { // a new client connected
modbusTCPServer.accept(client); // let the Modbus TCP accept the connection
while (client.connected()) {
modbusTCPServer.poll(); // poll for Modbus TCP requests, while client connected
updatemodbusloop(); // update holdingReister
updatedataloop(); // counts every loop
// stop WiFi when connection lost
if (WiFi.status() != WL_CONNECTED) {
WiFi.disconnect();
}
}
}
}
void updatemodbusloop() {
unsigned long h_currentMillis = millis();
if (h_currentMillis - h_previousMillis >= h_interval) {
h_previousMillis = h_currentMillis;
modbusTCPServer.holdingRegisterWrite(4, course);
}
}
void updatedataloop(){
unsigned long u_currentMillis = millis();
if (u_currentMillis - u_previousMillis >= u_interval) {
u_previousMillis = u_currentMillis;
course = course + 1;
}
}