2012-06-09 54 views
0

我需要編寫一個Arduino代碼,以交替頻率淡入淡出兩個LED。 也就是說 - 當第一個LED達到峯值時,第二個LED開始消失。 同樣最佳的是它應該沒有延遲地運行(),因爲我需要一堆其他代碼同時運行。我想我會使用SoftPWMLibrary,但我沒有看到如何使用它來淡化開始。Arduino中的時間衰落

回答

0

也許你可以添加此

class fade 
{ 
private: 
    uint8_t _min; 
    uint8_t _max; 
    uint8_t _to; 
    uint8_t _dutyCycle; 
    uint32_t _time; 
    uint32_t _last; 
    int _pin; 

public: 
    fade (int pin, uint32_t timeStep=10000, uint8_t min=0, uint8_t max=255) 
    { 
    _pin = pin; 
    _time = timeStep; 
    _min = min; 
    _max = max; 
    analogWrite(_pin,_min); 
    _dutyCycle = _min; 
    } 
    void write(int to) 
    { 
    _to = (uint8_t) constrain(to,_min,_max); 

    this->update(); 
    } 

    void update() 
    { 
    this->update(micros()); 
    } 

    void update(uint32_t time) 
    { 
    if(time + _time > _last) 
    { 
     _last = time; 
     if(_dutyCycle > _to) analogWrite(_pin,--_dutyCycle); 
     if(_dutyCycle < _to) analogWrite(_pin,++_dutyCycle); 
    } 
    } 

    uint8_t read() 
    { 
    return _dutyCycle; 
    } 

    uint32_t readSpeed() 
    { 
    return _time; 
    } 

    uint32_t writeSpeed(uint32_t time) 
    { 
    _time=time; 
    } 
}; 

/*now create a fade object 
* fade foo(pin, timestep, min, max) 
* timeStep is by default 10000 us (10 ms) 
* min is by default 0 
* max is by default 255 
* 
* example 
* fade foo(13) is the same as fade foo(13, 10000, 0, 255) 
* 
* to change the speed once declared. 
* foo.writeSpeed(new speed); 
* to read the current speed 
* foo.readSpeedspeed(); 
* 
* foo.read() returs the current fade level (pwm dutyCycle); 
* foo.write(to) defines the new endpoint of the fader; 
* 
* foo.update(); needs to called in the loop 
* foo.update(time); is for saving time if more time relating objects; 
* unsigned long a = micros(); 
* foo.update(a); 
* bar.update(a); 
* foobar.update(a); 
* is faster than redefine time every update 
*/ 

fade led1(11);// fader pin 11 speed 10 ms/ step 
fade led2(10,100000);// fader pin 10 speed 100 ms/step; 

void setup() 
{ 
    led2.write(128); //fade to half 
    led1.write(255); //fade to max 

    //setup 
} 

void loop() 
{ 
    unsigned long time = micros(); 
    led1.update(time); 
    led2.update(time); 

    // loop 
} 

這不是測試,但應該工作