MB_HoldingRegWr()

MB_HoldingRegWr() is called when a Modbus master sends a Function Code 6 and Function Code 16 command. MB_HoldingRegWr() writes a single holding register value. Integer holding registers are numbered from 0 through (MODBUS_CFG_FP_START_IX – 1). MODBUS_CFG_FP_START_IX allows you to specify the start of ‘floating-point’ (see section 5.09, MD_HoldingRegWrFP()). MB_HoldingRegWr() should only be called by µC/Modbus.

Prototype

void MB_HoldingRegWr (CPU_INT16U reg,
                      CPU_INT16U reg_val, perr)

Arguments

reg

Is the desired holding register to read and can be a number between 0 and MODBUS_CFG_FP_START_IX-1 (depending on your product). It is up to you to decide what application variable is assigned to each holding register number. Note that if your product doesn’t have any floating-point registers but a large number of holding registers, you can set MODBUS_CFG_FP_START_IX to 65535. 

reg_val

Is the desired value for the specified holding register and can be a number between 0 and 65535. Note that your product could have a signed 16-bit integer but this function will ‘temporarily’ treat it as an unsigned value. However, the assignment is performed correctly and your application variable will have the sign set correctly.

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 holding register number you specified is a valid holding register and you are able to have code access the value of this holding register.

MODBUS_ERR_RANGE

if the holding register number passed as an argument is not a valid holding register number for your product.

Returned Value

None

Notes / Warnings

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

Called By:

MBS_FC06_HoldingRegWr() and MBS_FC16_HoldingRegWr() in mbs_core.c

Example

In this example, our product has 2 integer variables that we want to assign to holding registers. Your systems Engineer decided to assign Modbus holding register numbers 1004 and 1005 to the two integer values. You will notice that we disable interrupts to access the variables. This is done in case your CPU is an 8-bit CPU and data accesses to 16-bit values are not atomic.


CPU_INT16U   AppCtr1;
CPU_INT16U   AppCtr2;


void  MB_HoldingRegWr (CPU_INT16U reg, CPU_INT16U reg_val, CPU_INT16U *err)
{
    *perr = MODBUS_ERR_NONE;
    switch (reg) {
        case 1004:
            CPU_CRITICAL_ENTER();
            AppCtr1 = reg_val;
            CPU_CRITICAL_EXIT();
            Break;

        case 1005:
            CPU_CRITICAL_ENTER();
            AppCtr = reg_val;
            CPU_CRITICAL_EXIT();
            break;
 
        default:
            *perr = MODBUS_ERR_RANGE;
            break;
    }
}