Article count:1382 Read by:1966155

Account Entry

Can't understand the code? Let's review the common C language knowledge points of microcontrollers

Latest update time:2024-06-12
    Reads:

Click on the blue " Linux " in the upper left corner and select " Set as Star "

1. Bit Operation

Bit operations are a method of operating binary numbers in a computer. Bit operations usually include AND (&), OR (|), XOR (^), and negation (~).

Common bit operations include:

  1. AND operation (&): Perform a logical AND operation on the corresponding bits of two binary numbers. The positions with the result of 1 are retained, and the positions with the result of 0 are set to 0.

  2. OR operation (|): Perform a logical OR operation on the corresponding bits of two binary numbers. The position with the result of 1 is set to 1, and the position with the result of 0 is left alone.

  3. XOR operation (^): Perform an XOR operation on the corresponding bits of two binary numbers. The position with a result of 1 is set to 1, and the position with a result of 0 is set to 0.

  4. Negation operation (~): reverse each bit of a binary number.

  5. Left shift operator (<<): It is used to shift the binary representation of a number to the left by a specified number of bits. In the left shift operation, all the bits in the binary representation of the number are shifted to the left by the specified number of bits and padded with zeros on the right.

  6. Right shift operator (>>): It is used to shift the binary representation of a number to the right by a specified number of bits. In the right shift operation, all the bits in the binary representation of the number are shifted to the right by a specified number of bits. If it is a signed number, it is filled with the original sign bit on the left; if it is an unsigned number, it is filled with zeros on the left.


Bitwise Operations

meaning

Example 1010

&

Bitwise AND

1010&=1100; //1010&1100=1000

~

Settlement

~(1010); //0101

|

Bitwise OR

1010|=1100; //1010|1100=1110

<<

Shift Left

1010<<1; //0100

>>

Shift Right

1010>>2; //0010

^

Bitwise XOR

1010^=1100; //0110


2. Macro Definition

#define TEMP 10 //TEMP 可替换成 10

#define is a preprocessor directive used to define a constant or macro.

When you use a statement like #define TEMP 10, it means defining the identifier TEMP to the value 10.

Throughout the program, you can use TEMP to represent the value 10, and it will be replaced by the actual value at compile time.

For example, the following code snippet

#include <stdio.h>
#define TEMP 10
int main() { int num = TEMP; printf("%d\n", num); return 0;}

In this code, #define TEMP 10 defines a constant TEMP, whose value is 10. In the main function, int num = TEMP; is actually replaced by int num = 10;, so the value of num is 10 when the program is running. Using #define to define constants or macros can improve the readability and maintainability of the code, and it is convenient to modify the value of the constant uniformly.

3. Conditional compilation

Conditional compilation is a method of selectively including or excluding parts of the code based on conditions during compilation. In C/C++, conditional compilation is implemented using the preprocessing directives #ifdef, #endif, #else, and #elif. Commonly used conditional compilation directives are:


  1. #ifdef: Compiles the following code block if the given identifier is already defined.

  2. #ifndef: If the given identifier is not defined, the following code block is compiled.

  3. #if: Accepts a conditional expression and compiles the following code block if the condition is true.

  4. #elif: Used in conjunction with #if, it means that if the previous condition is not met, continue to judge the next condition.

  5. #else: Used with #if or #elif to execute the following code block if the condition is not met.

  6. #endif: Ends the conditional compilation block.


文件名:led.h

#include _LED_H    //如果没有编译过这个头文件(_LED_H与文件led.h一一对应)#include _LED_H    //编译这个文件
void LED_init(void); //函数定义#endif //保证在多个.c 文件同时引用时不重复,默认所有头文件都添加

Through conditional compilation, we can choose to compile different codes according to different conditions and switch between different versions.

4. extern variable declaration

extern 类型 变量名;

The keyword extern is used to declare a variable or function, indicating that its definition is in another file. By using the extern keyword, you can reference global variables or functions defined in other files without redefining them.

Specifically, when a variable is declared using the extern keyword, it means that the variable is not defined in the current file, but in another file, and the current file only references the variable. This allows the same variable to be shared between multiple files.

Example:

Suppose there are two files file1.c and file2.c, and a global variable int num is defined in file1.c:

// file1.cint num = 10;

