-2
我試圖通過非常快速地打開和關閉LED來編程一個Arduino由於PWM LED矩陣。爲了控制亮度,我想在LED的開啓和關閉狀態之間添加額外的指令。亮度應該由預處理器變量設置。 Arduino擁有84MHz Cortex-M3 ARM處理器。如何在C++中使用預處理器指令的幫助下在語句之間插入語句?
這是我的代碼目前以何種方式提高亮度的簡化:
uint8_t volatile dummy = 0;
uint8_t i;
for (i=0;i<1<<current_layer;i++) { // every next layer has double the amount of pulses
LED_STATE = ON; // several pulses in one go speeds up the for loop
dummy = 0; // increases ON-time
LED_STATE = OFF;
LED_STATE = ON;
dummy = 0;
LED_STATE = OFF;
LED_STATE = ON;
dummy = 0;
LED_STATE = OFF;
LED_STATE = ON;
dummy = 0;
LED_STATE = OFF;
}
現在我希望能夠根據處理器變量像這樣可以提高亮度:
#define BRIGHTNESS 2
// inside loop
LED_STATE = ON; // several pulses in one go speeds up the for loop
#if BRIGHTNESS > 0
dummy = 0; // increases ON-time
#if BRIGHTNESS == 2
dummy = 0; // increases ON-time even more
#endif
#endif
LED_STATE = OFF;
LED_STATE = ON;
#if BRIGHTNESS > 0
dummy = 0;
#if BRIGHTNESS == 2
dummy = 0;
#endif
#endif
LED_STATE = OFF;
LED_STATE = ON;
#if BRIGHTNESS > 0
dummy = 0;
#if BRIGHTNESS == 2
dummy = 0;
#endif
#endif
LED_STATE = OFF;
LED_STATE = ON;
#if BRIGHTNESS > 0
dummy = 0;
#if BRIGHTNESS == 2
dummy = 0;
#endif
#endif
LED_STATE = OFF;
由於你可以看到,這使得代碼非常難讀。我想定義一個預處理器宏,根據BRIGHTNESS
的值添加這些虛擬語句。
這是代碼看起來應該像:
#define BRIGHTNESS 2
#define B1 ... // adds dummy=0; when BRIGHTNESS > 0 or else nothing at all
#define B2 ...
#define B3 ...
#define B4 ...
// inside loop
LED_STATE = ON;
B1 B2 B3 B4 // adds a number of dummy statements based on the value of BRIGHTNESS
LED_STATE = OFF;
LED_STATE = ON;
B1 B2 B3 B4
LED_STATE = OFF;
LED_STATE = ON;
B1 B2 B3 B4
LED_STATE = OFF;
LED_STATE = ON;
B1 B2 B3 B4
LED_STATE = OFF;
更妙的是插入基於可變那些語句的功能:
#define ADD_DUMMIES ...
// inside loop
LED_STATE = ON;
ADD_DUMMIES(BRIGHNESS)
LED_STATE = OFF;
我如何定義預處理器宏,以便他們會根據BRIGHTNESS
的值插入虛假陳述?
爲什麼不使用常規的'if'語句? – DimChtz
@DimChtz if語句如何提高可讀性? – uzumaki
如果你打算改變LED的亮度,爲什麼它是恆定的?我錯過了什麼? –