本帖最后由 xzyswr 于 2024-5-14 09:16 编辑
先贴个测试效果图
double不一致是默认%f只保留6位,要完全一直使用%.7f
测试输出用的代码
[C] 纯文本查看 复制代码
// 输出系统信息
debug << "系统时钟频率:" << HAL_RCC_GetSysClockFreq() / 1000000 << "MHz" << endl;
debug << "APB1总线时钟频率:" << HAL_RCC_GetPCLK1Freq() / 1000000 << "MHz" << endl;
debug << "APB2总线时钟频率:" << HAL_RCC_GetPCLK2Freq() / 1000000 << "MHz" << endl;
debug << "外设时钟频率:" << HAL_RCC_GetHCLKFreq() / 1000000 << "MHz" << endl;
bool bool_test = true;
char char_test[] = "Hello, World!";
int int_test = 123;
float float_test = 3.14;
double double_test = 3.1415926;
uint8_t uint8_test = 0xFF;
uint16_t uint16_test = 0xFFFF;
uint32_t uint32_test = 0xFFFFFFFF;
debug << bool_test << endl;
debug << char_test << endl;
debug << int_test << endl;
debug << float_test << endl;
debug << double_test << endl;
debug << uint8_test << endl;
debug << uint16_test << endl;
debug << uint32_test << endl;
debug.toHex(uint8_test) << endl;
debug.toHex(uint16_test) << endl;
debug.toHex(uint32_test) << endl;
debug.toHex(uint32_t(100)) << endl;
搞这个的原因是觉得C语言的封装写起来总觉得不是很优美,C++用起来感觉不错,但有些功能吃flash空间
重点:封装思路
首先看使用效果
1.先封装一个bsp函数
[C] 纯文本查看 复制代码 void bsp_uart2_send(uint8_t *buf, uint16_t len)
{
HAL_UART_Transmit(&huart2, buf, len, HAL_MAX_DELAY);
}
2.创建串口对象,并将函数指针传递给构造函数
[C] 纯文本查看 复制代码 Serial debug(bsp_uart2_send);
3.然后直接用就完事了,
[C] 纯文本查看 复制代码 debug << "Hello";
原理:
在Serial类里面定义了一个(*send)函数指针,初始化构造函数时将(*send)指针指向实际的发送函数
这样类里面就没有和底层硬件耦合的代码了
补充分享:
/*某些编译器或环境(特别是嵌入式系统)默认不支持浮点数的格式化。这是因为浮点数的支持会显著增加编译后的程序大小*/
/*GCC或者Clang 添加 -u_printf_float 选项来支持浮点数的格式化输出*/
开启后
Memory region Used Size Region Size %age Used
RAM: 2216 B 160 KB 1.35%
RAM2: 0 GB 32 KB 0.00%
FLASH: 33216 B 512 KB 6.34%
未开启
Memory region Used Size Region Size %age Used
RAM: 1848 B 160 KB 1.13%
RAM2: 0 GB 32 KB 0.00%
FLASH: 21000 B 512 KB 4.01%
|