Open MohammedBENHADINE opened 2 months ago
I don't see any issue on how you are using the library, except maybe checking the returned error of nmbs_client_create()
.
My main suspects is are those HAL_UART_Receive()
and HAL_UART_Transmit()
. Have you tried to check with an oscilloscope, or with another board, if data is actually going onto the serial line?
Or, for good measure, is RTU_SERVER_ADDRESS
correct?
Thanks for the quick answer. The address is correct ( 1 ). Checking the UART with a USB to UART doesn't show any data coming from the interface.
Are read_serial()
and write_serial()
being called at all?
Hey, after some debugging I figured out that USART2 was internally routed to ST-LINK on-board debugger, and PA2 & PA3 not usable. Switching to USART1 did solve the problem. The library integrates smoothly to STM32 codebase. Here's a working code, could be added to examples folder of library .
#include "nanomodbus.h"
#define RTU_SERVER_ADDRESS 1
#define NMBS_SERVER_DISABLED
UART_HandleTypeDef huart1;
nmbs_t nmbs;
int32_t read_serial(uint8_t* buf, uint16_t count, int32_t byte_timeout_ms, void* arg) {
HAL_StatusTypeDef status = HAL_UART_Receive(&huart1, buf, count, byte_timeout_ms);
if (status == HAL_OK) {
return count;
} else {
return 0;
}
}
int32_t write_serial(const uint8_t* buf, uint16_t count, int32_t byte_timeout_ms, void* arg) {
HAL_StatusTypeDef status = HAL_UART_Transmit(&huart1, (uint8_t *)buf, count, byte_timeout_ms);
if (status == HAL_OK) {
return count;
} else {
return 0;
}
}
static void modbus_init(nmbs_t *nmbs) {
nmbs_platform_conf platform_conf;
platform_conf.transport = NMBS_TRANSPORT_RTU;
platform_conf.read = read_serial;
platform_conf.write = write_serial;
nmbs_error err = nmbs_client_create(nmbs, &platform_conf);
if (err != NMBS_ERROR_NONE)
Error_Handler();
nmbs_set_read_timeout(nmbs, 1000);
nmbs_set_byte_timeout(nmbs, 100);
nmbs_set_destination_rtu_address(nmbs, RTU_SERVER_ADDRESS);
}
uint16_t get_moisture(nmbs_t *nmbs) {
uint16_t r_reg = 0;
nmbs_error err = nmbs_read_holding_registers(nmbs, MOISTURE, 1, &r_reg);
if (err != NMBS_ERROR_NONE)
Error_Handler();
return r_reg;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
modbus_init(&nmbs);
while (1)
{
uint16_t moisture = get_moisture(&nmbs);
HAL_Delay(2000);
}
}
Sure! I'll have a look at it and add it to the examples. Thank you
I'm trying to use this library inside a STM32 CubeIDE project but no success. I've defined the two required functions but polling the registers of the sensor always returns TIMEOUT. The sensor works fine with direct access from Modbus Poll tools ( using UART to USB). Here is my base code :
Any help ?