-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的亮度,为什么它是恒定的?我错过了什么? –