Summary of C Language Knowledge for Microcontrollers!

Summary of C Language Knowledge for Microcontrollers!

1. Introduction to the advantages of C language for microcontrollers in conjunction with the 8051: · No need to understand the specific hardware of the microcontroller to write professional-level programs that conform to the actual hardware; · No need to understand the instruction set of the microcontroller to write perfect microcontroller programs; · Different function data can overlap, effectively utilizing the limited RAM space on the chip; · Provides storage types such as auto, static, const, and storage types specifically for the 8051 microcontroller such as data, idata, pdata, xdata, code, etc., automatically allocating reasonable addresses for variables; · C language provides complex data types (arrays, structures, unions, enumerations, pointers, etc.), greatly enhancing program processing capabilities and flexibility; · Provides compilation modes such as small, compact, and large to adapt to the size of on-chip memory; · The context protection and recovery of interrupt service routines, as well as the filling of the interrupt vector table, are directly related to the microcontroller and are handled by the C compiler; · Programs have robustness: data corruption is a major factor leading to abnormal program operation. C language has many professional treatments for data to avoid asynchronous corruption during operation; · Provides commonly used standard function libraries for users to use directly; · Has strict syntax checking, with few errors that can be easily eliminated at a high-level language level; · Can easily accept services from various utility programs: for example, utility programs for on-chip resource initialization can be automatically generated; also, real-time multitasking operating systems can schedule multiple tasks, simplifying user programming and improving operational safety, etc.; · Macro definitions in header files, explanations of complex data types, and function prototypes are beneficial for program portability and support for the development of serialized products for microcontrollers;2. HEX file Established the first microcontroller C language project, but in order for the compiled program to be written into the 51 chip by the programmer, a HEX file must first be generated by the compiler.3. Comment statements supported by the C compiler: One type starts with the “//” symbol, and all statements after the symbol are treated as comments until a newline is encountered. The other type is comments within “/*” and “*/” symbols. Comments will not be compiled by the C compiler.4. Main function: A C application must have one main function, which can call other functional functions, but other functional functions are not allowed to call the main function. Regardless of where the main function is placed in the program, it is always executed first.5. Minimal system A resistor and an LED are added to display its status, and the crystal oscillator can be used according to its situation. Generally, the experimental board uses 11.0592MHz or 12MHz. The advantage of using the former is that it can generate standard serial port baud rates, while the latter has a machine cycle of 1 microsecond, which is convenient for precise timing.

2. C51 Constants

1. Description of constant data types: (1) Integer constants can be represented in decimal such as 123, 0, -89, etc. Hexadecimal starts with 0x, such as 0x34, -0x3B, etc. Long integers are suffixed with the letter L, such as 104L, 034L, 0xF340, etc. (2) Floating-point constants can be divided into decimal and exponential notation. Exponential notation is [±]number[.number]e[±]number, where the content in [] is optional, and the rest must be present, such as 125e3, 7e9, -3.0e-3. (3) Character constants are characters within single quotes, such as ‘a’, ‘d’, etc. Non-displayable control characters can be formed into special escape characters by adding a backslash “\” before the character. For a common escape character table, please refer to the table below:

Escape Character Meaning ASCII Code (Hex/Decimal)
\o Null Character (NULL) 00H/0
\n Newline (LF) 0AH/10
\r Carriage Return (CR) 0DH/13
\t Horizontal Tab (HT) 09H/9
\b Backspace (BS) 08H/8
\f Form Feed (FF) 0CH/12
\’ Single Quote 27H/39
Double Quote 22H/34
\\ Backslash 5CH/92

(4) String constants consist of characters within double quotes, such as “test”, “OK”, etc. When there are no characters within the quotes, it is an empty string. When using special characters, escape characters must also be used, such as double quotes. In C, string constants are treated as character type arrays, and when storing strings, the system adds a \o escape character at the end of the string as a terminator. String constant “A” and character constant ‘A’ are not the same; the former occupies one more byte in storage. (5) Bit scalar, whose value is a binary.2. Applications Constants can be used in situations where the value does not need to change, such as fixed data tables, font libraries, etc. There are several ways to define constants, as explained below. #define False 0x0; // Use predefined statements to define constants #define True 0x1; // Here False is defined as 0, True as 1 // In the program, when False is used, it is automatically replaced with 0 at compile time, and similarly, True is replaced with 1 unsigned int code a=100; // This line defines a in program memory and assigns a value const unsigned int c=100; // Defines c as an unsigned int constant and assigns a value. The values of the above two lines are stored in program memory, which cannot be modified during runtime, so if similar assignment statements like a=110, a++ are used after these two lines, a compile-time error will occur.

