cancel
Showing results for 
Search instead for 
Did you mean: 

stm32 modbus

sreedharan1196
Associate II

I am working on stm32u0 with ultrasonic flow meter, i am facing an issue to receive the response from the device using Modbus communication

 

#include "main.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
 
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#define GETCHAR_PROTOTYPE int __io_getchar(void)
#define MODBUS_SLAVE_ID 0x01
#define MODBUS_FUNCTION_READ_HOLDING_REGISTERS 0x03
uint8_t uart2_tx_data[8];
uint8_t uart2_rx_data[15];
uint16_t recv_data[2];
 
#define DATA_REGISTER_START_POSITIVE 115  // Positive accumulator value
#define DATA_REGISTER_START_NEGATIVE 117  // Negative accumulator value
#define DATA_REGISTER_START_NET      119  // Net accumulator value
 
int REGISTERS_TO_READ = 0x02;    // Number of registers to read
 
UART_HandleTypeDef hlpuart1;
UART_HandleTypeDef huart3;
 
PUTCHAR_PROTOTYPE
{
    HAL_UART_Transmit(&huart3, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
    return ch;
}
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_LPUART1_UART_Init(void);
 
void modbusPreTransmission(void);
void modbusPostTransmission(void);
void sendModbusRequest(uint8_t *request, uint8_t len);
void ultrasonic_value(int DATA_REGISTER_START, int REGISTERS_TO_READ);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);
 
void modbus_tx_data()
{
 
    uint8_t slaveAddress = MODBUS_SLAVE_ID;
    uint8_t functionCode = MODBUS_FUNCTION_READ_HOLDING_REGISTERS;
    uint16_t startAddress = DATA_REGISTER_START_POSITIVE-1;
    uint8_t numRegistersHigh = 0x00;
    uint8_t numRegistersLow = REGISTERS_TO_READ;
 
    uart2_tx_data[0] = slaveAddress;
    uart2_tx_data[1] = functionCode;
    uart2_tx_data[2] = startAddress >> 8;
    uart2_tx_data[3] = startAddress & 0xFF;
    uart2_tx_data[4] = numRegistersHigh;
    uart2_tx_data[5] = numRegistersLow;
    uint16_t crc = crc16(uart2_tx_data, 6);
    uart2_tx_data[6] = crc & 0xFF;
    uart2_tx_data[7] = (crc >> 8) & 0xFF;
 
    printf("The Uart_tx buffer: ");
    for (int i = 0; i < 8; ++i)
    {
        printf("%02X ", uart2_tx_data[i]);
    }
    printf("\r\n");
 
    sendModbusRequest(uart2_tx_data, 8);
}
 
void modbusPreTransmission()
{
printf("Date pin enabled........\r\n");
    HAL_GPIO_WritePin(data_enable_GPIO_Port, data_enable_Pin, GPIO_PIN_SET);
    HAL_Delay(1000);
}
 
void modbusPostTransmission()
{
printf("Data pin disabled......\r\n");
    HAL_GPIO_WritePin(data_enable_GPIO_Port, data_enable_Pin, GPIO_PIN_RESET);
    HAL_Delay(1000);
}
 
void sendModbusRequest(uint8_t *request, uint8_t len)
{
    printf("Sending data to the Modbus...\r\n");
    modbusPreTransmission();
    if (HAL_UART_Transmit(&hlpuart1, request, len, 2000) == HAL_OK)
    {
        printf("\nSuccess : UART transmit done\r\n\n");
    }
    else
    {
        printf("\nError : UART transmit failed\r\n\n");
        return;
    }
 
    modbusPostTransmission();
 
    printf("Waiting for response...\r\n");
        HAL_Delay(100); // Adjust delay as necessary
 
        if (HAL_UART_Receive(&hlpuart1, uart2_rx_data, 7 + (2 * REGISTERS_TO_READ), 2000) == HAL_OK)
        {
            printf("Received data from Modbus: ");
            for (int i = 0; i < (7 + 2 * REGISTERS_TO_READ); ++i)
            {
                printf("%02X ", uart2_rx_data[i]);
            }
            printf("\r\n");
        }
        else
        {
            printf("Error: UART receive failed\r\n");
        }
}
 
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == LPUART1)
    {
        if (uart2_rx_data[1] == MODBUS_FUNCTION_READ_HOLDING_REGISTERS)
        {
            for (int i = 0; i < REGISTERS_TO_READ; i++)
            {
                recv_data[i] = (uart2_rx_data[3 + 2*i] << 8) | uart2_rx_data[4 + 2*i];
            }
 
            float data = *(float*)&recv_data;
 
            printf("Register Data: %f\r\n", data);
        }
        else
        {
            printf("Received unexpected data\r\n");
        }
    }
}
 
