问题描述
我想在 tinkercad 中使用 Arduino 制作 2 个 LED 的占空比。我有 2 个 LED,一个是红色的,另一个是绿色的。我希望两个 LED 同时亮起,但红色 LED 的发光延迟为 1 秒,绿色 LED 为 1.3 秒,如下图所示,并且两个占空比均为 50%。
但我无法做到这一点,我曾尝试使用 2 个 if-else 块,但由于它同步获取 if-else 而不起作用,然后我尝试计算图形并希望将其作为延迟但这不是一个简单的解决方案
我已经了解到millis() 是解决方案,但我将如何使用它? 请帮我解决这个问题
解决方法
试试这个代码:
#define LED11_PIN 11
#define LED12_PIN 12
#define LED12_BLINK_RATE 1000
#define LED11_BLINK_RATE 1300
class Led
{
private:
bool _ledState;
const int _ledBlinkRate;
double _lastStateChange;
const int _ledPin;
public:
Led(int blinkRate,int ledPin) : _ledState(false),_ledBlinkRate(blinkRate),_lastStateChange(millis()),_ledPin(ledPin)
{}
~Led()
{}
void update()
{
double currTime = millis();
if((_lastStateChange + _ledBlinkRate/2) <= currTime)
{
_ledState = !_ledState;
digitalWrite(_ledPin,_ledState);
_lastStateChange = currTime;
}
}
};
Led led11(LED11_BLINK_RATE,LED11_PIN);
Led led12(LED12_BLINK_RATE,LED12_PIN);
void setup()
{
pinMode(LED12_PIN,OUTPUT);
pinMode(LED11_PIN,OUTPUT);
}
void loop()
{
led11.update();
led12.update();
}