In file2.c, we can use the extern keyword to declare num:

// file2.cextern int num;

In this way, file2.c can reference the num variable defined in file1.c. When linking, the compiler will merge the num variables in the two files into one to ensure that they point to the same memory address.

If multiple source files in the same file use the extern keyword to reference the same global variable, the global variable will only be defined once when the program is finally linked.

5. typedef type alias

typedef 类型 别名;

A keyword that defines a new name or alias for an existing data type. With the typedef keyword, we can create a new name for an existing type, making the code easier to read and maintain.

example:

typedef unsigned char uint8_t;    //把 unsigned char 类型取别名为 uint_ttypedef uint8_t u8;               //把 uint8_t “类型” 再取名为 u8


6. Structure

A structure is a user-defined data type that can be used to combine different types of data into a new data type. A structure can contain multiple different data members, each of which can be a different data type.

Structures are usually used to represent an entity with related attributes, such as a student, a car, a book, etc. Through structures, these attributes can be packaged together for easy operation and transfer.

In C language, the definition format of the structure is as follows:

struct 结构体名称 {    数据类型1 成员名称1;    数据类型2 成员名称2;    // 其他成员};


example:

Suppose we have a simple STM32 project and need to configure a timer to generate a timer interrupt. We can define a structure to represent the configuration information of the timer, as shown below:


#include "stm32f4xx.h"
typedef struct { TIM_TypeDef *timerInstance; uint32_t period;} TimerConfig;
void configureTimer(TimerConfig *config) { // 设置定时器时钟使能 if(config->timerInstance == TIM2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); }
// 配置定时器周期 TIM_TimeBaseInitTypeDef TIM_InitStruct; TIM_InitStruct.TIM_Prescaler = 8400 - 1; // 1us为单位 TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_InitStruct.TIM_Period = config->period - 1; TIM_InitStruct.TIM_ClockDivision = 0; TIM_TimeBaseInit(config->timerInstance, &TIM_InitStruct);
// 启用定时器 TIM_Cmd(config->timerInstance, ENABLE);}
int main() { // 配置定时器2,周期为1秒 TimerConfig timer2Config; timer2Config.timerInstance = TIM2; timer2Config.period = 1000000; // 1秒,单位为us
configureTimer(&timer2Config);
while(1) { // 循环执行其他操作 }
return 0;}

In this example, the TimerConfig structure contains a pointer to a timer instance and the period information of the timer. The configureTimer function is used to initialize the timer according to the given configuration information. In the main function, a TimerConfig structure instance is created to configure Timer 2, and the configureTimer function is called for configuration. Finally, an infinite loop is entered to perform other operations.

By using structures, related configuration information can be packaged together and the information can be transferred and managed more flexibly. Structures are usually used in STM32 microcontroller projects to represent register mapping, peripheral configuration, etc., to help organize and manage code.

7. C language keyword static

static 类型 变量名

If a variable is declared as a static variable or a global variable (using the static keyword), it will have static storage duration and remain unchanged in memory during the execution of the program. This means that the value of a static variable persists after the function call ends and until the program terminates. Static local variables declared in a function also retain their values ​​during the life of the program.

The static keyword is commonly used in C language:

  • Control the scope of variables and functions;

  • Keep variables or functions persistent so that they retain their state during program execution;

  • Avoid name conflicts between global variables and functions when writing modular code.

example:


int sta(){    static int n = 0;    n++;        return n;//1234567...}// n 的值保存了上一次调用的值,程序运行期间内存中保持不变
The article comes from the Internet and the copyright belongs to the original author. If there is any infringement, please contact us to delete it.

end



A bite of Linux


Follow and reply【 1024 】 to get a large amount of Linux information


Collection of wonderful articles

Recommended articles

【Album】 ARM
【Album】 Fan Q&A
【Album】 All original
Album Getting started with Linux
Special Computer Network
Album Linux Driver


Latest articles about

 
EEWorld WeChat Subscription

 
EEWorld WeChat Service Number

 
AutoDevelopers

About Us Customer Service Contact Information Datasheet Sitemap LatestNews

Room 1530, Zhongguancun MOOC Times Building,Block B, 18 Zhongguancun Street, Haidian District,Beijing, China Tel:(010)82350740 Postcode:100190

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号