↑ Powrót do Systemy Wbudowane

Arduino: dwie migające niezależnie diody

Dwie niezależnie migające diody. Prosta przeróbka programu „Blink without delay” zrealizowana przez dodanie drugiego licznika.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Public Domain Code
// This code is NOT OPTIMAL - this is only version of "Blink without delay" for 2 LED

const int led1Pin =  12;      // the number of the LED1 pin
const int led2Pin =  13;      // the number of the LED2 pin

// Variables will change:
int led1State = LOW;             // ledState used to set the LED1
int led2State = LOW;             // ledState used to set the LED2
long previousLed1Millis = 0;     // will store last time LED1 was updated
long previousLed2Millis = 0;     // will store last time LED2 was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long intervalLed1ON =  100;      // interval at which to LED1 will be ON
long intervalLed1OFF = 500;      // interval at which to LED1 will be OFF
long intervalLed2ON = 1000;      // interval at which to LED2 will be ON
long intervalLed2OFF = 800;      // interval at which to LED2 will be OFF

long interval1 = intervalLed1OFF; //  store interval for current status of LED1
long interval2 = intervalLed2OFF; //  store interval for current status of LED2

void setup() {
// set the digital pin as output:
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
}

void loop()
{
unsigned long currentMillis = millis();

if(currentMillis - previousLed1Millis > interval1) {
  // save the last time you blinked the LED
  previousLed1Millis = currentMillis;
  // if the LED is off turn it on and vice-versa:
  if (led1State == LOW){
     led1State = HIGH;
     interval1 = intervalLed1ON;}  // set interval for status ON
  else{
     led1State = LOW;
     interval1 = intervalLed1OFF;}  /// set interval for status OFF
  // set the LED with the ledState of the variable:
  digitalWrite(led1Pin, led1State);
}

if(currentMillis - previousLed2Millis > interval2) {
  // save the last time you blinked the LED
  previousLed2Millis = currentMillis;
  // if the LED is off turn it on and vice-versa:
  if (led2State == LOW){
     led1State = HIGH;
     interval2 = intervalLed2ON;}
  else{
     led2State = LOW;
     interval2 = intervalLed2OFF;}
  // set the LED with the ledState of the variable:
  digitalWrite(led1Pin, led1State);
}

}

Jak można zoptymalizować ten kod? A gdyby dołożyć trzecią, czwartą, … szóstą diodę?

[important]Treść tego artykułu wraz z ilustracjami udostępniam na licencji Public Domain.[/important]