cancel
Showing results for 
Search instead for 
Did you mean: 

Uart Interrupt does not work

Imhyeonu
Associate II

Hi, I am using the Nucleo - L152RE board and I am having a problem with the UART1 interrupt.
The output to Teraterm works fine, but it does not go to the interrupt and the code terminates. Can you tell me what the problem is?

 

 

/* 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 <stdlib.h>
#include <string.h>
#include "stm32l1xx_hal.h"
/* USER CODE END Includes */

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

/* 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 huart1;
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
uint32_t ulUartBuffCnt = 0;
uint32_t ulTemp;
uint32_t frameLength = 0;
Buffer uartBuffer;
unsigned short crc;
/* USER CODE END PV */

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

/* USER CODE END PFP */

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

#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)

PUTCHAR_PROTOTYPE
{
    while (!__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TXE));

    huart2.Instance->DR = ch;

    return ch;
}

void Buffer_Init(Buffer *uartBuffer) {
	uartBuffer->head = 0;
	uartBuffer->tail = 0;
}

int Buffer_IsEmpty(Buffer *uartBuffer) {
    return uartBuffer->head == uartBuffer->tail;
}

int Buffer_IsFull(Buffer *uartBuffer) {
    return ((uartBuffer->head + 1) % BUFFER_SIZE) == uartBuffer->tail;
}

void Buffer_Write(Buffer *uartBuffer, unsigned char data) {
    if (Buffer_IsFull(uartBuffer)) {
        printf("Buffer full! Overwriting oldest data.\n");
        uartBuffer->tail = (uartBuffer->tail + 1) % BUFFER_SIZE;
    }

    uartBuffer->buffer[uartBuffer->head] = data;
    uartBuffer->head = (uartBuffer->head + 1) % BUFFER_SIZE;
}

int Buffer_Read(Buffer *uartBuffer, unsigned char *data) {
    if (!Buffer_IsEmpty(uartBuffer)) {
        *data = uartBuffer->buffer[uartBuffer->tail];
        uartBuffer->tail = (uartBuffer->tail + 1) % BUFFER_SIZE;
        return 1;
    }
    return 0;
}

void Start_Flag(Buffer *uartBuffer) {
    crc = DN_HDLC_CRCINIT;

    Buffer_Write(uartBuffer, DN_HDLC_FLAG);
}

void End_Flag(Buffer *uartBuffer) {
    Buffer_Write(uartBuffer, DN_HDLC_FLAG);
}

void Boot_Event(uint8_t Event, uint8_t Responseflags, uint8_t Rc_res, uint8_t Rc_len) {
    unsigned char data[4];
    unsigned short crc;

    data[0] = Event;
    data[1] = Rc_len;
    data[2] = Responseflags;
    data[3] = Rc_res;


    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);
    for (int i = 0; i < 4; i++) {
        Buffer_Write(&uartBuffer, data[i]);
    }

    crc = crc16_x25(data, sizeof(data));

    Buffer_Write(&uartBuffer, crc & 0xFF);
    Buffer_Write(&uartBuffer, (crc >> 8) & 0xFF);
    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);

}

void Packet_structure(uint8_t cmdId, uint8_t extraFlags, uint8_t *payload, uint8_t length) {
    unsigned char data[3 + length];
    unsigned short crc;

    data[0] = cmdId;
    data[1] = length;
    data[2] = extraFlags;
    memcpy(&data[3], payload, length);

    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);
    Buffer_Write(&uartBuffer, cmdId);
    Buffer_Write(&uartBuffer, length);
    Buffer_Write(&uartBuffer, extraFlags);
    for (int i = 0; i < length; i++) {
        Buffer_Write(&uartBuffer, payload[i]);
    }

    crc = crc16_x25(data, sizeof(data));

    Buffer_Write(&uartBuffer, crc & 0xFF);
    Buffer_Write(&uartBuffer, (crc >> 8) & 0xFF);
    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);

}

