目录
STM32F1串口重定义printf+数据类型的范围
1. 实验内容:
重定义printf,就是说在单片机上可以使用printf进行输出;
输出short、char、int、long long int、u8、u16、u32的字节和最大存储数据。
2. printf重定义:
寄存器、标准库、HAL库的重定义相同的。
通过对fputc函数实现对printf():函数的重定义
//Printf重定义
int fputc(int ch,FILE *f)
{
USART1_Send(ch); //串口发送字节
return(ch);
}
//printf重定义
int fputc(int ch,FILE *f)
{
USART1_Send(ch);
return(ch);
}
//主函数
int main(void)
{
USART1_Config(); //串口1配置115200
USART1_Sends((u8*)"USART1测试\r\n");
printf("USART Test\r\n");
printf("char = %d字节\r\n",sizeof(char));
printf("short = %d字节\r\n",sizeof(short));
printf("int = %d字节\r\n",sizeof(int));
printf("long int = %d字节\r\n",sizeof(long));
printf("long long int = %d字节\r\n",sizeof(long long));
printf("u8 = %d字节 %ud\r\n",sizeof(u8),(u8)-1);
printf("u16 = %d字节 %ud\r\n",sizeof(u16),(u16)-1);
printf("u32 = %d字节 %ud\r\n",sizeof(u32),(u32)-1);
printf("(unsigned long) = %d字节 %lud\r\n",sizeof(unsigned long),(unsigned long)-1);
printf("unsigned long long = %d字节 %llud\r\n",sizeof(long long),(long long)-1);
while (1)
{
}
}
3. printf输出数据类型的字节和存储最大值:
如上程序源码可知,
printf("char = %d字节\r\n",sizeof(char)); //输出char类型占用的字节
printf("short = %d字节\r\n",sizeof(short)); //输出short类型占用的字节
printf("int = %d字节\r\n",sizeof(int)); //输出int类型占用的字节
printf("long int = %d字节\r\n",sizeof(long)); //输出long int类型占用的字节
printf("long long int = %d字节\r\n",sizeof(long long)); //输出long long int类型占用的字节
printf("u8 = %d字节 %ud\r\n",sizeof(u8),(u8)-1); //输出u8类型最大存储的值
printf("u16 = %d字节 %ud\r\n",sizeof(u16),(u16)-1); //输出u16类型最大存储的值
printf("u32 = %d字节 %ud\r\n",sizeof(u32),(u32)-1); //输出u32类型最大存储的值
//输出unsigned long类型最大存储的值
printf("(unsigned long) = %d字节 %lud\r\n",sizeof(unsigned long),(unsigned long)-1);
//输出unsigned long long类型最大存储的值
printf("unsigned long long = %d字节 %llud\r\n",sizeof(long long),(long long)-1);
4. 实验结果:
串口会输出对应的定义类型的大小和最大值。