Functions of single-chip microcomputer C language C51

Publisher:未来感觉Latest update time:2021-07-08 Source: eefocusKeywords:MCU Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

Function


1. Function definition


The general format of a function definition is as follows:


Function type Function name (formal parameter list) [reentrant][interrupt m][using n]


Formal parameter description


{

Local variable definition


Function body


}


The first part is called the header of the function, and the second part is called the tail of the function. The format is as follows:


1) Function type


The function type describes the type of value returned by the function.


2) Function name


The function name is the name that the user gives to the custom function for use when calling the function.


3). Formal parameter table


The formal parameter table is used to list the formal parameters for data transfer between the calling function and the called function.


[Example] Define a function max() that returns the maximum value of two integers.


int max(int ​​x,int y)


{ int z;


z=x>y?x:y;


return (z);


}


It can also be used like this:


int max(x,y)


int x,y;


{ int z;


z=x>y?x:y;


return (z);


}


4) The reentrant modifier


This modifier is used to define a function as a reentrant function. A reentrant function is a function that allows recursive calls. A recursive call of a function means that when a function is being called and has not yet returned, it directly or indirectly calls itself. Ordinary functions cannot do this, only reentrant functions allow recursive calls.


Regarding reentrant functions, note the following:


(1) When a reentrant function modified with reentrant is called, bit type parameters are not allowed in the actual parameter list. Any operations on bit variables are not allowed in the function body, and bit type values ​​cannot be returned.


(2) During compilation, the system creates a simulated stack area in the internal or external memory for the reentrant function, called the reentrant stack. The local variables and parameters of the reentrant function are placed in the reentrant stack, so that the reentrant function can be called recursively.


(3) In terms of parameter passing, actual parameters can be passed to the indirectly called reentrant function. Indirectly called functions without reentrant attributes cannot contain call parameters, but defined global variables can be used for parameter passing.


5). interrupt m modifier


Interrupt m is a very important modifier in C51 functions, because interrupt functions must be modified by it. In C51 programming, when the interrupt m modifier is used in function definition, the system converts the corresponding function into an interrupt function during compilation, automatically adds the program header and tail segments, and automatically arranges it in the corresponding position in the program memory according to the 51 system interrupt processing method.


In this modifier, the value of m is 0~31, and the corresponding interrupt conditions are as follows:


0——External interrupt 0


1——Timer/Counter T0


2——External interrupt 1


3——Timer/Counter T1


4——Serial port interrupt


5——Timer/Counter T2


Other values ​​are reserved.


When writing 51 interrupt function, please note the following:


(1) Interrupt functions cannot pass parameters. If an interrupt function contains any parameter declaration, a compilation error will occur.


(2) The interrupt function has no return value. If you attempt to define a return value, you will not get the correct result. It is recommended to define the interrupt function as a void type to clearly indicate that there is no return value.


(3) In any case, the interrupt function cannot be called directly, otherwise a compilation error will occur. This is because the return of the interrupt function is completed by the RETI instruction of the 8051 microcontroller, and the RETI instruction affects the hardware interrupt system of the 8051 microcontroller. If the interrupt function is called directly without an actual interrupt, the operation result of the RETI instruction will produce a fatal error.


(4) If other functions are called in an interrupt function, the registers used by the called function must be the same as those used by the interrupt function. Otherwise, incorrect results will be generated.


(5) When the C51 compiler compiles an interrupt function, it will automatically add the corresponding content at the beginning and end of the program. Specifically, ACC, B, DPH, DPL, and PSW are pushed onto the stack at the beginning of the program and popped off at the end. If the interrupt function does not have the using n modifier, R0~R1 will also be pushed onto the stack at the beginning and popped off at the end. If the interrupt function has the using n modifier, the working register group select bit in PSW will also be modified after PSW is pushed onto the stack at the beginning.


(6) The C51 compiler generates an interrupt vector from the absolute address 8m+3, where m is the interrupt number, which is the number after interrupt. The vector contains an absolute jump to the entry address of the interrupt function.


(7) The interrupt function is best written at the end of the file, and the use of extern storage type declaration is prohibited to prevent other programs from calling it.


[Example] Write an interrupt service program to count the number of interrupts of external interrupt 0


extern int x;


void int0() interrupt 0 using 1


{

  x++;


}


6) Using n modifier


The modifier using n is used to specify the working register group used inside this function, where n is a value from 0 to 3, indicating the register group number.


When using the using n modifier, note the following points:


(1) After adding using n, C51 automatically adds the following instructions at the beginning and end of the function during compilation.


{

PUSH PSW ; push the flag register onto the stack


MOV PSW, #Constant associated with register group number



POP PSW ; Pop the flag register from the stack


}


(2) The using n modifier cannot be used for functions that return values, because the return value of a C51 function is stored in a register. If the register set is changed, the return value will be incorrect.


 


 


 


2. Function calling and declaration


1. Function call


The general form of a function call is as follows:


           function name(argument list);


For a function call with parameters, if the argument list contains multiple arguments, each argument is separated by a comma.


According to the position of the function call in the calling function, there are three types of function calls:


(1) Function statement: A statement that treats the called function as the main calling function.


(2) Function expression. A function is placed in an expression and appears as an operand. In this case, the called function is required to have a return statement to return a clear value to participate in the expression operation.


(3) Function parameters. The called function is used as a parameter of another function.


2. Declaration of custom functions


In C51, the general form of a function prototype is as follows:


       [extern] function type function name (formal parameter list);


The function declaration tells the compiler the function name, function type, and the type, number, and order of its parameters so that the system can check them when the function is called. A semicolon is added after the function declaration.


