51 MCU can also use the printf() function for debugging

I don’t know if friends who are just getting started with 51 single-chip microcomputers are the same as me. I don’t know whether the changes in the variable values ​​​​defined in the project are consistent with what I think. When we first learned C language, we could use the printf function to check the operation of the code. Today, I will introduce how to use the printf function of the C51 single-chip microcomputer to realize debugging.

Idea: display the print result on the serial port assistant.

The main function code is as follows:

#include <REGX51.H>
#include <delay.h>
#include <stdio.h>

void Uart_SendChar(unsigned char  dat)
{
    SBUF = dat; 
    while(!TI); 
    TI = 0; 
}

char putchar(char c)//重定向
{
    Uart_SendChar(c);
    return c;
}

void UART_init()    //设置串行通信 本晶振为11.0592MHZ,其他的就自己算一下应该设置多少
{
      TMOD = 0x20;
      TH1 = 0xfd;
      TL1 = 0xfd;  //波特率9600
      SM0 = 0;  
      SM1 = 1;   // 串口工作方式1 10位异步
      REN = 1;  //串口允许接收
      TR1 = 1;
      EA = 1;
      ES =1 ;  //串口中断
}
void main()
{
    UART_init();
    while(1)
    {
        printf("hello world");
        Delay(2000);
    }
}

Code analysis:

The serial port is initialized to realize the communication between the microcontroller and the PC.

void UART_init()    //设置串行通信 本晶振为11.0592MHZ
{
      TMOD = 0x20;
      TH1 = 0xfd;
      TL1 = 0xfd;  //波特率9600
      SM0 = 0;  
      SM1 = 1;   // 串口工作方式1 10位异步
      REN = 1;  //串口允许接收
      TR1 = 1;
      EA = 1;
      ES =1 ;  //串口中断
}

The header file <stdio.h> is used to use the printf() function.

The header file <delay.h> performs delay, and the code can be automatically generated in the generator, as shown in the figure below:

In C language, the putchar function can only output a single character, while the printf function can output multiple characters and various types of data; the printf() function calls the putchar() function when formatting output, in the header file stdio.h There are two functions in it, we need to modify the putchar function, use SBUF to receive the input data, and then it can be transmitted to the PC. The following two functions are implemented:

void Uart_SendChar(unsigned char  dat)
{
    SBUF = dat; 
    while(!TI); 
    TI = 0; 
}

char putchar(char c)//重定向
{
    Uart_SendChar(c);
    return c;
}

result:

Existing doubts:

For example, I want to send int m=15;printf("%d",m); At this time, m is an integer. Is the putchar function also used when formatting output? Can the types be different? After experimenting, data 15 can be printed.

If anyone knows, I look forward to your answer.

After mastering this method, we only need to use a serial debugger to print data and then debug the code.

If there is something wrong with the article, I look forward to your correction.

Guess you like

Origin blog.csdn.net/qq_62262788/article/details/128544555