If your USB-Cable is broken, or even when the OpenPLC-runtime is aborted you may acounter problems with outputs remain its current state. For this case I've extended the Arduino-Code with a modbus-timeout of 1 second and set the outputs to defined default-values (safestate).
Here is the code that I've changed:
In OpenPLC_Uno.ino line 58-60 (note that my amount of outputs differs from the original code)
//(de)fault-values
bool default_DOUT[] = {1, 1, 1, 1, 1, 1, 1, 1};
int default_AOUT[] = {0, 0};
and the loop at the bottom:
void loop()
{
//Run the main modbus task
int result = modbus.task();
//Update modbus registers
for (int i = 0; i < NUM_DISCRETE_INPUT; ++i)
{
modbus.Ists(i, digitalRead(pinMask_DIN[i]));
}
for (int i = 0; i < NUM_INPUT_REGISTERS; ++i)
{
modbus.Ireg(i, (analogRead(pinMask_AIN[i]) * 64));
}
for (int i = 0; i < NUM_COILS; ++i)
{
if(result == 0)
digitalWrite(pinMask_DOUT[i], modbus.Coil(i));
else
digitalWrite(pinMask_DOUT[i], default_DOUT[i]);
}
for (int i = 0; i < NUM_HOLDING_REGISTERS; ++i)
{
if(result == 0)
analogWrite(pinMask_AOUT[i], (modbus.Hreg(i) / 256));
else
analogWrite(pinMask_AOUT[i], default_AOUT[i]);
}
}
in ModbusSerial.h line 28:
unsigned long _timestamp;
and line 38:
in ModbusSerial.cpp function task (from line 239):
int ModbusSerial::task() {
_len = 0;
while ((*_port).available() > _len) {
_len = (*_port).available();
delayMicroseconds(_t15);
}
if (_len == 0)
{
unsigned long now = millis();
if (now > _timestamp && now - _timestamp > 1000)
return -1;
else
return 0;
}
byte i;
_frame = (byte*) malloc(_len);
for (i=0 ; i < _len ; i++) _frame[i] = (*_port).read();
#ifdef DEBUG_MODE
(*DebugPort).println(F("GOT Serial CMD"));
for (int i=0 ; i < _len ; i++) {
(*DebugPort).print(_frame[i], DEC);
(*DebugPort).print(":");
//(*DebugPort).println(sendbuffer[i], HEX);
}
(*DebugPort).println();
(*DebugPort).println(F("-----------------"));
#endif
if (this->receive(_frame)) {
if (_reply == MB_REPLY_NORMAL)
this->sendPDU(_frame);
else
if (_reply == MB_REPLY_ECHO)
this->send(_frame);
}
free(_frame);
_len = 0;
_timestamp = millis();
return 0;
}
Maybe you find this useful somehow 🙂
greets,
Omicron