This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Dynamic memory allocation and UART

Former Member
Former Member

Hi friends, I came across a problem with my UART communication.My codes are below.

if I use

rx_buffer = (uint8_t*)calloc(3,sizeof(uint8_t));
HAL_UART_Receive_IT(&huart1,&rx_data,1);  and rx_buffer = (uint8_t*)realloc(rx_buffer,sizeof(uint8_t));

program works , but if I use these codes

rx_buffer = (uint8_t*)calloc(10,sizeof(uint8_t));
HAL_UART_Receive_IT(&huart1,&rx_data,1);  and rx_buffer = (uint8_t*)realloc(rx_buffer,sizeof(uint8_t));

it doesn't work,I changed 10 instead of 3 in calloc. As much as I remembered stm32f103 stop to work after the first sending data.probably hardfault.I couldn't debug because of limited USB input.




#include "main.h"
#include "stm32f1xx_hal.h"
#include "usart.h"
#include "gpio.h"
#include "stdlib.h"

void SystemClock_Config(void);
static void MX_NVIC_Init(void);
void Clear_Buffer(void);

uint8_t rx_data=0;
uint8_t *rx_buffer;
uint8_t rx_index=0;
uint8_t dataReady=0;
uint8_t length=0;


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

MX_GPIO_Init();
MX_USART1_UART_Init();
MX_USART2_UART_Init();

MX_NVIC_Init();


rx_buffer = (uint8_t*)calloc(3,sizeof(uint8_t));
HAL_UART_Receive_IT(&huart1,&rx_data,1);


while (1)
{
Clear_Buffer();

}

}
//****************************************************************************//
void Clear_Buffer(void)
{
if(dataReady)
{
dataReady = 0;
for(int i=0;i<length;i++) rx_buffer[i] = NULL;
free(rx_buffer);
rx_buffer = (uint8_t*)calloc(3,sizeof(uint8_t));
}
}
//Bu interrupt fonksiyonuna ait prototip zaten oldugundan ayrica tanimlamaya gerek yoktur
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1)
{
HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13);

if(rx_data != 13)
{
rx_buffer[rx_index++] = rx_data;
rx_buffer = (uint8_t*)realloc(rx_buffer,sizeof(uint8_t));
}

else
{
length = strlen(rx_buffer);
//Gönder
HAL_UART_Transmit(&huart1,rx_buffer,length,1000);

dataReady = 1;
rx_index = 0;


}


HAL_UART_Receive_IT(&huart1,&rx_data,1);
}
}