Abstract: I heard that many friends learning microcontrollers can’t use structs? Pointers and structs are essential to mastering microcontrollers. If your C language skills are shaky, you won’t grasp the essence of microcontrollers and will only complete some basic projects. Understanding structs and being able to use them flexibly indicates that you have entered the world of microcontrollers.
This article will explain the use of structs in the simplest way, combined with the STM32 microcontroller. It aims to resolve your frustration of not understanding microcontroller structs even after learning C language and passing the computer level 2 exam.
As we all know, pointers and structs are the difficult points in microcontrollers, so we go to learn C language, watch videos, read books…
The views of each video are very high. For purely learning C language, they explain it very clearly. After watching, you can’t help but comment below: Wow! It’s really explained so clearly!
However, when you actually learn microcontrollers, you’ll find that you have learned C language, passed the computer level 2 exam, but still don’t understand pointers and structs? Did I learn a fake C language?
Actually, this is not your fault, nor the fault of microcontrollers. The problem is that there needs to be a transition between C language and microcontrollers! This transitional point is not explained in many microcontroller video tutorials. Educational institutions assume you already know, so when explaining the running light, they do not explain the GPIO initialization struct, assuming you know how to operate it.
Declare a GPIO_InitTypeDef
struct, and then define a variable GPIO_InitStructure
in the LED_Init(void)
function. This variable can set the members of the GPIO_InitTypeDef
struct. This is just an introduction; please continue reading.
1. Why Structs Are Needed
Let’s not talk about what a struct is for now; let’s discuss why we need structs. Only by knowing why we need them can we learn according to our needs, which will enhance efficiency. You will know under what circumstances we need to write a struct and how to use it.
Let’s take a smart home project as an example.
First, we look at a practical problem: There is a project with 4 sensors: Light sensor, smoke sensor, alcohol sensor, humidity sensor. Each of these sensors also has a set alarm threshold range.
It is generally written like this:
#include "sys.h"
#include "delay.h"
#include "usart.h"
/* Record sensor values */
float temperature; // Temperature
char humidity; // Humidity
char alcohol; // Alcohol concentration
int illumination; // Light intensity
/* Record sensor high and low thresholds */
float temperature_threshold[2];
float humidity_threshold[2];
float alcohol_threshold[2];
float illumination_threshold[2];
int main(void)
{
uart_init(115200);// Serial port initialization
delay_init();
while(1)
{
}
}
Of course, when you do a project, you will definitely define many other variables and need to record other variables.
Then a few days later, you add a carbon monoxide sensor.
A few days later, each sensor also needs a flag bit to indicate whether it is working normally.
Due to project requirements, you then add 4 more identical sensors: temperature and humidity, light intensity, smoke concentration, alcohol concentration.
Then you add 4 more identical sensors: temperature and humidity, light intensity, smoke concentration, alcohol concentration.
The screenshots are too crowded…
If you can’t prepare in advance when starting the project, continuing to work will make the entire program code hard to maintain, let alone continue writing!
2. The Emergence of Structs
Then the folks who created C language invented a feature struct
1. A struct is something that can contain variables.
struct
represents the definition of a struct, sensors
is the name of the struct, followed by a pair of curly braces { }
You can define variables freely inside the curly braces~
How to use the variables inside?
Note: A struct is a data type, just like int
and char
.
Since it is a data type, you can define variables of this data type.
Define a variable of this struct:
Why is it defined that way?
Answer: Go ask the folks who created C language! Ask them why they designed it this way!
Then operate the member variables inside the struct variable. When we define the struct variable, the member variables will automatically appear when initializing the member variables. If you typed this code one by one, you would marvel at how wonderful structs are in microcontrollers!
Some might ask why there is a dot in the middle of the struct variable?
Answer: Go ask the folks who created C language! Ask them why they designed it this way.
2. You can actually define a struct variable like this
You can also define multiple:
Did you notice that each struct variable has all the member variables of the struct?
As mentioned earlier, if you add another set of sensors: temperature and humidity, light intensity, smoke concentration, alcohol concentration, you only need to define another struct variable.
However, many times the structs we see in microcontrollers are not defined like above but with a typedef
keyword in front.
Such examples are often seen in library function header files, where we frequently see the following struct:
3. The typedef Keyword
First, let’s look at the definition of typedef
from Baidu Encyclopedia:
In summary: typedef
can give a data type a different name.
typedef {data type} {new name}
#include "sys.h"
#include "delay.h"
#include "usart.h"
typedef int zhjiguoxin;//zhjiguoxin is int
zhjiguoxin value = 0;
int main(void)
{
uart_init(115200);// Serial port initialization
delay_init();
printf("value=%d\r\n",value);
while(1)
{
}
}
Although typedef
can give variables aliases, nobody would name them like that; I just used it as an example.
4. The Essence of Structs
1. The following represents this struct data type
2. Give this data type an alias
Note that there are three parts: typedef {data type} {new name}
. Thus, sensor
represents this struct.
It is recommended that beginners save the following image to your computer so that you will never forget the use of typedef
in structs and can quickly remember this concept.
3. In the future, when defining struct variables, you won’t need to define them like struct sensors sen;
anymore; you can just use sensor sen;
.
4. The struct name can be omitted.
Note that the struct definition can omit the struct name; in C language, that sensors
is not called the struct name but a tag. The struct name is the struct
keyword + tag. Thus, for simplicity, we often see structs in microcontrollers written as follows.
5. Struct Variables Can Hold Any Variable
1. Struct variables can hold any variable (int pointer)
#include "sys.h"
#include "delay.h"
#include "usart.h"
typedef struct
{
float temperature; // Temperature
char humidity; // Humidity
char alcohol; // Alcohol concentration
int illumination;// Light intensity
char CO; // Carbon monoxide concentration
int *p; // int pointer variable
} sensor;
sensor sen;
int value =0;
int main(void)
{
uart_init(115200);// Serial port initialization
delay_init();
sen.p=&value;// Assign the address of value
// Print the value at the address represented by p (which is actually the value of value)
printf("value=%d\r\n",*(sen.p));
while(1)
{
}
}
Since it’s a pointer variable, the value assigned to the pointer variable is, of course, an address.