3. C51 Variables

1. Variable format [Storage Type] Data Type [Memory Type] Variable Name List In the definition format, except for the data type and variable name list, which are necessary, the others are optional.2. Storage types There are four storage types: automatic (auto), external (extern), static (static), and register (register), with the default type being automatic (auto).(1)Static (local static) variables Memory will not be released during the entire runtime of the program. If a local variable is defined without an initial value, it will automatically be assigned a value of 0 at compile time. For automatic variables, if not assigned a value during definition, it will have an indeterminate value. Other functions cannot reference it.(2)Declaring external variables with extern A program can consist of multiple source files. If a program needs to reference an external variable defined in another file, it needs to use extern to declare it. Example: In one file: int abc; In another file: extern abc;3. Data types(1) Data types

Data Type

Length

Value Range

unsigned char

Single byte

0~255

signed char

Single byte

-128~+127

unsigned int

Double byte

0~65535

signed int

Double byte

-32768~+32767

unsigned long

Four bytes

0~4294967295

signed long

Four bytes

-2147483648~+2147483647

float

Four bytes

±1.175494E-38~±3.402823E+38

*

1~3 bytes

Address of the object

bit

Bit

0 or 1

sfr

Single byte

0~255

sfr16

Double byte

0~65535

sbit

Bit

0 or 1

The highest byte in a byte indicates the sign of the data, “0” indicates a positive number, and “1” indicates a negative number, with negative numbers represented in two’s complement.(2) Special Bit scalar is an extended data type of the C51 compiler, which allows defining a bit scalar, but bit pointers and bit arrays cannot be defined. Its value is a binary bit, either 0 or 1, similar to the Boolean type in some high-level languages representing True and False. SFR is also an extended data type, occupying one memory unit, with a value range of 0~255. It allows access to all special function registers inside the 51 microcontroller. SFR16 occupies two memory units, with a value range of 0~65535. SFR16, like SFR, is used to operate special function registers, but it is used to operate registers that occupy two bytes, such as timers T0 and T1.sfr16 T2 = 0xCC; // Here defines timer 2 of the 8052, address T2L=CCH, T2H=CDH. When defining a 16-bit special function register with sfr16, the address after the equal sign is its low address, and the high address must be located above the physical low address. Note that it cannot be used for defining timers 0 and 1. Sbit is also an extended data type in microcontroller C language, which allows access to addressable bits in the internal RAM of the chip or addressable bits in special function registers. For example, if we previously defined sfr P1=0x90; // Since the P1 port register is bit-addressable, we can define sbit P1_1=P1^1; // P1_1 is the P1.1 pin in P1. Similarly, we can write using the address of P1.1, such as sbit P1_1=0x91; so that in future program statements we can use P1_1 to read and write to the P1.1 pin.(3) Redefining data types with typedef The syntax of typedef: typedef existing data type new data type name Example: typedef int integer; integer a,b; Typedef cannot be used directly to define variables; it only replaces the name of an existing data type and does not create a new data type.4. Memory types Specify the storage area used by the variable in the microcontroller C language hardware system and accurately locate it at compile time.

Memory Type Description
data Direct access to internal data memory (128 bytes), fastest access speed
bdata Bit-addressable internal data memory (16 bytes), allows bit and byte mixed access
idata Indirect access to internal data memory (256 bytes), allows access to all internal addresses
pdata Page access to external data memory (256 bytes), accessed using MOVX @Ri instruction
xdata External data memory (64KB), accessed using MOVX @DPTR instruction
code Program memory (64KB), accessed using MOVC @A+DPTR instruction

