On [STM32](https://www.ampheo.com/search/STM32) you can print floats with printf("%.2f"), but two things must be set up: 1. printf must be routed somewhere (UART/SWO/etc.) 2. float-formatting must be enabled in the C library (often off by default to save flash) 3. ![hq720 (48)](https://hackmd.io/_uploads/SyLiybgm-g.jpg) **1) Retarget printf to UART (HAL, STM32CubeIDE / GCC)** Add this to e.g. main.c (or a separate retarget.c). Replace huart2 with your UART handle. ``` #include "usart.h" #include <unistd.h> int _write(int file, char *ptr, int len) { HAL_UART_Transmit(&huart2, (uint8_t*)ptr, len, HAL_MAX_DELAY); return len; } ``` Now printf("Hello\r\n"); goes out over UART. **2) Enable float support in printf** If you use newlib-nano (common in STM32CubeIDE), float printing is usually disabled. **In STM32CubeIDE** **Project Properties → C/C++ Build → Settings → MCU GCC Linker → Miscellaneous → Linker flags** Add: -u _printf_float (If you also need float with scanf, add -u _scanf_float.) Rebuild. **3) Print a float** ``` float v = 3.14159f; printf("v = %.3f\r\n", v); ``` Note: in printf, float is promoted to double automatically, so %f is correct. **Precautions (important)** * Flash size cost: enabling float printf can add several KB (sometimes more). If you’re tight on flash, consider fixed-point printing instead. * Speed: float formatting is relatively slow; prefer snprintf into a buffer and send it, or print less often. **Fixed-point alternative (small + fast)** ``` int32_t mv = 3300; // millivolts printf("%ld.%03ld V\r\n", mv/1000, mv%1000); ```