Pages: [1]   Go Down
Author Topic: One output blinking, another output fading?  (Read 1944 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 13
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am a newbie and this question may sound a little bit silly.

How can I have a flashing LED on output 13 and a fading LED on output 11.
And why not throw in a pushbutton on input 2.

I don't see to understand how to do "multiple" tasks that are "independant" from each other.
Am I supposed to write several void loops? Or do I have to put  all my diffrent "tasks" inside {}
Logged

Brisbane, Australia
Offline Offline
God Member
*****
Karma: 1
Posts: 593
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Throw them all in to loop().
The only catch is you cannot use delay(). You need to do your own timing.
Logged

SF Bay Area (USA)
Offline Offline
Tesla Member
***
Karma: 137
Posts: 6805
Strongly opinionated, but not official!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here you go.
Code:
int ledPin = 13;                 // LED connected to digital pin 13
int fadePin = 3;
unsigned long nextBlink, nextFade;
int fadeBrightness = 0;
char ledState = LOW, fadeDir = 10;

void setup()
{
    pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    pinMode(fadePin, OUTPUT);
    ledState = LOW;
    nextBlink = millis();
    nextFade = millis();
}

/*
 * This checks whether it's time to change the state of the LED, and
 * does the write if so.  But it doesn't execute delay(), so in either
 * case it takes essentially no time to execute.
 */
void blink(void)
{
    unsigned long now;
    now = millis();
    if (now >= nextBlink) {
        nextBlink = now + 1000;    // Next change in one second
        if (ledState == LOW) {
            digitalWrite(ledPin, HIGH);
            ledState = HIGH;
        }
        else {
            digitalWrite(ledPin, LOW);
            ledState = LOW;
        }
    }
}

void fade(void)
{
    unsigned long now;
    now = millis();
    if (now >= nextFade) {
        nextFade = now + 200;    // Next change in one second
        if (fadeDir > 0) {
            if (fadeBrightness > (255 - fadeDir)) {
                fadeDir = - fadeDir;
            }
        }
        else {
            if (fadeBrightness < (-fadeDir)) {
                fadeDir = - fadeDir;
            }
        }
        fadeBrightness += fadeDir;
        analogWrite(fadePin, fadeBrightness);
    }
}

void loop()
{
    blink();
    fade();
}
Logged

Pages: [1]   Go Up
Jump to: