C language C51 statements for single chip microcomputers

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

1. If Statement


The if statement is a basic conditional selection statement in C51. It usually has three formats:


(1) if (expression) {statement;}


(2) if (expression) {statement 1;} else {statement 2;}


(3) if (expression 1) {statement 1;}


else if (expression 2) (statement 2;)


else if (expression 3) (statement 3;)



else if (expression n-1) (statement n-1;)


else {statement n}


【Example】 Usage of if statement.


(1) if (x!=y) printf("x=%d,y=%dn",x,y);


When executing the above statement, if x is not equal to y, the value of x and the value of y are output.


(2) if (x>y) max=x;


else max=y;


     When executing the above statement, if x is greater than y, x is sent to the maximum value variable max. If x is not greater than y, y is sent to the maximum value variable max. The max variable gets the larger number of x and y.


(3) if (score>=90) printf(“Your result is an An”);


else if (score>=80) printf("Your result is an Bn");


else if (score>=70) printf("Your result is an Cn");


else if (score>=60) printf("Your result is an Dn");


else printf("Your result is an En");


After executing the above statement, five levels A, B, C, D, and E can be scored according to the score.


2. Switch/case Statement


If statements can be nested to implement a multi-branch structure, but the structure is complex. Switch is a multi-branch selection statement provided in C51 that specifically handles multi-branch structures. Its format is as follows:


switch (expression)


