
54
A.12 Simple demonstration program
The simple ‘C’ program below will show how to read the sensor data and how to deal with errors. The program will read the
registers: ‘operational mode, status flags, scale factor, and sensor data’ from Modbus® device with address 2 into registers
uOperationMode, uStatusFlags, iScaleFactor and iSensorData. Then the program will check the operation mode (must be
‘normal’) and if there are no errors flags set in iStatusFlags. If there is an error then set the
IO_ERROR_FLAG.
UInt16
uOperationalMode = 0;
UInt16
uStatusFlags = 0;
Int16
iScaleFactor = 0;
Int16
iSensorData = 0;
float
fSensorData = 0;
int main (void)
{
while (true)
{
// Send MODBUS request 0x04 Read input registers to slave 2
// Get modus data will wait for the answer and copies the data to registers
// uOperationalMode, uStatusFlags, iScaleFactor and iSensorData
SendModbusRequest (0x04, 2, IO_OPERATIONAL_MODE, 4);
WaitModbusReply ();
GetModbusData ();
If (uOperationalMode != 1)
{
// Send MODBUS request 0x05 write single coil to slave 2
SendModbusRequest (0x05, 2, IO_CLEAR_ERRROR, true);
WaitModbusReply
();
}
else if (uStatusFlags != 0)
{
SendModbusRequest (0x05, 2, IO_CLEAR_ERRROR, true);
WaitModbusReply
();
}
switch (iScaleFactor)
{
case 2: fSensorData = (float)(iSensorData) / 100.0;
case 1: fSensorData = (float)(iSensorData) / 10.0;
case 0: fSensorData = (float)(iSensorData);
case -1: fSensorData = (float)(iSensorData) * 10.0;
default: fSensorData = 0.0;
}
// wait 1 second
Delay (1000);
}
}