Note that in the AT89c51 chip, RAM only has the lower 128 bits, while the higher 128 bits located from 80H to FFH are only useful in the 52 chip and overlap with special register addresses. If the memory type is omitted, the system will specify the variable’s storage area according to the default memory type specified by the compilation mode SMALL, COMPACT, or LARGE. Regardless of the storage mode, variables can be declared in any of the 8051 storage area ranges; however, placing the most commonly used commands such as loop counters and queue indices in the internal data area can significantly improve system performance. It should also be pointed out that the storage type of variables is completely unrelated to the memory type.(1) Addresses of special registers (SFR) List of special function registers for AT89C51 (applicable to chips of the same architecture)

Symbol

Address

Comment

*ACC

E0H

Accumulator

*B

F0H

Multiplication Register

*PSW

D0H

Program Status Word

SP

81H

Stack Pointer

DPL

82H

Data Memory Pointer Low 8 bits

DPH

83H

Data Memory Pointer High 8 bits

*IE

A8H

Interrupt Enable Controller

*IP

D8H

Interrupt Priority Controller

*P0

80H

Port 0

*P1

90H

Port 1

*P2

A0H

Port 2

*P3

B0H

Port 3

PCON

87H

Power Control and Baud Rate Selection

*SCON

98H

Serial Port Controller

SBUF

99H

Serial Data Buffer

*TCON

88H

Timer Control

TMOD

89H

Timer Mode Selection

TL0

8AH

Timer 0 Low 8 bits

TL1

8BH

Timer 1 Low 8 bits

TH0

8CH

Timer 0 High 8 bits

TH1

8DH

Timer 1 High 8 bits

All special function registers marked with an asterisk are bit-addressable registers.(2) Data storage modes ① Small mode: All default variable parameters are loaded into internal RAM, the advantage is fast access speed, the disadvantage is limited space, suitable only for small programs. ② Compact mode: All default variables are located in a page (256 Bytes) of external RAM, which page can be specified by the P2 port, as explained in the STARTUP.A51 file, or can be specified using pdata. The advantage is that space is more ample than Small, and speed is slower than Small but faster than Large, making it an intermediate state. ③ Large mode: All default variables can be placed in up to 64KB of external RAM, the advantage is large space, can store many variables, the disadvantage is slower speed.5. Keil C51 pointer variables The microcontroller C language supports generic pointers and memory-specific pointers. (1) Generic pointers The declaration and use of generic pointers are the same as standard C, but can also specify the storage type of the pointer, for example: char * xdata ptr; ptr is a pointer to char data, while ptr itself is stored in the external RAM area.Generic pointers occupy 3 bytes, consisting of storage type, high byte offset, and low byte offset. (2) Memory-specific pointers When specifying a memory-based pointer, the storage type is also specified, for example: char data * str; str points to char data in the data area;this type of pointer only needs one or two bytes for storage, as it only needs to store the offset. (3) Pointer conversion When a memory-based pointer is passed as an argument to a function that requires a generic pointer, the pointer is automatically converted. If the external function prototype is not specified, the memory-based pointer is automatically converted to a generic pointer, leading to errors, so please use “#include” to specify all function prototypes.6. Space allocation methods for variables in microcontroller C language (1) The data area is small, so only frequently used or high-speed operation-required variables should be placed in the data area, such as counting values in for loops. It is best to place local variables in the data area. The space for local variables is released upon exiting the function, except for static local variables, which have the same memory usage as global variables; (2) Ensure that there are no unused functions in your program. In Keil C, if an unused function is encountered, the compiler considers it a potential interrupt function. The space for local variables used in the function is not released, and is treated the same as global variables. (3) Logical flag variables encountered in the program can be defined in bdata, which can greatly reduce memory usage. (4) Other variables that are not frequently used and do not require high-speed operations should be placed in the xdata area. If you want to save data space, you must use large mode, placing all variables without defined memory locations in the xdata area. Of course, it is best to specify the memory type for all variables. (5) When using pointers, specify the memory type to which the pointer points. An undefined generic pointer occupies 3 bytes; while a pointer defined to point to the data area only occupies 1 byte; a pointer defined to point to the xdata area occupies 2 bytes. For example, if pointer p points to the data area, it should be defined as: char data *p; You can also specify the memory type where the pointer itself is stored, such as: char data *xdata p;

