Lesson 17 C51 Use of Structures, Unions and Enumerations

Publisher:创意火舞Latest update time:2023-06-26 Source: elecfansKeywords:C51 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

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.

[1] [2]
Keywords:C51 Reference address:Lesson 17 C51 Use of Structures, Unions and Enumerations

Previous article:Why is the 51 crystal oscillator 11.0592?
Next article:How to use Keil3 to develop 51 microcontroller program

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号