MB_CoilRd()
MB_CoilRd() is called when a Modbus master sends a Function Code 1 command. MB_CoilRd() returns the value of a single coil. MB_CoilRd() should only be called by µC/Modbus.
Prototype
CPU_BOOLEAN MB_CoilRd (CPU_INT16U coil, CPU_INT16U *perr)
Arguments
coil
Is the coil number that you want to read and can be a number between 0 and 65535 (depending on your product). It is up to you to decide which coil is assigned to what variable in your product.
perr
Is a pointer to a variable that will contain an error code based on the outcome of the call. Your code thus needs to return one of the following error codes:
MODBUS_ERR_NONE
if the coil number you specified is a valid coil and you are able to have code access the value of this coil.
MODBUS_ERR_RANGE
if the coil number passed as an argument is not a valid coil number for your product.
Returned Value
MB_CoilRd() returns the current value of the specified coil number (TRUE or FALSE). If an invalid coil number is specified, you should return FALSE.
Notes / Warnings
Code is enabled when MODBUS_CFG_FC01_EN is set to DEF_ENABLED in your product’s mb_cfg.h file.
Called By:
MBS_FC01_CoilRd() in mbs_core.c
Example
In this example, our product has 163 coils. 160 coils are placed in a table called AppCoilTbl[]. The other three coils are actually variables that we treat as coils to allow a Modbus master to read the status of those values. The first 160 coils are assigned coil numbers 0 to 159. Coil numbers 200, 201 and 202 correspond to the following application variables: AppStatus, AppRunning and AppLED, respectively.
CPU_INT08U AppCoilTbl[20];
CPU_BOOLEAN AppStatus;
CPU_BOOLEAN AppRunning;
CPU_BOOLEAN AppLED;
CPU_BOOLEAN MB_CoilRd (CPU_INT16U coil, CPU_INT16U *perr)
{
CPU_INT08U ix;
CPU_INT08U bit_nbr;
*perr = MODBUS_ERR_NONE;
if (coil < 20 * sizeof(CPU_INT08U)) {
ix = coil / 8;
bit_nbr = coil % 8;
if (AppCoilTbl[ix] & (1 << bit_nbr)) {
return (TRUE);
} else {
return (FALSE);
}
return (val);
} else {
switch (coil) {
case 200:
return (AppStatus);
case 201:
return (AppRunning);
case 202:
return (AppLED);
default:
*perr = MODBUS_ERR_RANGE;
return (0);
}
}
}