I'm programming an STM32 microcontroller. In the code I'm just calling sprintf the way I did before and it worked then, but now it just freezes the entire program. What's the problem here?
char str[100];
sprintf(str, "TEMP_ADC: %d\n", 50);
I've included stdlib.h, stdio.h, math.h and string.h. The 100 char limit is more than enough.
I tried lighting LEDS above and below the sprintf() call and it's clear the program gets stuck on the sprintf(). I tried switching to snprintf() but it resulted in the same behaviour.
EDIT:
I noticed that sprintf() works when I use it before starting the DMA. If I use it after, the program freezes. Could it have something to do with casting an uint16_t array to uint32_t?
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 */
uint16_t values[4];
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* Configure the peripherals common clocks */
PeriphCommonClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_TIM2_Init();
MX_TIM16_Init();
MX_MEMORYMAP_Init();
MX_LPUART1_UART_Init();
MX_RF_Init();
/* USER CODE BEGIN 2 */
char str[100];
sprintf(str, "TEMP_ADC: %d\n", 50);
int size = (int)((ceil(log10(50))+1+11)*sizeof(char));
HAL_UART_Transmit(&hlpuart1, str, size, 100);
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, SET);
HAL_ADC_Start_DMA(&hadc1, (uint32_t *)values, 4);
uint16_t temp = 0;
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
HAL_Delay(1000);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
sprintfis pretty heavyweight for a string that easily could be formatted manually. The exact fragment shown could be more simply achieved withchar str[100] = "TEMP_ADC: 50\n";. Or if the real circumstances don't permit using an initializer, thenstrcpy()would still be an improvement oversprintf()for this particular case.