6

stc 51 单片机使用 printf,方便、灵活的发送信息到串口

 3 years ago
source link: https://blog.popkx.com/stc-51-mcu-use-printf-function-to-send-messages-to-uart-convinietly/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

stc 51 单片机使用 printf,方便、灵活的发送信息到串口

发表于 2018-08-12 21:08:26   |   已被 访问: 825 次   |   分类于:   单片机   |   暂无评论

51 单片机一般很少专门带有可以方便输出信息的屏幕。有时候拿到一块最小系统的单片机,甚至连指示灯都没有,这时候如果想知道其输出是否符合预期,串口是一个非常不错的选择。

在 stm32 单片机上开发时,使用过 c 语言标准库里的 printf 函数,很方便就可以把想要展示的包括字符串、数字等信息输出到串口,这样,在电脑上就可以判断输出是否符合预期。今天突发奇想,想试试 51单片机 是否可以使用 printf 函数,结果还真实现了,只不过数字需要小小的转换。

以下是小 demo


\#include "reg51.h" #include "stdio.h" #define FOSC 11059200L #define BAUD 9600 void InitUart() { SCON = 0x5a; TMOD = 0x20; TH1 = TL1 = -(FOSC/12/32/BAUD); TR1 = 1; ES = 1; EA = 1; } void main() { InitUart(); printf("hello world, num: %d\n", (int)98); while(1); }

代码很简单,把串口配置一下,包含一下"stdio.h"就可以使用printf函数了。不过,貌似我使用的这款单片机会把 printf 函数参数里的%d识别为字符,所以使用 (int)强制类型转换了一下。

编译,下载到单片机里,在电脑端打开串口调试助手,发现成功了,输出符合预期。

阅读更多:   单片机


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK