Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the library in STM32 project #50

Open
MohammedBENHADINE opened this issue Apr 19, 2024 · 9 comments
Open

Using the library in STM32 project #50

MohammedBENHADINE opened this issue Apr 19, 2024 · 9 comments

Comments

@MohammedBENHADINE
Copy link

MohammedBENHADINE commented Apr 19, 2024

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 :

/* 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 "nanomodbus.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define RTU_SERVER_ADDRESS 1

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

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

/* USER CODE END PFP */

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

int32_t read_serial(uint8_t* buf, uint16_t count, int32_t byte_timeout_ms, void* arg) {
    HAL_StatusTypeDef status = HAL_UART_Receive(&huart2, buf, count, byte_timeout_ms * count);
    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(&huart2, (uint8_t *)buf, count, byte_timeout_ms * count);
    if (status == HAL_OK) {
        return count;
    } else {
        return 0;
    }
}

/* 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_USART2_UART_Init();
  /* USER CODE BEGIN 2 */

  nmbs_platform_conf platform_conf;
  platform_conf.transport = NMBS_TRANSPORT_RTU;
  platform_conf.read = read_serial;
  platform_conf.write = write_serial;

  nmbs_t nmbs;
  nmbs_error err = nmbs_client_create(&nmbs, &platform_conf);
  if (err != NMBS_ERROR_NONE)
	  __NOP();
  nmbs_set_read_timeout(&nmbs, 1000);
  nmbs_set_byte_timeout(&nmbs, 100);

  nmbs_set_destination_rtu_address(&nmbs, RTU_SERVER_ADDRESS);

  // Read 2 holding registers from address 0023h
  uint16_t r_reg[2];
  err = nmbs_read_holding_registers(&nmbs, 0x23, 2, r_reg);
  if (err != NMBS_ERROR_NONE)
	  __NOP();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* 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};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  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_MUL12;
  RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
  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_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

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

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 9600;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

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

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

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

}

/* 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 */

Any help ?

@debevv
Copy link
Owner

debevv commented Apr 19, 2024

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?

@MohammedBENHADINE
Copy link
Author

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.

@debevv
Copy link
Owner

debevv commented Apr 20, 2024

Are read_serial() and write_serial() being called at all?

@MohammedBENHADINE
Copy link
Author

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);
  }
}

@debevv
Copy link
Owner

debevv commented May 7, 2024

Sure! I'll have a look at it and add it to the examples. Thank you

@debevv
Copy link
Owner

debevv commented Sep 20, 2024

@MohammedBENHADINE can you give me more details about your platform? Which STM32 board are you working on?

@MohammedBENHADINE
Copy link
Author

MohammedBENHADINE commented Sep 20, 2024

I developed it for a nucleo board (stm32f030c8) , based on HAL platform from ST ( stm32cubeMX framework).
I can add the complete example in a pull request if u want.

@debevv
Copy link
Owner

debevv commented Sep 23, 2024

Sure, it would be much appreciated!
Like I wrote here #55 (comment), can you include a way for the user to build the project, like a simple makefile and a readme?

@donghoonpark
Copy link

donghoonpark commented Oct 5, 2024

I have added an stm32 example on #69. As it use dma and buffer by default for the stable transaction, I think you can take a look for this one to improve your code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants