1
\$\begingroup\$

I have an STM32F303K8T6 uC and I'm using the UART to transfer data to a PC. Now, when I unplug the Serial Interface while running, the whole program run into an error. How can I check in HAL, if the UART is available?

For Transmission I use the following function:

HAL_UART_Transmit_DMA(usart1, str,size);

Edit: I have here now the code for the UART1. The RxCallback function is never called, since it always runs into a Overrun error:

if(((isrflags & USART_ISR_ORE) != RESET) &&
       (((cr1its & USART_CR1_RXNEIE) != RESET) || ((cr3its & USART_CR3_EIE) != RESET)))
    {
      __HAL_UART_CLEAR_IT(huart, UART_CLEAR_OREF);

      huart->ErrorCode |= HAL_UART_ERROR_ORE;
    }

Now here is the code of the initialization of the UART for RX:

main.c:

   /* Includes ------------------------------------------------------------------*/
    #include "main.h"
#include "stm32f3xx_hal.h"

/* USER CODE BEGIN Includes */
    #include "USART.h"
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_tx;
char rx_buff[BUFFSIZE_RX];
char rx_data[BUFFSIZE_RX];
/* USER CODE BEGIN PV */
    /* Private variables ---------------------------------------------------------*/

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART1_UART_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

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_DMA_Init();
  MX_USART1_UART_Init();

  /* USER CODE BEGIN 2 */
    //UART
    init_usart(&huart1);
    //HAL_UART_Receive_IT(&huart1, (uint8_t *)buff_rx, USART_BUFFER_SIZE);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
      while (1)
      {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

      }
  /* USER CODE END 3 */

}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  RCC_PeriphCLKInitTypeDef PeriphClkInit;

    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  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_0) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Configure the Systick interrupt time 
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick 
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/* USART1 init function */
static void MX_USART1_UART_Init(void)
{

  huart1.Instance = USART1;
  huart1.Init.BaudRate = 57600;
  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;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

}

/** 
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void) 
{
  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Channel4_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel4_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel4_IRQn);

}

/** Pinout Configuration
*/
static void MX_GPIO_Init(void)
{

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

}

/* USER CODE BEGIN 4 */
    ///////////////////////CALLBACK//////////////////////////////////////////////////////////////////////////////////
    void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {

    }


    void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {

    }

    ///////////////////////END_CALLBACK//////////////////////////////////////////////////////////////////////////////


/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void _Error_Handler(char * file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    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

/**
  * @}
  */ 

/**
  * @}
*/ 

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

UART.c:

#include <USART.h>
#include "stdlib.h"

extern rx_buff[BUFFSIZE_RX];
extern rx_data[BUFFSIZE_RX];

/*
 * Variables to adjust via USART RX
 */
char *key;
char *s1;
char *s2;

uint8_t buff[36];

float val;
//////////////////////////////////////////////////

//////////////////////////////////////////////////

void init_usart(UART_HandleTypeDef *u) {
    usart_handler=u;
    __HAL_UART_ENABLE_IT(usart_handler,UART_IT_RXNE);
    //HAL_UART_Receive_DMA(u, &rx_data, BUFFSIZE_RX);

}

void usart_tx(UART_HandleTypeDef *usart1, uint16_t bufferSize, char *str) {
    int size=0;
    char *p_str=str;
    for(uint16_t i=0;i<bufferSize;i++) {
        if(*p_str) {
            size++;
            p_str++;
        } else {
            break;
        }
    }

    HAL_UART_Transmit_DMA(usart1, str,size);
}

void clearBuffer(char *buff, int size) {
    for(int i=0;i<size;i++) {
        buff[i]='\0';
    }
}

void copyValuesToBuff() {
    sprintf(rx_buff,"%s\n",rx_data);
    setCommand();
}

void setCommand() {
    val=0;

    key = strtok(rx_buff, "=.");
    s1 = strtok(NULL, "=.");
    s2 = strtok(NULL,"=.");

    if(strcmp(s1,"")==0 || strcmp(s2,"")==0) {

    } else {
        sprintf(buff,"%s.%s",(char*)s1,(char*)s2); //only works if x.y, only x alone does not work!!!!
        val=strtof(buff,NULL);
    }
}

int strcmp(const char *s1, const char *s2)
{
    const unsigned char *c1 = (const unsigned char *)s1;
    const unsigned char *c2 = (const unsigned char *)s2;
    unsigned char ch;
    int d = 0;

    while (1) {
        d = (int)(ch = *c1++) - (int)*c2++;
        if (d || !ch)
            break;
    }

    return d;
}

Edit: How exactly can I see if an rx interrupt or a tx interrupt happened and how can I decide if it happened only because rx is floating? I tried the following, but it only works if the cable is connected:

void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */
    uint8_t isRx = 0;
    uint32_t it_rx=0;
    uint32_t it_tx=0;

    it_rx=USART1->ISR & UART_IT_RXNE;
    it_tx=USART1->ISR & UART_IT_TXE;

    if (it_tx!=0) {
        isRx=1;
    } else {
        isRx=0;
    }

    /* USER CODE END USART1_IRQn 0 */
    HAL_UART_IRQHandler(&huart1);
    /* USER CODE BEGIN USART1_IRQn 1 */
    if(isRx) {
        uint8_t rbyte = huart1.Instance->RDR;
        __HAL_UART_SEND_REQ(&huart1, UART_RXDATA_FLUSH_REQUEST);
        rx_data[pointer]=rbyte;
        if(rx_data[pointer]=='$') {
              rx_data[pointer]='\0';
              pointer=0;
              copyValuesToBuff();
              clearBuffer(&rx_data,BUFFSIZE_RX);
        } else {
          pointer++;
          if(pointer>=BUFFSIZE_RX) {
              pointer=0;
          }
        }
        __HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE);
    }


  /* USER CODE END USART1_IRQn 1 */
}
\$\endgroup\$
2
  • \$\begingroup\$ HAL UART 'crash', or just an Overrun error? What is the actual error you are getting? \$\endgroup\$ Commented Oct 7, 2017 at 17:53
  • \$\begingroup\$ The overrun seems only to happen when I send a string with more than one character over the uart. When I send only one string, it has returns as busy in the UART_Receive_IT() function. So it never reaches the callback. \$\endgroup\$ Commented Oct 7, 2017 at 18:40

1 Answer 1

-1
\$\begingroup\$

UART is always avaiable as it is the part of your micro. When you transmit - there is no way to check if something is connected or not. You can only reconfigure the Rx pin to GPIO analog and check if the pin is floating. If yes the device has been disconnected.

If you only unplug the USB cable - that depends on your converter - if it gives any option to read the status and check the errors.

BTW your program should not crash. You have probably another problem there and it has unveiled when you disconnect the device. Show us your code.

\$\endgroup\$
3
  • \$\begingroup\$ I really don't get, why the RxCallback function never is called when I send a character. The interrupt is correctly called and I could also read the value from the DR register, but when the UART_Receive_IT is called (only when I send exactly one character), then huart->RxState == HAL_UART_STATE_BUSY_RX is never satisfied (RxState is HAL_UART_READY) \$\endgroup\$ Commented Oct 7, 2017 at 13:47
  • \$\begingroup\$ I do not use this bloattware. I do only the bare register programming. \$\endgroup\$ Commented Oct 7, 2017 at 14:14
  • \$\begingroup\$ This is not an answer. this is a comment \$\endgroup\$ Commented Apr 19, 2019 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.