Mark
Mark

Reputation: 5102

How to read/write datetime from modbus in ESP32-S3

In my ESP32-S3 program I created a modbus holding register to store a unix timestamp value. Here the definition of the memory area:

#pragma pack(push, 1)
typedef struct
{
    uint64_t datetime; // 400001
} holding_reg_params_t;
#pragma pack(pop)

from a function called every second I update it with the Unix time:

static portMUX_TYPE param_lock = portMUX_INITIALIZER_UNLOCKED;

void Tasks1s(void)
{
    time_t now;
    time(&now);
    portENTER_CRITICAL(&param_lock);
    holding_reg_params.datetime = now;
    portEXIT_CRITICAL(&param_lock);
}

here, instead, I catch the write operation from master to update the current time:

static portMUX_TYPE param_lock = portMUX_INITIALIZER_UNLOCKED;

static void slave_operation_func(void *arg)
{
    mb_param_info_t reg_info; 
    
    while (1)
    {
        mb_event_group_t event = mbc_slave_check_event(MB_WRITE_MASK);
        if (event & MB_EVENT_HOLDING_REG_WR)
        {
            mbc_slave_get_param_info(&reg_info, MB_PAR_INFO_GET_TOUT);
            if (reg_info.address == (uint8_t*) &holding_reg_params.datetime)
            {
                portENTER_CRITICAL(&param_lock);
                settimeofday(&holding_reg_params.datetime, NULL);
                portEXIT_CRITICAL(&param_lock);
            }
        }

        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

It almost work, but in an odd way. Using ModbusTools I write this value 1722368161 but the next read returns 1722369248.

Not calling Tasks1s() allows me to write the correct value. Hence I bet I'm doing something wrong the the locks.

Upvotes: 0

Views: 67

Answers (0)

Related Questions