HAL 库使用printf函数
#include "main.h"
#include "adc.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart3,(uint8_t *)&ch,1,0xFFFF);//??????
return ch;
}
/* 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 ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
float votagle=3.125;
char ab[5]="test";
/* 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_ADC_Init();
MX_USART3_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
int i;
printf("hello world\r\n");
for(i=0;i<4;i++)
{
printf("%c",ab[i]);
}
printf("\n");
printf("%s\r\n",ab);
printf("%f\r\n",votagle);
HAL_Delay(500);
}
/* USER CODE END 3 */
}
想使用printf,首先要以下代码。其实&huart3是我刚好要使用的串口,可根据自己需求修改
#include "stdio.h"
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart3,(uint8_t *)&ch,1,0xFFFF);//??????
return ch;
}
然后我主函数中分别通过USART3输出字符串和浮点型
int i;
printf("hello world\r\n");
for(i=0;i<4;i++)
{
printf("%c",ab[i]);
}
printf("\n");
printf("%s\r\n",ab);
printf("%f\r\n",votagle);
HAL_Delay(500);
输出结果如下
printf各种类型输出控制符如下
%d 输出整数
%ld 长整型
%u 输出无符号类型,输出无符号类型时也可以用%d
%c 输出一个字符
%s 输出字符串
%f 输出实数(小数点后6位,超过的四舍五入)