|
Code: --- |
|---|
|
``` const unsigned long duration = 30 * 1000; // The minimum total duration of the entire effect. |
| const unsigned long timer = 100; // The higher the number, the slower the timing. |
| const uint8_t buttonPin = 13; |
const uint8_t firstLedPin = 2;
const uint8_t lastLedPin = 7;
void setupcolor=#000000[/color] {
pinMode(buttonPin, INPUT);
// use a for loop to initialize each pin as an output:
for (uint8_t thisPin = firstLedPin; thisPin <= lastLedPin; thisPin++)
pinMode(thisPin, OUTPUT);
}
void ledsEffectcolor=#000000[/color] {
// loop from the lowest pin to the highest:
for (uint8_t thisPin = firstLedPin; thisPin <= lastLedPin; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delaycolor=#000000[/color];
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (uint8_t thisPin = lastLedPin; thisPin >= firstLedPin; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delaycolor=#000000[/color];
// turn the pin off:
digitalWrite(thisPin, LOW);
}
}
void ledsOffcolor=#000000[/color] {
for (uint8_t thisPin = firstLedPin; thisPin <= lastLedPin; thisPin++)
// turn leds off:
digitalWrite(thisPin, LOW);
}
void loopcolor=#000000[/color] {
static bool running = false;
static unsigned long startTime;
// read the value from the sensor :
bool buttonState = digitalReadcolor=#000000[/color];
if (buttonState == HIGH) {
running = true;
startTime = milliscolor=#000000[/color];
}
if color=#000000[/color] {
if (milliscolor=#000000[/color] - startTime > duration) {
running = false;
ledsOffcolor=#000000[/color];
} else {
ledsEffectcolor=#000000[/color];
}
}
}
```
|
Je kan gebruik maken van millis() voor de timing.
Voor de rest nog een paar opmerkingen:
Je pinnen en timers zijn constanten, dus gebruik het const keyword om aan te geven dat ze read-only zijn.
Je zet de pinMode van de buttonPin 6 keer in de loop, je kan die gewoon uit de loop halen.
Als je "sensor" een gewone drukknop is, kan je gewoon de interne pull-up weerstanden gebruiken in plaats van een externe weerstand, veel gemakkelijker.
buttonState hoeft geen globale variabele te zijn. Limiteer de scope zoveel mogelijk, en maak de variabele lokaal in de loop.
Pieter