uint16_t crc16(uint16_t crc, uint8_t *data, uint32_t length)
{
  int i;
  crc ^= length;
  for (i = 0; i < 8; ++i)
  {
    if (crc & 1)
      crc = (crc >> 1) ^ 0xA001;
    else
      crc = (crc >> 1);
  }
  printf("The CRC : %x",crc);
 
  return crc;
}
int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_LPUART1_UART_Init();
  printf("Welcome to stm32.......\r\n");
  HAL_Delay(2000);
  while (1)
  {
     modbus_tx_data();
HAL_Delay(5000);
  }
}
 
6 REPLIES 6

Please see the posting guidelines - particularly how to properly post source code:

https://community.st.com/t5/community-guidelines/how-to-write-your-question-to-maximize-your-chances-to-find-a/ta-p/575228

 


@sreedharan1196 wrote:

I am working on stm32u0 with ultrasonic flow meter,


Please give the full part number of the STM32, and details of the flow meter

 


@sreedharan1196 wrote:

i am facing an issue to receive the response from the device using Modbus communication


What issue, exactly?

What testing/investigation/debugging have you done to find the problem?

 

Not clear how the callback will occur here.

Blindly waiting for a large block of data is probably not going to work.

You have minimal control of the synchronization of received data, nor the ultimate length.

You should perhaps recover a byte at a time, building a frame, getting it synchronized, and check CRC over the frame. Once you have a full valid frame, pass that on to another subroutine or process to decode / unpack.

Do you have any colleagues or a supervisor who can work through the issues with you locally?

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#include "modbus_crc.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#define GETCHAR_PROTOTYPE int __io_getchar(void)

#define MODBUS_SLAVE_ID 0x01
#define MODBUS_FUNCTION_READ_HOLDING_REGISTERS 0x03

uint8_t uart2_tx_data[8];
uint8_t uart2_rx_data[15];
uint16_t recv_data[2];

#define DATA_REGISTER_START_POSITIVE 115  // Positive accumulator value
#define DATA_REGISTER_START_NEGATIVE 117  // Negative accumulator value
#define DATA_REGISTER_START_NET      119  // Net accumulator value

int REGISTERS_TO_READ = 0x02;    // Number of registers to read

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */


/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

UART_HandleTypeDef hlpuart1;
UART_HandleTypeDef huart3;

/* USER CODE BEGIN PV */

PUTCHAR_PROTOTYPE
{
    HAL_UART_Transmit(&huart3, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
    return ch;
}

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_LPUART1_UART_Init(void);
/* USER CODE BEGIN PFP */

void modbusPreTransmission(void);
void modbusPostTransmission(void);

void sendModbusRequest(uint8_t *request, uint8_t len);
void ultrasonic_value(int DATA_REGISTER_START, int REGISTERS_TO_READ);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void modbus_tx_data()
{

	    uint8_t slaveAddress = MODBUS_SLAVE_ID;
	    uint8_t functionCode = MODBUS_FUNCTION_READ_HOLDING_REGISTERS;
	    uint16_t startAddress = DATA_REGISTER_START_POSITIVE-1;
	    uint8_t numRegistersHigh = 0x00;
	    uint8_t numRegistersLow = REGISTERS_TO_READ;

	    uart2_tx_data[0] = slaveAddress;
	    uart2_tx_data[1] = functionCode;
	    uart2_tx_data[2] = startAddress >> 8;
	    uart2_tx_data[3] = startAddress & 0xFF;
	    uart2_tx_data[4] = numRegistersHigh;
	    uart2_tx_data[5] = numRegistersLow;
//
//	    uint8_t frame[] = {0x01, 0x03, 0x00, 0x72, 0x00, 0x02};
//	    uint16_t len = sizeof(frame) / sizeof(frame[0]);
//
//	    uint16_t crc = crc16(frame, len-1);

	    uint16_t crc = crc16(uart2_tx_data, 6);
	    uart2_tx_data[6] = crc & 0xFF;
	    uart2_tx_data[7] = (crc >> 8) & 0xFF;

	    printf("The Uart_tx buffer: ");
	    for (int i = 0; i < 8; ++i)
	    {
	        printf("%02X ", uart2_tx_data[i]);
	    }
	    printf("\r\n");

    sendModbusRequest(uart2_tx_data, 8);
}

void modbusPreTransmission()
{
	printf("Date pin enabled........\r\n");
    HAL_GPIO_WritePin(data_enable_GPIO_Port, data_enable_Pin, GPIO_PIN_SET);
    HAL_Delay(1000);
}

void modbusPostTransmission()
{
	printf("Data pin disabled......\r\n");
    HAL_GPIO_WritePin(data_enable_GPIO_Port, data_enable_Pin, GPIO_PIN_RESET);
    HAL_Delay(1000);
}

void sendModbusRequest(uint8_t *request, uint8_t len)
{
    printf("Sending data to the Modbus...\r\n");
    modbusPreTransmission();
    if (HAL_UART_Transmit(&hlpuart1, request, len, 2000) == HAL_OK)
    {
        printf("\nSuccess : UART transmit done\r\n\n");
    }
    else
    {
        printf("\nError : UART transmit failed\r\n\n");
        return;
    }

    modbusPostTransmission();

    printf("Waiting for response...\r\n");
        HAL_Delay(100); // Adjust delay as necessary

        if (HAL_UART_Receive(&hlpuart1, uart2_rx_data, 7 + (2 * REGISTERS_TO_READ), 2000) == HAL_OK)
        {
            printf("Received data from Modbus: ");
            for (int i = 0; i < (7 + 2 * REGISTERS_TO_READ); ++i)
            {
                printf("%02X ", uart2_rx_data[i]);
            }
            printf("\r\n");
        }
        else
        {
            printf("Error: UART receive failed\r\n");
        }
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == LPUART1)
    {
        if (uart2_rx_data[1] == MODBUS_FUNCTION_READ_HOLDING_REGISTERS)
        {
            for (int i = 0; i < REGISTERS_TO_READ; i++)
            {
                recv_data[i] = (uart2_rx_data[3 + 2*i] << 8) | uart2_rx_data[4 + 2*i];
            }

            float data = *(float*)&recv_data;

            printf("Register Data: %f\r\n", data);
        }
        else
        {
            printf("Received unexpected data\r\n");
        }
    }
}

