MB_CoilWr()

MB_CoilWr()

MB_CoilWr() is called when a Modbus master sends a Function Code 5 and Function Code 15 command. MB_CoilWr() changes the value of a single coil. MB_CoilWr() should only be called by µC/Modbus.

Prototype

void MB_CoilWr (CPU_INT16U coil,

CPU_BOOLEAN coil_val;
CPU_INT16U *perr) 

Arguments

coil

Is the coil number that you want to change 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.

coil_val

Is the value you want to change the coil to and can be either DEF_TRUE or DEF_FALSE.

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

None

Notes / Warnings

Code is enabled when either MODBUS_CFG_FC05_EN is set to DEF_ENABLED or MODBUS_CFG_FC15_EN is set to DEF_ENABLED in your product’s mb_cfg.h file.

Called By:

MBS_FC05_CoilWr() and MBS_FC15_CoilWrMultiple() 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; void MB_CoilWr (CPU_INT16U coil, CPU_BOOLEAN coil_val, 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; CPU_CRITICAL_ENTER(); if (coil_val == TRUE) { AppCoilTbl[ix] |= (1 << bit_nbr); } else { AppCoilTbl[ix] &= ~(1 << bit_nbr); } CPU_CRITICAL_EXIT(); } else { switch (coil) { case 200: AppStatus = coil_val; break; case 201: AppRunning = coil_val; break; case 202: AppLED = coil_val; break; default: *perr = MODBUS_ERR_RANGE; break; } } }