c语言方式优化#define MODEA_ON() (GPIOB->BSRR = GPIO_Pin_3) #define MODEA_OFF() (GPIOB->BRR = GPIO_Pin_3) #define MODEB_ON() (GPIOB->BSRR = GPIO_Pin_4) #define MODEB_OFF() (GPIOB->BRR = GPIO_Pin_4) #define MODEB1_ON() (GPIOB->BSRR = GPIO_Pin_7) #define MODEB1_OFF() (GPIOB->BRR = GPIO_Pin_7) volatile int drive; int TorqueContro(int tar,int cur) { static int Terror; int Tmid=2,Tmin=1000,Tmax=2000; static int driveA=0,driveB=0,driveC=0,driveD=0; Terror=tar-cur; if(Terror>=Tmax) {MODEA_ON();MODEB_OFF();MODEB1_OFF();//1 driveA=1;driveB=0;driveC=0;} else if(Tmin<=Terror&&Terror<Tmax) {MODEA_ON();MODEB_ON();MODEB1_OFF();//2 driveA=2;driveB=1;driveC=0;} else if(0<=Terror&&Terror<Tmin) {MODEA_OFF();MODEB_ON();MODEB1_OFF();//3 driveA=3;driveB=1;driveC=0;} else if(-Tmin<=Terror&&Terror<0) {MODEA_OFF();MODEB_ON();MODEB1_ON();//4 driveA=4;driveB=1;driveC=1;} else if(-Tmax<=Terror&&Terror<-Tmin) {MODEA_OFF();MODEB_OFF();MODEB1_ON();//5 driveA=5;driveB=0;driveC=1;} else if(Terror<-Tmax) {MODEA_ON();MODEB_OFF();MODEB1_ON();//6 driveA=6;driveB=0;driveC=1;} // MODEA_ON();MODEB_OFF();MODEB1_OFF(); // driveA=1;driveB=0;driveC=0;//²âÊÔÓà else MODEA_OFF();MODEB_OFF();MODEB1_OFF(); driveA=0;driveB=0;driveC=0; }
时间: 2024-04-13 16:29:11 浏览: 240
C语言优化方法
3星 · 编辑精心推荐
对于宏定义的优化,我们可以使用内联函数来替代宏定义。内联函数可以提高代码的可读性和可维护性,并且避免一些潜在的问题。
首先,将宏定义改为内联函数的示例代码如下:
```c
inline void MODEA_ON() {
GPIOB->BSRR = GPIO_Pin_3;
}
inline void MODEA_OFF() {
GPIOB->BRR = GPIO_Pin_3;
}
inline void MODEB_ON() {
GPIOB->BSRR = GPIO_Pin_4;
}
inline void MODEB_OFF() {
GPIOB->BRR = GPIO_Pin_4;
}
inline void MODEB1_ON() {
GPIOB->BSRR = GPIO_Pin_7;
}
inline void MODEB1_OFF() {
GPIOB->BRR = GPIO_Pin_7;
}
```
然后,在`TorqueContro`函数中使用这些内联函数,示例代码如下:
```c
volatile int drive;
int TorqueContro(int tar, int cur) {
static int Terror;
int Tmid = 2, Tmin = 1000, Tmax = 2000;
static int driveA = 0, driveB = 0, driveC = 0, driveD = 0;
Terror = tar - cur;
if (Terror >= Tmax) {
MODEA_ON();
MODEB_OFF();
MODEB1_OFF();
driveA = 1;
driveB = 0;
driveC = 0;
} else if (Tmin <= Terror && Terror < Tmax) {
MODEA_ON();
MODEB_ON();
MODEB1_OFF();
driveA = 2;
driveB = 1;
driveC = 0;
} else if (0 <= Terror && Terror < Tmin) {
MODEA_OFF();
MODEB_ON();
MODEB1_OFF();
driveA = 3;
driveB = 1;
driveC = 0;
} else if (-Tmin <= Terror && Terror < 0) {
MODEA_OFF();
MODEB_ON();
MODEB1_ON();
driveA = 4;
driveB = 1;
driveC = 1;
} else if (-Tmax <= Terror && Terror < -Tmin) {
MODEA_OFF();
MODEB_OFF();
MODEB1_ON();
driveA = 5;
driveB = 0;
driveC = 1;
} else if (Terror < -Tmax) {
MODEA_ON();
MODEB_OFF();
MODEB1_ON();
driveA = 6;
driveB = 0;
driveC = 1;
} else {
MODEA_OFF();
MODEB_OFF();
MODEB1_OFF();
driveA = 0;
driveB = 0;
driveC = 0;
}
}
```
通过将宏定义替换为内联函数,可以提高代码的可读性和可维护性。希望这些优化建议对你有帮助!如果你还有其他问题,请随时提问。
阅读全文