//void Command_packet (uint8_t cmd, uint8_t Flags, uint8_t len){
//
//	unsigned char data [2 + len];
//    unsigned short crc;
//
//    data[0] = cmd;
//    data[1] = len;
//    data[2] = Flags;
//    memcpy(&data[2], &len, sizeof(len));
//
//    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);
//    Buffer_Write(&uartBuffer, cmd);
//    Buffer_Write(&uartBuffer, len);
//    for (int i = 0; i < sizeof(len); i++) {
//    Buffer_Write(&uartBuffer, data[2 + i]);
//        }
//    Buffer_Write(&uartBuffer, Flags);
//
//    crc = crc16_x25(data, sizeof(data));
//    Buffer_Write(&uartBuffer, crc & 0xFF);
//	Buffer_Write(&uartBuffer, (crc >> 8) & 0xFF);
//    Buffer_Write(&uartBuffer, DN_HDLC_FLAG);
//}


unsigned short crc16_x25(const unsigned char* data, unsigned int length) {
    unsigned short crc = DN_HDLC_CRCINIT;
    for (unsigned int i = 0; i < length; i++) {
        crc ^= data[i];
        for (unsigned char j = 0; j < 8; j++) {
            if (crc & 1) {
                crc = (crc >> 1) ^ 0x8408;
            } else {
                crc >>= 1;
            }
        }
    }
    return ~crc;
}

//void VerifyCRC(Buffer *uartBuffer, unsigned int length) {
//    unsigned char data[length];
//    unsigned short receivedCrc, calculatedCrc;
//
//    for (unsigned int i = 0; i < length; i++) {
//        if (!Buffer_Read(uartBuffer, &data[i])) {
//            printf("Buffer read error!\n\r");
//            return;
//        }
//    }
//
//    if (!Buffer_Read(uartBuffer, (unsigned char*)&receivedCrc) || !Buffer_Read(uartBuffer, (unsigned char*)&receivedCrc + 1)) {
//        printf("CRC read error!\n\r");
//        return;
//    }
//
//    calculatedCrc = crc16_x25(data, length);
//
//    if (receivedCrc == calculatedCrc) {
//        printf("CRC valid!\n\r");
//    } else {
//        printf("CRC invalid. Expected 0x%04x but received 0x%04x\n", calculatedCrc, receivedCrc);
//    }
//}

//void VerifyCRC(Buffer *uartBuffer, unsigned int length) {
//    unsigned char data[length];
//    unsigned short receivedCrc, calculatedCrc;
//
//    for (unsigned int i = 0; i < length; i++) {
//        if (!Buffer_Read(uartBuffer, &data[i])) {
//            printf("Buffer read error! Resetting buffer.\n");
//            Buffer_Init(uartBuffer);
//            return;
//        }
//    }
//
//    if (!Buffer_Read(uartBuffer, (unsigned char*)&receivedCrc) || !Buffer_Read(uartBuffer, (unsigned char*)&receivedCrc + 1)) {
//        printf("CRC read error! Resetting buffer.\n");
//        Buffer_Init(uartBuffer);
//        return;
//    }
//
//    calculatedCrc = crc16_x25(data, length);
//
//    if (receivedCrc == calculatedCrc) {
//        printf("CRC valid!\n");
//    } else {
//        printf("CRC invalid. Expected 0x%04x but received 0x%04x\n", calculatedCrc, receivedCrc);
//    }
//}

void HDLCcheck(const unsigned char *original, unsigned int originalLength) {
    unsigned char modified[2 * originalLength];
    unsigned int newLength;
    unsigned int i, j;

    for (i = 0, j = 0; i < originalLength; i++) {
        if (original[i] == DN_HDLC_FLAG || original[i] == DN_HDLC_ESCAPE) {
            modified[j++] = DN_HDLC_ESCAPE;
            modified[j++] = original[i] ^ DN_HDLC_ESCAPE_MASK;
        } else {
            modified[j++] = original[i];
        }
    }
    newLength = j;

    for (i = 0; i < newLength; i++) {
        Buffer_Write(&uartBuffer, modified[i]);
    }
}

