MCU code optimization

MCU code optimization

1. Macro definition and header file

The basic composition of the header file

#ifndef _KEY_H_ //防重复引用,如果没有定义过_KEY_H_,则编译下句
#define _KEY_H_ //此符号唯一, 表示只要引用过一次,即#i nclude,则定义符号_KEY_H_

char keyhit( void ); //击键否
unsigned char Keyscan( void ); //取键值
#endif

Macro definition

  • Capitalize the macro name
  • The macro definition is not a C statement, without a semicolon at the end
#define KEYNUM 65//按键数量,用于Keycode[KEYNUM]
#define LINENUM 8//键盘行数
#define ROWNUM 8//键盘列数

2. Operational optimization

1. Multiplication and division can be changed to shift

2 multiples

a = a * 4;
b = b / 4;
// 可以改为:
a = a << 2; 
b = b >> 2;

other

a = a * 9
// 等价于 a = a * 8 + a
a = (a << 3) + a

2. Take the modulus

x = x % 8
// 就是8 - 1
x = x & 7

Three. Statement

1. Loop

for(;;)Than while(1)good

Four. Variable type

1. Global variables

  • Variables defined outside the function occupy resources
  • Poor versatility

2. Local variables

Only valid inside the function, no value assignment, its initial value is uncertain

3.auto type

By default, local variables areauto

4.static type

  • Define a local variable as static, then its value in the function is unchanged (will not die when the function ends) and the initial value defaults to 0.
  • Set the global variable to static, then it is available in the current file, but cannot be read in other files

5.extern type

Multiple files need to be used, such as defining a global variable, and multiple files must read the value of this global variable.

// 这里是声明
extern int MAX;

6.register type

Call register to calculate

int sum = 0;
for (register int i = 0; i < 10; ++i)
{
    
    
    sum += i;
}

Guess you like

Origin blog.csdn.net/weixin_44179485/article/details/113529150