4. C51 Operators and Expressions

Operators can be divided into unary operators, binary operators, and ternary operators based on their relationship with operands in expressions. Unary means it requires one operand, binary requires two operands, and ternary requires three operands. An expression is a statement composed of operations and operands that has a specific meaning. Adding a semicolon after an expression forms an expression statement.

1. Operators and expressions ① Assignment operator: variable=expression; ② Arithmetic operators: +, /, -, *, %; the division operator differs from general arithmetic rules, for example, if two floating-point numbers are divided, the result is a floating-point number, such as 10.0/20.0 resulting in 0.5, while dividing two integers results in an integer, such as 7/3 resulting in 2. ③ ++ increment operator, — decrement operator. These two operators are unique to C language. In VB, PASCAL, etc., they do not exist. I++ (or I–) uses the value of I first, then executes I+1 (or I-1); ++I (or –I) executes I+1 (or I-1) first, then uses the value of I. ④ Relational operators: >, <, >=, <=, ==, !=. “==” in VB or PASCAL is represented by “=”, and “!=” is represented by “not”. ⑤ Logical operators: Logical AND: condition1 && condition2; Logical OR: condition1 || condition2; Logical NOT: !condition2. Note that the result of using logical operators can only be 0 or 1, which means logical true and false, in other words, logical quantities. ⑥ Bitwise operators: ~, <<, >>, &, ^, |. Bitwise operators perform operations on variables bit by bit, but do not change the values of the variables involved in the operation. If you want to change the value of the variable bitwise, you need to use the corresponding assignment operation.Bitwise operators cannot be used to operate on floating-point data. ⑦ Compound assignment operators: Add other operators before the assignment operator “=”: +=, -=, *=, /=, >>=, &=, |=, ^=, %=, !=, <<=. a+=56 is equivalent to a=a+56; y/=x+9 is equivalent to y=y/(x+9). ⑧ Comma operator ⑨ Conditional operator: logical expression? expression1 : expression2. When the value of the logical expression is true (non-zero), the value of the entire expression is the value of expression1; when the value of the logical expression is false (zero), the value of the entire expression is the value of expression2. ⑩ Pointer and address operators:*: get content; &: get address; the general forms for getting content and address are: variable=*pointer variable; pointer variable=⌖ variable. ⑪ sizeof operator: syntax: sizeof(data type). Example: printf(“char is how many bytes? %d bytes\n”, sizeof(char)); the result is: char is how many bytes? 1 byte. ⑫ Type casting operator: statement: (type) expression.Note: Implicit conversions that are automatically handled by the compiler during program compilation are called implicit conversions. The rules are as follows: Implicit conversions occur when assigning variables, where the data type of the expression on the right side of the “=” sign is converted to the data type of the variable on the left side. All char type operands are converted to int type. When two operands of different data types are connected by an operator, implicit conversions occur in the following order: if one operand is of float type, the other operand will also be converted to float type; if one operand is of long type, the other will also be converted to long; if one operand is of unsigned type, the other operand will be converted to unsigned type. 2. Operator precedence and associativity

Level

Category

Name

Operators

Associativity

1

Type conversion, arrays, structures, unions

Type casting

Subscript

Access structure or union members

( )

[ ]

-> or .

Right associative

2

Logical

Bitwise

Increment

Decrement

Pointer

Arithmetic

Length calculation

Logical NOT

Bitwise NOT

Increment

Decrement

Address, content retrieval

Unary minus

Length calculation

!

~

++

&, *

sizeof

Left associative

3

Arithmetic

Multiplication

Division

Modulus

*

/

%

Right associative

4

Arithmetic and pointer operations

Addition

Subtraction

+

Right associative

5

Bitwise

Left shift

Right shift

<<

>>

Right associative

6

Relational

Greater than or equal to

Greater than

Less than or equal to

Less than

>=

>

<=

<

Right associative

7

Relational

Equal to

Not equal to

==

!=

Right associative

8

Bitwise

Bitwise AND

&

Right associative

9

Bitwise

Bitwise XOR

^

Right associative

10

Bitwise

Bitwise OR

|

Right associative

11

Logical

Logical AND

&&

Left associative

12

Logical

Logical OR

