简单的C语言宏定义,结合全局变量,实现单片机串口,实现透明传输方式

时间:2024-10-23

什么是透明传输?根据百度百客给出的定义: & nbsp; & nbsp;  透明传输,即透明传输(直通),这意味着无论在通信中传输的业务内容如何,​​它仅负责从源传输内容。

目标地址,而无需更改业务数据的内容。

& nbsp; & nbsp; & nbsp;在实际的MCU产品开发过程中,如果有多个串行端口,则在调试和打印某些模块信息时,大多数人的方法是引出所有模块的TX,RX和GND。

分别连接到不同的调试端口,并通过PC终端分别打印出信息。

这样做将不可避免地会犯错误,而且非常麻烦。

如果意外连接,将导致模块烧坏。

& nbsp; & nbsp; & nbsp;因此,透明传输模式的出现就是为了解决这个问题,即在程序中指定使用串行端口,连接其他模块的串行端口,然后这个指定的串行端口可以输出这些甚至模块的串行端口信息,我们都可以通过PC上串行模块的TX线将命令发送到下位机,并根据该命令指定输出哪个模块串行端口。

这样既方便又快捷,对分析问题和避免实际发展也很有帮助。

繁琐和误操作。

& nbsp; & nbsp; & nbsp;接下来,让我们看一下实现逻辑://条件标记,要打印的内容是根据条件标记确定的。

int debug_condition = 0; #define& nbsp; GENERAL_DEBUG& nbsp; 0 #define& nbsp; MODULE1& nbsp; & nbsp; & nbsp; 1 #define& nbsp; MODULE2& nbsp; & nbsp; & nbsp; & nbsp; 2& nbsp; #define DEBUG(cond,...)if(cond == GENERAL_DEBUG)printf(__ VA_ARGS__)  #define Module1_Debug(cond,...)if(cond == GENERAL_DEBUG || cond == MODULE1)printf(__ VA_ARGS__)  #define Module2_Debug(cond,...)if(cond == GENERAL_DEBUG || cond == MODULE2)printf(__ VA_ARGS__)  GENERAL_DEBUG用作正常输出的标志。

当全局变量debug_condition是此符号时,DEBUG宏有效。

MODULE1用作模块1输出的标志。

当不需要干扰其他调试信息并且仅需要模块1输出时,Module1_Debug宏有效,而其他无效。

MODULE2也是如此。

使用标准C语言模拟此过程:#include& lt; stdio.h& gt; & nbsp; //条件标记,根据条件标记确定要打印的内容int debug_condition = 0; #define& nbsp; GENERAL_DEBUG& nbsp; 0 #define& nbsp; MODULE1& nbsp; & nbsp; & nbsp; 1 #define& nbsp; MODULE2& nbsp; & nbsp; & nbsp; & nbsp; 2& nbsp; #define DEBUG(cond,...)if(cond == GENERAL_DEBUG)printf(__ VA_ARGS__)  #define Module1_Debug(cond,...)if(cond == GENERAL_DEBUG || cond == MODULE1)printf(__ VA_ARGS__)& nbsp; #define Module2_Debug(cond,...)if(cond == GENERAL_DEBUG || cond == MODULE2)printf(__ VA_ARGS__)  & nbsp; int main(void){int cmd = 0; start:printf("请输入命令: ”); scanf(“%d”,& cmd); //将输入命令转发到全局变量debug_condition = cmd; switch(debug_condition){case GENERAL_DEBUG:DEBUG(debug_condition,“ jeadlaksl; dkl; ak ”); Module1_Debug(debug_condition,“ Hello world%d%d%d%d ,, 1,2,3,4); Module2_Debug(debug_condition,“ Hello%d ",1);休息;案例MODULE1:DEBUG(debug_condition,“ jeadlaksl; dkl; ak ”); Module1_Debug(debug_condition,“ Hello world%d%d%d%d ,, 1,2,3,4); Module2_Debug(debug_condition,“ Hello%d ",1);休息; & nbsp;案例MODULE2:DEBUG(debug_condition,“ jeadlaksl; dkl; ak ”); Module1_Debug(debug_condition,“ Hello world%d%d%d%d ,, 1,2,3,4); Module2_Debug(debug_condition,“ Hello%d ",1);休息;默认值:printf("命令输入错误! ”);转到开始break;& nbsp;}返回0; }& nbsp;操作结果:输入0、1、2以外的数字时无效,当输入为1时,将打印模块1的调试信息。

当输入为2点钟时,仅打印模块2的调试信息。

当输入为0时,有一种实现方法可以打印所有调试信息。

当然,在单片机上实现它并不难。

甚至其他平台也可以以此方式使用。

达到。