//void vMakePacket(uint8_t *payload, uint8_t *pucBuf, uint8_t flags, uint16_t length) {
//    uint16_t usCrc;
////    uint8_t i;
//
//    usCrc = crc16_x25(payload, length);
//
//    pucBuf[0] = DN_HDLC_FLAG;
//    memcpy(&pucBuf[1], payload, length);
//    pucBuf[length + 1] = (usCrc >> 8) & 0xFF;
//    pucBuf[length + 2] = usCrc & 0xFF;
//    pucBuf[length + 3] = DN_HDLC_FLAG;
//}

//void MakePacket(uint8_t cmdId, uint8_t *payload, uint8_t length, uint8_t flags, uint8_t *pucbuf){
//
//}

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


  //==============================BOOT====================================
  	  uint8_t Event = EVENTS;
  	  uint8_t Responseflags = 0x03;
  	  uint8_t Rc_res = DN_SERIAL_RC_OK;
  	  uint8_t Rc_len = 0x00;
  //===========================CMD_Packet=================================

//  	  uint8_t cmd = JOIN;
//	  uint8_t Flags = 0x04;
//	  uint8_t len = sizeof(len);

  //======================================================================

  //=========================Packet Structure=============================
  	  uint8_t cmdId = GETPARAMETER;
  	  uint8_t extraFlags = 0x02;
  	  uint8_t payload[] = {MOTEINFO};
  	  uint8_t length = sizeof(payload);
  //======================================================================

//  	  Buffer pucBuffer;
  	  Buffer_Init(&uartBuffer);
  	  uint8_t packetBuf[512];
  	  unsigned char data;

  	while(GPIO_PIN_RESET == HAL_GPIO_ReadPin(GPIOA, Mote_Rts_Pin));
  		  	  HAL_Delay(10);
  		  HAL_GPIO_WritePin(Mote_Cts_GPIO_Port, Mote_Cts_Pin, GPIO_PIN_RESET);
  		  	  HAL_Delay(50);

  //======================================================================
  	  Boot_Event(Event, Responseflags, Rc_res, Rc_len);

//  	  VerifyCRC(&uartBuffer, 4 + 2);
  //======================================================================

//  	  Command_packet(cmd, Flags, len);

  //======================================================================
  	  Packet_structure(cmdId, extraFlags, payload, length);

//  	  VerifyCRC(&uartBuffer, 3 + length + 2);
  //======================================================================
  	  printf("Buffer Data: ");
  	  while(Buffer_Read(&uartBuffer, &data)) {
  	  printf("0x%02X ", data);
  	  }
  	  	printf("\n");

//  	  vMakePacket(payload, packetBuf, extraFlags, length);


//  	  printf("Packet data: ");
//  	  for (unsigned int i = 0; i < length + 4; i++) {
//  	   printf("0x%02X ", packetBuf[i]);
//  	  }
//  	  printf("\n\r");
//

  //======================================================================



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

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** 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_MUL6;
  RCC_OscInitStruct.PLL.PLLDIV = RCC_PLL_DIV3;
  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_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

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

/**
  * @brief USART1 Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  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();
  }
  /* USER CODE BEGIN USART1_Init 2 */
  __HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
  HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* USER CODE END USART1_Init 2 */

}

/**
  * @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 = 115200;
  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;
  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};
/* 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_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LD2_Pin|Mote_Cts_Pin, GPIO_PIN_RESET);

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

  /*Configure GPIO pins : LD2_Pin Mote_Cts_Pin */
  GPIO_InitStruct.Pin = LD2_Pin|Mote_Cts_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : Mote_Rts_Pin */
  GPIO_InitStruct.Pin = Mote_Rts_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Mote_Rts_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 */

 

3 REPLIES 3
Techn
Senior III

The simplest method is to enable the interrupt by using the CubeMX and call activate the interrupt by using the HAL function as follows

HAL_UART_Receive_IT(&huart, pData, Size)

in the interrupt call back i.e void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)

you can do what ever with the received character or characters. But avoid any long operations, then re-enable the interrupt by calling HAL_UART_Receive_IT(&huart, pData, Size)

 

If you feel a post has answered your question, please click "Accept as Solution".

친절한 답변에 감사드립니다. 이것이 유일한 방법입니까?

Karl Yamashita
Lead III

You have zero code that receives UART data or read the data register..

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.