{case constant expression 1: {statement 1;}break;


case constant expression 2: {statement 2;}break;



case constant expression n: {statement n;}break;


default: {statement n+1;}


described as follows:


(1) The expression in the parentheses after switch can be an integer or character expression.


(2) When the value of the expression is equal to the value of the constant expression after a "case", the statement after the "case" is executed, and then the switch statement is exited when a break statement is encountered. If the value of the expression is different from the value of the constant expression after all cases, the statement after default is executed, and then the switch structure is exited.


(3) The value of each case constant expression must be different, otherwise there will be a contradiction.


(4) The order in which case statements and default statements appear has no effect on the execution process.


(5) Each case statement can be followed by a "break" or not. If there is a break statement, the switch structure will be exited when it is executed. If there is no break statement, the following statements will be executed in sequence until a break is encountered or the switch structure ends.


(6) Each case statement can be followed by one statement, multiple statements, or no statement. Statements can be enclosed in curly braces or not.


(7) Multiple cases can share a set of execution statements.


【Example】 Usage of switch/case statement.


The student scores are divided into A~D, corresponding to different percentage scores, and the corresponding percentages are required to be printed according to different grades. This can be achieved through the following switch/case statement.



switch(grade)


{

case 'A'; printf("90~100n"); break;


case 'B'; printf("80~90n"); break;


case 'C'; printf("70~80n"); break;


case 'D'; printf("60~70n"); break;


case 'E'; printf("<60n"); break;


default; printf("error"n)


}


3. while statement


The while statement is used in C51 to implement the while loop structure. Its format is as follows:


       while (expression)


           {statement;} /*loop body*/


       The expression after the while statement is the condition for looping, and the following statement is the loop body. When the expression is non-zero (true), the statements in the loop body are executed repeatedly; when the expression is zero (false), the while loop is terminated, and the program will execute the next statement outside the loop structure. Its characteristics are: first judge the condition, then execute the loop body. Change the condition in the loop body, and then judge the condition again. If the condition is met, execute the loop body again. If the condition is not met, exit the loop. If the condition is not met for the first time, the loop body will not be executed once.


[Example] The following program uses the while statement to calculate and output the cumulative sum of 1 to 100.


#include //Includes special function register library


#include //Include I/O function library


void main(void) //Main function


{

int i,s=0; //define integer variables x and y


i=1;


SCON=0x52; //Serial port initialization


TMOD=0x20;


TH1=0XF3;


TR1=1;


while (i<=100) // accumulate the sum of 1 to 100 in s


{

s=s+i;


i++;


}


printf("1+2+3……+100=%dn",s);


while(1);


}


The result of program execution:


1+2+3…+100=5050


4. do while statement


The do while statement is used in C51 to implement the until loop structure. Its format is as follows:


           do


                 {statement;} /*loop body*/


           while(expression);


Its characteristics are: the statements in the loop body are executed first, and then the expression is judged. If the expression is true (true), the loop body is executed again, and then judged again, until an expression is not true (false), then the loop is exited and the next statement of the do while structure is executed. When the do while statement is executed, the statements in the loop body will be executed at least once.


[Example] Use the do while statement to calculate and output the cumulative sum of 1 to 100.


#include //Includes special function register library


#include //Include I/O function library


void main(void) //main function


{

int i,s=0; //define integer variables x and y


i=1;


SCON=0x52; //Serial port initialization


TMOD=0x20;


TH1=0XF3;


TR1=1;


do //Accumulate the sum of 1 to 100 in s


{

s=s+i;


i++;


}


while (i<=100);


printf("1+2+3……+100=%dn",s);


while(1);


}


5. for Statement


for(expression1; expression2; expression3)


{statement;} /*loop body*/


The for statement is followed by three expressions and its execution process is as follows:


(1) First solve the value of expression 1.


(2) Solve the value of expression 2. If the value of expression 2 is true, execute the statements in the loop and then execute the next step (3). If the value of expression 2 is false, end the for loop and go to the last step.


(3) If the value of expression 2 is true, after executing the statements in the loop body, expression 3 is evaluated and then the process goes to step 4.


(4) Go to (2) and continue execution.


(5) Exit the for loop and execute the following statement.


    In a for loop, general expression 1 is an initial value expression, which is used to assign an initial value to the loop variable; expression 2 is a conditional expression, which is used to judge the loop variable; expression 3 is a loop variable update expression, which is used to update the value of the loop variable so that the loop variable can exit the loop if the condition is not met.


[Example] Use the for statement to calculate and output the cumulative sum of 1 to 100.


#include //Includes special function register library


#include //Include I/O function library


void main(void) //main function


{

int i,s=0; //define integer variables x and y


SCON=0x52; //Serial port initialization


TMOD=0x20;


TH1=0XF3;


TR1=1;


for (i=1;i<=100;i++) s=s+i; // add the sum of 1 to 100 in s


printf("1+2+3……+100=%dn",s);


while(1);


}


6. Nesting of loops


A loop body is allowed to contain a complete loop structure, which is called loop nesting. The outer loop is called the outer loop, and the inner loop is called the inner loop. If the inner loop body contains a loop structure, it constitutes a multiple loop. In C51, three loop structures are allowed to be nested.


[Example] Use nested structures to construct a delay program.


void delay(unsigned int x)


{

unsigned char j;


while(x--)


{for (j=0;j<125;j++);}


}


Here, an inner loop is used to construct a benchmark delay, and the number of outer loops is set through parameters when calling, so that various delay relationships can be formed.


7. break and continue statements


The break and continue statements are usually used in loop structures to jump out of the loop structure. However, there are some differences between the two statements, which are introduced below.


1) Break statement


As mentioned above, the break statement can be used to jump out of the switch structure, allowing the program to continue executing the next statement after the switch structure. The break statement can also be used to jump out of the loop body, ending the loop early and then executing the statement following the loop structure. It cannot be used in any other statement except loop statements and switch statements.


[Example 19] The following program is used to calculate the area of ​​a circle. When the calculated area is greater than 100, the break statement jumps out of the loop.


for (r=1; r<=10; r++)


{

area=pi*r*r;


if (area>100) break;


printf("%fn",area);


}


2) Continue statement


The continue statement is used in a loop structure to end the current loop, skip the unexecuted statements following continue in the loop body, and directly determine whether to execute the loop next time.


The difference between the continue statement and the break statement is that the continue statement only ends the current loop instead of terminating the entire loop; the break statement ends the loop without further conditional judgment.


【Example 20】 Output the numbers between 100 and 200 that are not divisible by 3.


