The previous article introduced the basic data types of C language. In order to process more complex data more effectively, C language introduced structured data types. Constructing a type is to put a batch of various types of data together to form a special type of data. The array discussed before can also be regarded as a structural type of data. The structural types in the microcontroller C language include structures, enumerations and unions.
structure
A structure is a collection of data that can combine variables of different types as needed. The entire collection is represented by a structure variable name, and the variables that make up this collection are called structure members. Understand the concept of structure and understand it through the relationship between the class and students. The class name is equivalent to the structure variable name, which represents the collection of all students, and each student is a member of this structure. When using structure variables, you must first define the structure type. The general definition format is as follows:
struct structure name {structural element list};
Example: struct FileInfo
{
unsigned char FileName[4]; unsigned long Date; unsigned int Size;
}
The above example defines a simple file information structure type, which can be used to define simple microcontroller file information. There are three elements in the structure, which are used to operate file names, dates, and sizes. Because each data member in the structure can use different data types, the data type must be defined for each data member. After defining a structure type, structure variables can be defined in the following format. It should be noted that only structure variables can participate in the execution of the program. The structure type is only used to indicate which structure the structure variable belongs to.
struct structure name Structural variable name 1, structure variable name 2...structural variable N; Example: struct FileInfo NewFileInfo, OleFileInfo;
Through the above definition, NewFileInfo and OleFileInfo are both FileInfo structures, and both have a character array, a long integer and an integer data. Defining a structure type only gives the organizational form of the structure. It does not occupy storage space. In other words, the structure name cannot be assigned values and operations. Structural variables are specific members in the structure, occupy space, and can operate on each member.
Structures are allowed to be nested, which means that when defining a structure type, the elements of the structure can be composed of another structure. like:
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 the data structure variable named NowDate
Friends who are starting to learn may ask after seeing this: "How to reference and assign values to each data element?" When using structural variables, it is achieved by referencing its structural elements. The reference method is to use the access structure element member operator "." to connect the structure name and element name. The format is as follows:
Structural variable name.structural element
To access the month in the structure variable in the above example, write NowDate..year. For nested structures, multiple member operators are used when referencing elements, connecting them level by level to the lowest level structure element. It should be noted that in the microcontroller C language, only the lowest-level structural elements can be accessed, and it is impossible to operate the entire structure. Operation example:
NowDate.year = 2005;
NowDate.month = OleMonth+ 2; //Add 2 to the month data based on the old one
NowDate.Time.min++; //The minute hand increases by 1, and only the lowest level element can be referenced when nesting. The name of an element in a structure variable can have the same name as a variable used elsewhere in the program, because the element belongs to the structure in which it is located. Use member operators to specify.
The definition of structure type can also have the following two formats.
struct
{
Structural element table
} Structure variable name 1, structure variable name 2...structure variable name N;
Example: struct
{
unsigned char FileName[4]; unsigned long Date; unsigned int Size;
} NewFileInfo, OleFileInfo;
This definition does not use a structure name and is called an unnamed structure. It is usually used when there are only a few certain structure variables in the program and cannot be nested in other structures.
Another way to define it is as follows:
struct structure name
{
Structural element table
} Structure variable name 1, structure variable name 2...structure variable name N;
例:struct FileInfo
{
unsigned char FileName[4]; unsigned long Date; unsigned int Size;
} NewFileInfo, OleFileInfo;
Using structure names makes it easier to read the program and easier to use later in defining other structures. enumerate
In programs, some variables are often used to make judgment marks in the program. If you often need to use a character or integer variable
To store 1 and 0 as signs to determine whether the condition is true or false, but we may overlook that this variable is only valid when it is equal to 0 or 1
If it is not valid, assigning it to another value will cause the program to error or become confusing. At this time, you can use enumerated data types to define variables and limit incorrect assignments. The enumeration data type is a collection of certain integer constants represented by a name, and the integer constants are the legal values that can be obtained by this enumeration type variable. The two definition formats of enumeration types are as follows:
enum enumeration name {enumeration value list} variable list;
Example enum TFFlag {False, True} TFF;
enum enumeration name {enumeration value list};
emum enumeration name variable list;
例 enum Week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum Week OldWeek, NewWeek;
After reading the above example, you may be confused about one thing, that is, why can enumeration values be used without depreciation? That's because in the enumeration list, each item name represents an integer value. By default, the compiler will automatically assign a value to each item. The first item is assigned a value of 0, the second item is 1... For example, Sun in Week is 0 and Fri is 5. The C language also allows initialization and assignment of various values. It should be noted that after a certain value is initialized, its subsequent values will also be incremented. like:
enum Week {Mon=1, Tue, Wed, Thu, Fri, Sat, Sun};
The enumeration in the above example makes the Week value range from 1 to 7, which is more in line with our habits. Use enumerations just like variables, but you cannot assign values to them in the program.
joint
Union is also a constructed type data structure in C language. Like the structure type, it can contain different types of data elements. The difference is that the combined data elements are stored starting from the same data address. The memory size occupied by a structure variable is the total number of memory occupied by the data elements in the structure, while the memory size occupied by a union variable is only the memory size occupied by the longest element in the union. If an int and a char are defined in the structure, the structure variable will occupy
Using 3 bytes of memory, and also defining an int and a char in the union, the union variable will only occupy 2 bytes. This technology that can make full use of memory space is called 'memory overlay technology', which allows different variables to use the same memory space in a time-sharing manner. When using joint variables, please note that its data elements can only be used in time-sharing, not at the same time. To give a simple example, the program first assigns a value of 1000 to the int in the union, and then assigns a value of 10 to the char. Then it cannot be referenced at this time.
int, otherwise the program will make an error. The last assigned element will take effect, and the last assigned element will be invalid. During use, please also note that when defining a union variable, its value cannot be initialized, pointers to union variables can be used to operate it, union variables cannot be passed as parameters of functions, and arrays and structures can appear in unions.
The definition method of union type variables is similar to the definition method of structure. Just replace the keyword struct with union. The reference method of union variables also uses the '.' member operator.
The following uses a comprehensive example to illustrate the simple use of the three types.
#include #include void main(void) { enum TF { False, True} State; //Define an enumeration to make the program more readable union File { //The union contains an array and structure, unsigned char Str[11]; //The entire union shares 11 bytes of memory struct FN { unsigned char Name[6],EName[5];} FileName; } MyFile; unsigned char Temp; SCON = 0x50; //Serial port mode 1, allowing reception TMOD = 0x20; //Timer 1 timing mode 2 TCON = 0x40; //Set timer 1 to start counting TH1 = 0xE8; //11.0592MHz 1200 baud rate TL1 = 0xE8; TI = 1; TR1 = 1; //Start the timer State = True; //Demonstrated here, State can only be assigned to two values: False and True, and the others are invalid. //State = 3; This is wrong printf ("Input File Name 5Byte: n"); scanf("%s", MyFile.FileName.Name); //It takes 6 bytes to save a 5-byte string printf ("Input File ExtendName 4Byte: n"); scanf("%s", MyFile.FileName.EName); if (State == True) { printf ("File Name : "); for (Temp=0; Temp<12; Temp++) printf ("%c", MyFile.Str[Temp]); //All bytes are listed here printf ("n Name :"); printf ("%s", MyFile.FileName.Name); printf ("n ExtendName :"); printf ("%s", MyFile.FileName.EName); } while(1); } Figure 17-1 shows the results of the operation. What is shown in A shows that the array and structure in the union in the routine occupy the memory space of the same address, while the two arrays in the structure each occupy two different segments of memory. space.
Previous article:Why is the 51 crystal oscillator 11.0592?
Next article:How to use Keil3 to develop 51 microcontroller program
- Popular Resources
- Popular amplifiers
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- LED chemical incompatibility test to see which chemicals LEDs can be used with
- Application of ARM9 hardware coprocessor on WinCE embedded motherboard
- What are the key points for selecting rotor flowmeter?
- LM317 high power charger circuit
- A brief analysis of Embest's application and development of embedded medical devices
- Single-phase RC protection circuit
- stm32 PVD programmable voltage monitor
- Introduction and measurement of edge trigger and level trigger of 51 single chip microcomputer
- Improved design of Linux system software shell protection technology
- What to do if the ABB robot protection device stops
- Industry first! Xiaopeng announces P7 car chip crowdfunding is completed: upgraded to Snapdragon 8295, fluency doubled
- P22-009_Butterfly E3106 Cord Board Solution
- Keysight Technologies Helps Samsung Electronics Successfully Validate FiRa® 2.0 Safe Distance Measurement Test Case
- Innovation is not limited to Meizhi, Welling will appear at the 2024 China Home Appliance Technology Conference
- Innovation is not limited to Meizhi, Welling will appear at the 2024 China Home Appliance Technology Conference
- Huawei's Strategic Department Director Gai Gang: The cumulative installed base of open source Euler operating system exceeds 10 million sets
- Download from the Internet--ARM Getting Started Notes
- Learn ARM development(22)
- Learn ARM development(21)
- Learn ARM development(20)
- Buck switching power supply MOS tube gate has pwm signal, but cannot conduct normally
- Motor Driver
- Sharing on the serious problem of LM2611 output voltage heating
- How much do you know about the "ADI Inside" behind these popular healthcare products?
- About ARM's interrupt service routine
- P-NUCLEO-WB55
- 4.3-inch split-screen display
- Recommend a 24-bit ADC module (not a chip), preferably with the same pin definition as the attachment, 12 pins, SPI interface...
- Reasons why the POE module does not supply power
- What are the types of LDOs used in portable mobile devices? Ripple test methods