uint16_t crc16(uint16_t crc, uint8_t *data, uint32_t length)
{
  int i;
  crc ^= length;
  for (i = 0; i < 8; ++i)
  {
    if (crc & 1)
      crc = (crc >> 1) ^ 0xA001;
    else
      crc = (crc >> 1);
  }
  printf("The CRC : %x",crc);

  return crc;
}



/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_LPUART1_UART_Init();
  /* USER CODE BEGIN 2 */

  printf("Welcome to stm32.......\r\n");
  HAL_Delay(2000);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
     modbus_tx_data();
	 HAL_Delay(5000);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE2);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief LPUART1 Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_LPUART1_UART_Init(void)
{

  /* USER CODE BEGIN LPUART1_Init 0 */

  /* USER CODE END LPUART1_Init 0 */

  /* USER CODE BEGIN LPUART1_Init 1 */

  /* USER CODE END LPUART1_Init 1 */
  hlpuart1.Instance = LPUART1;
  hlpuart1.Init.BaudRate = 115200;
  hlpuart1.Init.WordLength = UART_WORDLENGTH_8B;
  hlpuart1.Init.StopBits = UART_STOPBITS_1;
  hlpuart1.Init.Parity = UART_PARITY_NONE;
  hlpuart1.Init.Mode = UART_MODE_TX_RX;
  hlpuart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  hlpuart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  hlpuart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_RS485Ex_Init(&hlpuart1, UART_DE_POLARITY_HIGH, 0, 0) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetTxFifoThreshold(&hlpuart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetRxFifoThreshold(&hlpuart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_DisableFifoMode(&hlpuart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN LPUART1_Init 2 */

  /* USER CODE END LPUART1_Init 2 */

}

/**
  * @brief USART3 Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_USART3_UART_Init(void)
{

  /* USER CODE BEGIN USART3_Init 0 */

  /* USER CODE END USART3_Init 0 */

  /* USER CODE BEGIN USART3_Init 1 */

  /* USER CODE END USART3_Init 1 */
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 115200;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart3.Init.ClockPrescaler = UART_PRESCALER_DIV1;
  huart3.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetTxFifoThreshold(&huart3, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetRxFifoThreshold(&huart3, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_DisableFifoMode(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART3_Init 2 */

  /* USER CODE END USART3_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(data_enable_GPIO_Port, data_enable_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : data_enable_Pin */
  GPIO_InitStruct.Pin = data_enable_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(data_enable_GPIO_Port, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */



/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @PAram  file: pointer to the source file name
  * @PAram  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

will u plz guide me how to work with it 

Pavel A.
Evangelist III

Several Modbus projects are on github, have a look.

https://github.com/urands/stModbus

https://github.com/alejoseb/Modbus-STM32-HAL-FreeRTOS

and more.

 

You didn't enable UART interrupt so HAL_UART_RxCpltCallback will never be called. 

Tips and Tricks with TimerCallback https://www.youtube.com/@eebykarl
If you find my solution useful, please click the Accept as Solution so others see the solution.