2. Struct variables can hold any variable (function pointer)
#include "sys.h"
#include "delay.h"
#include "usart.h"
typedef struct
{
float temperature; // Temperature
char humidity; // Humidity
char alcohol; // Alcohol concentration
int illumination;// Light intensity
char CO; // Carbon monoxide concentration
int *p; // int pointer variable
void (*fun)();
} sensor;
sensor sen;
void function()
{
printf("zhiguoxin\r\n");
}
int value =0;
int main(void)
{
uart_init(115200);// Serial port initialization
delay_init();
sen.fun=function;
sen.fun();
while(1)
{
}
}
Since it’s a function pointer variable, the value assigned to the function pointer variable is also an address, and it must be the address of a function. The function name is the address of that function. That’s why we assign the address of the function function();
to the function pointer fun
.
Is it clear to everyone now? If not, it is recommended to watch it more than three times!
3. Struct variables can hold any variable (struct variable)
This is struct nesting, where one struct contains another struct as its member. When struct nesting occurs, you must access the struct members in a cascading manner, that is, use the member selection operator to find the lowest level member before referencing it.
#include "sys.h"
#include "delay.h"
#include "usart.h"
typedef struct
{
int i;
}zhiguoxin;
typedef struct
{
float temperature; // Temperature
char humidity; // Humidity
char alcohol; // Alcohol concentration
int illumination;// Light intensity
char CO; // Carbon monoxide concentration
int *p; // int pointer variable
void (*fun)();
zhiguoxin guougo;
}sensor;
sensor sen;
int main(void)
{
uart_init(115200);// Serial port initialization
delay_init();
sen.guougo.i=100;
printf("i=%d\r\n",sen.guougo.i);
while(1)
{
}
}
4. Struct variables can hold any variable (struct pointer)
A struct is a data type. Of course, data types can also define corresponding pointer variables.
Just like int
type can define int *p;
So, if you find that your code accesses the struct through —>
, then this struct variable must be a pointer type variable.
Similarly, if the struct is accessed through .
, then this struct variable is not a pointer variable but a regular variable.
Conclusion: By now, regarding the application of structs in microcontrollers, I believe you have grasped it quite well. You might feel that the content of this article is too simple, but only by solidifying this simple foundational knowledge can you progress faster; otherwise, you will always feel that your code is lacking.
Source: Guoguo Little Brother
Microcontroller C Language Programming Encyclopedia, a must-have for beginners
Classic Introductory Tutorial for 51 Microcontroller (a very good tutorial)
Comprehensive Examples of Microcontroller Programming
Collection of Microcontroller Interface Materials, 50 volumes
Learn Microcontrollers in Ten Days, very complete version
Microcontroller Peripheral Circuit Design
100 Examples of Microcontroller Programming Techniques
👇Scan to join the Microcontroller WeChat group for free downloads👇