||

Left associative

13

Conditional

Conditional operation

?:

Left associative

14

Assignment

Assignment

Compound assignment

=

Op=

Left associative

15

Comma

Comma operation

,

Right associative

5. C51 Expression Statements

1. Different programming languages have different expression statements, such as VB, which forms an expression statement by adding a newline after the expression, while in C language for the 51 microcontroller, a semicolon “;” is added to form an expression statement.2. A special expression statement called an empty statement is usually formed by adding a semicolon after a loop statement constructed with while or for, creating an empty loop body that does not execute any other operations. Example:#include <AT89x51.h>

void main(void)

{ unsigned int a;

do

{

P1 = 0xFF; // Turn off the LED on P1

while(P3_7); // Empty statement, wait for P3_7 to be pressed to low level, when low level execute the following statement P1 = 0; // Light up the LED

for(;a<60000;a++); // This is also a method of using an empty statement, note that a’s initial value is the current value

} // This way, when pressed for the first time, there will be a delay to light up for a period of time, and after that, the longer it is pressed, the longer it will light up

while(1); // After lighting for a period of time, turn off and check P3_7 again, and loop like this

}

3. Compound statements:Combine several statements into a functional block, and this statement composed of several statements is called a compound statement. Each statement inside it still needs to end with a semicolon “;”. Compound statements are allowed to be nested. For a function, the function body is a compound statement, and it may be known that compound statements can consist not only of executable statements but also of variable definition statements.

4. Conditional statements:

C language provides three forms of conditional statements:

① if(condition expression) statement. When the result of the condition expression is true, the statement is executed; otherwise, it is skipped. For example, if(a==b) a++; When a equals b, a is incremented by 1.

② if(condition expression) statement1 else statement2. When the condition expression holds, statement1 is executed; otherwise, statement2 is executed. For example, if(a==b) a++; else a–; When a equals b, a is incremented by 1; otherwise, a is decremented by 1.

③ if(condition expression1) statement1;

else if(condition expression2) statement2;

else if(condition expression3) statement3;

else if(condition expressionm) statementn;

else statementm;

5. Switch statements:

Syntax: switch(expression)

{case constant expression1: statement1; break;

case constant expression2: statement2; break;

case constant expression3: statement3; break;

case constant expressionn: statementn; break;

default: statement}

6. Loop statements:In C language, the statements that constitute loop control are while, do-while, for, and goto statements.(1) goto statement An unconditional jump statement. Syntax: goto label; where the label is an identifier with a colon. Example:

void main(void)

{

unsigned char a;

start: a++;

if (a==10) goto end;

goto start;

end:;

}

A common use of the goto statement is to jump out of multiple loops, but it can only jump from an inner loop to an outer loop, not from an outer loop to an inner loop.(2)while statement Syntax: while(condition expression) statement;

When the condition expression is true, it executes the following statement; after execution, it returns to the while to perform the condition check. If true, it repeats the statement; if false, it exits the loop body. If the condition is false from the start, the loop body (statement or compound statement) after while will not execute at all and will exit the loop. When debugging the program, be careful that the condition of while should not be false, which may cause an infinite loop. It may help your debugging work to add breakpoints at the while condition.

(3) do while statement Syntax: do statement while(condition expression); Executes the loop body first, then checks the condition to decide whether to exit the loop.(4) for statement for([initialization expression];[loop condition expression];[condition update expression]) statement; the expressions in the brackets are optional.7. continue statement (also called interrupt statement) An unconditional jump statement. Its function is to end the current loop, skip the statements in the loop body that have not been executed, and jump to the next loop cycle. This is different from the break statement mentioned earlier, as continue does not exit the loop but jumps to the start of the loop and executes the next loop.8. return statement Syntax: return (expression); when returning, the expression is calculated first, and then the value of the expression is returned. If no expression is provided, the returned value is indeterminate.

6. C51 Functions

1. Function definition

The definition pattern is as follows:

Function Type Function Name(Formal Parameter List)

{

Function Body

}