If the declared function is inside a file, then extern is not used in the declaration. If the declared function is not inside a file but in another file, then extern must be used in the declaration to indicate that the function to be used is in another file.


【Example】Use of function


#include //Includes special function register library


#include //Include I/O function library


int max(int ​​x,int y); //declare the max function


void main(void) //main function


{

int a,b;


SCON=0x52; //Serial port initialization


TMOD=0x20;


TH1=0XF3;


TR1=1;


scanf("please input a,b:%d,%d",&a,&b);


printf("n");


printf("max is:%dn",max(a,b));


while(1);


}


int max(int ​​x,int y)


{ int z;


z=(x>=y?x:y);


return(z);


}


[Example 24] Use of external functions


Program serial_initial.c


#include //Includes special function register library


#include //Include I/O function library


void serial_initial(void) //main function


{

SCON=0x52; //Serial port initialization


TMOD=0x20;


TH1=0XF3;


TR1=1;


}


Program y1.c


#include //Includes special function register library


#include //Include I/O function library


extern serial_initial();


void main(void)


{

int a,b;


serial_initial();


scanf("please input a,b:%d,%d",&a,&b);


printf("n");


printf("max is:%dn",a>=b?a:b);


while(1);


}


3. Nested and recursive functions


1. Nesting of functions


In the process of calling a function, another function is called. The C51 compiler usually relies on the stack to pass parameters. The stack is set in the on-chip RAM, and the space of the on-chip RAM is limited, so the nesting depth is relatively limited, generally within a few layers. If there are too many layers, it will lead to insufficient stack space and errors.  


【Example】 Nested function calls


#include //Includes special function register library


#include //Include I/O function library


extern serial_initial();


int max(int ​​a,int b)


{

int z;


z=a>=b?a:b;


return(z);


}


int add(int c,int d,int e,int f)


{

int result;


result=max(c,d)+max(e,f); //Call function max


return(result);


}


main()


{

int final;


serial_initial();


final=add(7,5,2,8);


printf("%d",final);


while(1);


}


2. Recursion of functions


Recursive calling is a special case of nested calling. If a function is called directly or indirectly, it is called a recursive calling of the function.


In the recursive calling of a function, it is necessary to avoid endless self-calling. The recursive calling should be ended through conditional control to limit the number of recursions.


The following is an example of using recursive calls to find n!.


【Example】Recursively find the factorial of a number n!.


In mathematical calculations, the factorial of a number n is equal to the number itself multiplied by the factorial of the number n-1, that is, n!=n´(n-1)!. Using the factorial of n-1 to represent the factorial of n is a recursive representation method. In programming, this is achieved through recursive function calls.

[1] [2]
Keywords:MCU Reference address:Functions of single-chip microcomputer C language C51

Previous article:Single chip microcomputer C language C51 structure data type
Next article:C language C51 statements for single chip microcomputers

Recommended ReadingLatest update time:2024-11-16 11:40

Learning C51 Basics 10 "Union"
Union     1. Union declaration and union variable definition     Union is also a new data type, which is a special form of variable.     Union declaration and union variable definition are very similar to structures. Its form is:      union union name {           data type member name;           data type member
[Microcontroller]
AVR Lesson 11: How to treat our microcontroller
After learning MCS51 MCU, AVR MCU, PIC MCU, or MSP430 MCU, do you feel that you can become an engineer? Let me share my opinion here. When we learn these single-chip microcomputers, we first learn theoretical knowledge, which is generally theoretical knowledge from books, such as the introduction of the development
[Microcontroller]
Regulatory considerations for MCUs in robots
Robots have unique demands on MCUs. MCUs optimized for robotics often include features including built-in Internet Protocol (IP) connectivity, information security and functional safety protection, and advanced control algorithms. Integrating MCU cores with field programmable gate arrays (FPGAs) is one means of optimi
[Microcontroller]
Regulatory considerations for MCUs in robots
Single chip automatic watering device
The automatic watering system is designed with 51 single-chip microcomputer + LCD1602 liquid crystal + soil sensor + relay + ADC0832 + water pump. The three system buttons are: system reset button, setup button, plus button, and minus button. 1. The soil dryness and humidity sensor transmits signals to the microcont
[Microcontroller]
Single chip automatic watering device
51 MCU-Invisible Vulnerability
1. Vulnerable code If we follow the writing method mentioned in the previous lesson, we can realize the running light with a timed interval of 50ms. #include reg52.h   #include function.h //See Chapter 6, Lecture 8 for details   void main() {     LED_Init(); //Initialize LED hardware module     EA = 1; //Close the
[Microcontroller]
51 MCU-Invisible Vulnerability
AVR chip two serial ports communicate with each other single chip source code
When learning the microcontroller serial port program, we often write a serial port self-transmitting and self-receiving program to test the hardware and the program we wrote; It is very simple to transmit and receive by yourself. You just need to short-circuit the RXD and TXD IOs of the serial port. And our XMEGA c
[Microcontroller]
AVR chip two serial ports communicate with each other single chip source code
Questions about RAM, SFR and bit address in 51 single chip microcomputer
There is a bit address 4EH in the 51 single-chip microcomputer. The 16 bytes of RAM 20H~2FH in the 51 single-chip microcomputer can be addressed according to "bits". There are a total of 128 "bit addresses", which are 00H~7FH. The bit address 4EH is the 6th bit in the "byte unit with byte address 29H".  Postscript: Z
[Microcontroller]
Questions about RAM, SFR and bit address in 51 single chip microcomputer
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号