Example code for implementing Modbus RTU communication based on STM32 microcontroller, using STM32 HAL library and modbus-STM32 library

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Example code for implementing Modbus RTU communication based on STM32 microcontroller, using STM32 HAL library and modbus-STM32 library缩略图

To implement Modbus RTU communication using HAL library and modbus-STM32 library based on STM32 microcontroller, you can follow the steps below:

  1. preparation:
    • Ensure that you have installed the STM32 CubeMX and HAL libraries.
    • Download and integrate the modbus-STM32 library into your project. You can find this repository on GitHub and integrate it according to its documentation.
    • Create a new CubeMX project, select the appropriate STM32 microcontroller model, and then configure peripherals such as clock and serial port.
  2. Configure serial communication:
    • Use CubeMX to configure the serial port for Modbus RTU communication. Ensure that the serial port configuration complies with the Modbus RTU standard, such as 8-bit data bits, 1-bit stop bits, and no parity check.
    • Enable serial port interrupts in the HAL library to handle receiving and sending data.
  3. Configuring the modbus-STM32 library:
    • According to the documentation of the modbus-STM32 library, configure the library to use the serial port and registers you have selected. Initialize the Modbus communication stack, including configuring parameters such as Modbus slave address and baud rate.
    • Initialize the Modbus communication stack, including configuring parameters such as Modbus slave address and baud rate.
  4. Writing Modbus RTU main program:
    • In the main program, you need to create a Modbus RTU request and send it to the Modbus slave device, then wait for a response.
    • Process the response to extract data from it.

Below is a simple example code for initializing a serial port and modbus-STM32 library, and sending a Modbus RTU read and hold register request and parsing the response. The basic example provided above includes STM32's HAL library and modbus-STM32 library, which are used to implement Modbus RTU communication. Here are some explanations about this code: The

#include "main.h"
#include "modbus.h"

UART_HandleTypeDef huart1;

void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);

int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_USART1_UART_Init();

  modbus_init();

  while (1)
  {
    modbus_update();
  }
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  modbus_rx_char(huart->Instance->DR);
  HAL_UART_Receive_IT(&huart1, (uint8_t*)modbus_tx_buf, 1);
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
  modbus_tx_end();
}

void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                              | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

static void MX_USART1_UART_Init(void)
{
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 9600;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_UART_Receive_IT(&huart1, (uint8_t*)modbus_tx_buf, 1);
}

static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  __HAL_RCC_GPIOC_CLK_ENABLE();

  GPIO_InitStruct.Pin = GPIO_PIN_13;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}

In the code example provided above, the HAL library and modbus-STM32 library of STM32 are included to implement Modbus RTU communication. Here are some explanations about this code:

  1. code initializes the HAL library, system clock, GPIO (GPOC Pin 13 as an output pin), and UART1 serial port. Then, it initializes the modbus-stm32 library and starts an infinite loop in whichmainfunction of themodbus_updateis called to handle Modbus communication. The
  2. HAL_UART_RxCpltCallbackThe function is a UART receive interrupt callback function used to process received data. In this function,modbus_rx_charUsed to process received characters and by callingHAL_UART_Receive_ITWaiting for the reception of the next character. This is a basic serial port receiving method used for Modbus communication.
  3. HAL_UART_TxCpltCallbackThe function is a UART send interrupt callback function used to handle send completion events. heremodbus_tx_endUsed to notify the Modbus library that the transmission has been completed.
  4. SystemClock_ConfigThe function configures the system clock. In this example, the clock is configured to use an HSI oscillator, 16 frequency division, and 9600 baud rate. Please configure the clock according to your hardware and performance requirements.
  5. MX_USART1_UART_InitThe function initializes the UART1 serial port and configures the baud rate, data bits, stop bits, parity bits, etc. You need to make corresponding changes based on your serial port configuration.
  6. MX_GPIO_InitThe function is configured with GPOC Pin 13 as an output pin. This pin can be used to control other devices, such as indicator lights, when needed.

This code provides a basic Modbus RTU communication framework, but you need to further configure the modbus-STM32 library to meet your specific needs, including slave addresses, function codes, and register addresses. Ensure to set up according to the documentation of the modbus-STM32 library and make appropriate modifications based on your application requirements.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

《“Example code for implementing Modbus RTU communication based on STM32 microcontroller, using STM32 HAL library and modbus-STM32 library”》 有 1 条Comments

Leave a Reply

Your email address will not be published. Required fields are marked *.