The function type indicates the type of value returned by the defined function. The return value is essentially a variable, and the function type should be defined according to the variable type. If the function does not need to return a value, the function type can be written as “void” to indicate that the function has no return value. Note that the return value type of the function body must be consistent with the function type. The formal parameters are the variables that need to be passed into the function body for computation when calling the function; they can have one, several, or none. When no formal parameters are needed, the parentheses can be empty or written as “void” to indicate that, but the parentheses cannot be omitted. The function body can contain definitions of local variables and program statements; if the function needs to return a computed value, the return statement must be used to return it. In the function’s {} brackets, nothing can be written, which becomes an empty function. In a program project, some empty functions can be written, making it convenient to expand functionality in these empty functions during future modifications and upgrades.

2. Function calls (1) Before calling a function, the type of the function must be specified, even for standard library functions. The specifications for standard library functions are written in different header files according to their functions, and when used, the corresponding header file can be included at the beginning of the file using the #include< .h> preprocessor statement. (2) Function statements. For example, printf(“Hello World!\n”); this appears in our first program, taking “Hello World!\n” as a parameter to call the printf library function. Here, the function call is treated as a statement. (3) Function parameters: for example, temp=StrToInt(CharB(16)); the return value of CharB is passed as an actual parameter to the StrToInt function. (4) Function expressions: temp=Count(); this statement treats the function call as an operand appearing in the expression, which can be called a function expression. (5) When calling a user-defined function, the function type specification should be written in the following form: type identifier function name(formal parameter list); this specification is used when the called function definition and the calling function are in the same file. (6) For files written in the filename.h file, use #include “filename.h” to include it. If the definition of the called function and the calling function are not in the same file, the following form should be used to specify that the definition of the called function is above in the same project but in a different file: extern type identifier function name(formal parameter list);3. Interrupt service functions The extended keyword is interrupt, which is an option in function definitions. Format: function type function name(formal parameters) interrupt n [using n]Interrupt numbers and interrupt vectors for the AT89C51 chip

Interrupt Number Interrupt Source Interrupt Vector
0 External Interrupt 0 0003H
1 Timer/Counter 0 000BH
2 External Interrupt 1 0013H
3 Timer/Counter 1 001BH
4 Serial Port 0023H