for (i=100; i<=200; i++)


{

if (i%3= =0) continue;


printf("%d ";i);


}


In the program, when i is divisible by 3, the continue statement is executed, the current loop ends, and the printf() function is skipped. The printf() function is only executed when i is divisible by 3.


8. return statement


The return statement is usually placed at the end of a function to terminate the execution of the function and control the program to return to the location where the function was called. When returning, the return statement can also be used to bring back the return value. There are two formats of the return statement:

[1] [2]
Keywords:MCU Reference address:C language C51 statements for single chip microcomputers

Previous article:Functions of single-chip microcomputer C language C51
Next article:Input and output of single chip microcomputer C language C51

Recommended ReadingLatest update time:2024-11-16 13:35

STC51 series MCU power-off-free download (hot start download)
        I believe that friends who like single-chip microcomputers have used STC single-chip microcomputers. Friends who have used STC single-chip microcomputers have this feeling: affordable, easy to use, and powerful! It’s just that it’s very disgusting to have to cold start every time you download. I believe that m
[Microcontroller]
STC51 series MCU power-off-free download (hot start download)
STM8 MCU ADC sampling function is triggered by timer
  When using the ADC function of the STM8 microcontroller, there are generally two ways to read ADC data. One is to continuously read the sampling flag to determine whether the ADC sampling is completed, and the other is to notify the system whether the sampling is completed through an interrupt.   Sometimes when sa
[Microcontroller]
STM8 MCU ADC sampling function is triggered by timer
Talk about the RETI instruction of 51 single chip microcomputer
  Recently, a very strange problem occurred in the process of programming based on 51 single-chip microcomputer : "During program execution, under the conditions of register EA=1, ET0=1, TR0=1, but no interrupt was executed when TF0=1".   Anyone who has experience in single-chip interrupt programming knows that when E
[Microcontroller]
What is the crystal oscillator frequency of 51 microcontroller?
The 51 microcontroller is a commonly used microcontroller chip that is widely used in the control and calculation of various electronic devices. The crystal oscillator is very important in the microcontroller. It is the basis for the microcontroller to achieve high-precision and high-speed operations. JSK Jinghongxing
[Microcontroller]
Design of multi-channel temperature and humidity cycle detection system using microcontroller AT89C2051 and AD7416 chips
1 Introduction AD7416 Device Architecture The AD7416 is available in space-saving SO-8 and small SOIC packages. 2. System software and hardware design 2.1 Hardware design The microcontroller AT89C2051 is used to realize the signal acquisition and output control of the AD7416. The hardware design is simple and relia
[Microcontroller]
Design of multi-channel temperature and humidity cycle detection system using microcontroller AT89C2051 and AD7416 chips
Microchip's new cryptographic microcontroller improves operating system security for connected, autonomous vehicles
According to foreign media reports, Microchip Technology has launched the trusted computing encryption microcontroller CEC1712, which can terminate malicious programs such as rootkits and bootkits in systems started through external serial peripheral interface (SPI) flash memory. (Image source: Microchip Technolog
[Automotive Electronics]
Microchip's new cryptographic microcontroller improves operating system security for connected, autonomous vehicles
Simulation Intelligent Irrigation System Based on Single Chip Microcomputer
Simulating smart irrigation system: First the schematic diagram   This is a simulation picture drawn with Proteus. Of course, there are also pictures of the actual object, but I have placed them all in my studio (it’s obviously a laboratory, okay?). I am currently studying outside, so I will not show the actual
[Microcontroller]
Simulation Intelligent Irrigation System Based on Single Chip Microcomputer
Experimental Loading Closed-Loop Control System Based on AVR Microcontroller
Separate hydraulic jacks are widely used in various engineering structure loading work such as production construction, scientific experiments, etc. The equipment is generally composed of an electric high-pressure oil pump + a compression (tension) jack. The specifications of the loading system discussed in this arti
[Microcontroller]
Experimental Loading Closed-Loop Control System Based on AVR Microcontroller
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号