Example:

  1. #include <at89x51.h>

  2. unsigned char P3State(void); // Function specification, interrupt functions do not need specification

  3. void main(void)

  4. {

  5. IT0 = 0; // Set external interrupt 0 to be triggered by low level

  6. EX0 = 1; // Allow response to external interrupt 0

  7. EA = 1; // Global interrupt switch

Copy code

7. Using arrays in C51

Example: unsigned int xcount [10]; // Define an unsigned integer array with 10 data units

char inputstring [5]; // Define a character array with 5 data units

float outnum [10],[10];// Define a floating-point array with 100 data units

unsigned char LEDNUM[2]={12,35}; // One-dimensional array with initial values

int Key[2][3]={{1,2,4},{2,2,1}}; // Two-dimensional array with initial values

unsigned char IOStr[]={3,5,2,5,3}; // Array length not specified, compiler sets automatically

unsigned char code skydata[]={0x02,0x34,0x22,0x32,0x21,0x12}; // Data stored in code area

8. Using pointers in C51

The content of a pointer variable is the address of another variable, and the variable to which the address belongs is called the variable pointed to by the pointer variable. The method is to first use &STR to get the variable address and assign it to the STRIP pointer variable, then you can access STR using *STRIP. The ‘*’ is the pointer operator, which allows you to obtain the value at the address pointed to by the pointer variable. Format: data type [memory type] *variable name; Example: unsigned char xdata *pi; // Pointer occupies two bytes, the pointer itself is stored in the compiler’s default storage area, pointing to char type in the xdata storage area

unsigned char xdata * data pi; // Pointer itself specified in data area, others the same

int * pi; // Defined as a generic pointer, pointer itself stored in the compiler’s default storage area, occupying three bytes

The maximum value of a pointer variable is 0xFFFF, which determines that a generic pointer occupies 3 bytes in memory, with the first byte storing the encoding of the pointer storage type, and the next two storing the high and low addresses of the pointer. Memory-based pointers occupy one or two bytes because they do not need to identify the storage type; idata, data, pdata storage pointers occupy one byte, while code and xdata occupy two bytes.

9. Using structures, unions, and enumerations in C51

1. Structure:A collection of data(1)General definition of structure typeFormat: struct structure name {structure element list}; Example: struct FileInfo{unsigned char FileName[4]; unsigned long Date; unsigned int Size;}(2)Defining structure variable format: struct structure name structure variable name1, structure variable name2,……structure variable nameN; Example: struct FileInfo NewFileInfo, OldFileInfo; Only structure variables can participate in program execution; structure types are only used to indicate which structure the structure variable belongs to. Through the above definition, NewFileInfo and OldFileInfo are both of the FileInfo structure, each having a character array, a long integer, and an integer data. Defining a structure type only gives the organization form of this structure; it does not occupy storage space, meaning that structure names cannot be assigned or operated on. Structure variables are the specific members of the structure, which occupy space and can operate on each member. Structures are allowed to be nested, meaning that when defining a structure type, the elements of the structure can consist of another structure. Example: struct clock{unsigned char sec, min, hour;}

struct date{

unsigned int year;

unsigned char month, day;

struct clock Time; // This is structure nesting

}

struct date NowDate; // Define date structure variable named NowDate

(3) Referencing and assigning Format:Structure variable name.structure element. To access the month in the structure variable from the previous example, it should be written as NowDate.year=2021. NowDate.Time.min++; // Increment minute by 1, when nested can only reference the lowest level element; a structure variable’s element name can be the same as a variable used elsewhere in the program, as the element belongs to the structure it is in, and when used, the member operator must be specified. (4) Other definition methods

struct{structure element list} structure variable name1, structure variable name2……structure variable nameN;

Example: struct{unsigned char FileName[4]; unsigned long Date; unsigned int Size;} NewFileInfo, OldFileInfo;

This definition method does not use a structure name, called an unnamed structure. It is usually used in cases where only a few specific structure variables are needed in the program and cannot be nested in other structures.

struct structure name{structure element list} structure variable name1, structure variable name2……structure variable nameN;

Example: struct FileInfo{unsigned char FileName[4]; unsigned long Date; unsigned int Size;} NewFileInfo, OldFileInfo;

Using structure names makes the program easier to read and facilitates future use in defining other structures.

2. Enumeration:Representing a collection of certain integer constants with a name, where the integer constants are the legal values that this enumeration type variable can take. (1) Definition format enum enumeration name {enumeration value list} variable list; Example: enum TFFlag {False, True} TFF; enum enumeration name {enumeration value list}; enum enumeration name variable list; Example: enum Week {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; enum Week OldWeek, NewWeek; (2) In the enumeration list, each item name represents an integer value, and by default, the compiler automatically assigns a value to each item, with the first item assigned 0, the second item 1, and so on. For example, in Week, Sun is 0, Fri is 5. C language also allows initializing values for each item, and it should be noted that after initializing a certain item value, the subsequent items will also increment accordingly. Example: enum Week {Mon=1, Tue, Wed, Thu, Fri, Sat, Sun};3. Union (1) It can contain different types of data elements like other structure types. The difference is that other types of data elements are stored starting from the same data address, while the memory size occupied by structure variables is the total memory size occupied by the data elements in that structure, while the memory size occupied by union variables is only the memory size occupied by the longest element in that union.(2) If an int in the union is first assigned a value of 1000, and then a char is assigned a value of 10, then at this point, the int cannot be referenced; otherwise, the program will error, as the last assigned element takes effect, while the previous assigned element becomes invalid. It should also be noted that when defining union variables, they cannot be initialized, can use pointers to operate on union variables, and union variables cannot be passed as function parameters; arrays and structures can appear in unions. (3) Definition format: union structure name{structure element list}; union structure name structure variable name1, structure variable name2,……structure variable nameN; union {structure element list} structure variable name1, structure variable name2……structure variable nameN; union structure name{structure element list} structure variable name1, structure variable name2……structure variable nameN;

Summary of C Language Knowledge for Microcontrollers!

Summary of C Language Knowledge for Microcontrollers!

Part of electronic book screenshots

Summary of C Language Knowledge for Microcontrollers!

【Complete Set of Hardware Learning Materials Collection】

Summary of C Language Knowledge for Microcontrollers!

Leave a Comment