Exercice : Fonctions

Simulation

Il est possible de simuler ce programme avec TinkerCad ou Wowki

Soit le programme suivant :

1
#include "constantes.h"
2
int i=0;
3
int motif[10];
4
5
void setup() {
6
  pinMode(PORT_LED, OUTPUT);
7
  Serial.begin(9600);//Initialise le port série (pour l'affichage dans la fenêtre Moniteur)
8
  motif[0] = 1;
9
  motif[1] = 1;
10
  motif[2] = 0;
11
  motif[3] = 1;
12
  motif[4] = 1;
13
  motif[5] = 0;
14
  motif[6] = 1;
15
  motif[7] = 1;
16
  motif[8] = 0;
17
  motif[9] = 1;
18
}
19
void loop() {
20
  if(i > 9) {i = 0;}
21
  if(motif[i] == 1){
22
    digitalWrite(PORT_LED, ALLUME);   // Allume la LED
23
    delay(DUREE_BASE_ALLUME); 
24
  }
25
  else{
26
    digitalWrite(PORT_LED, ETEINT);    // Eteint la LED
27
    delay(DUREE_BASE_ETEINT);
28
  }
29
  i++;
30
}
1
/* Principaux réglages (fichier constantes.h) */
2
3
#define PORT_LED 4
4
#define ALLUME 1
5
#define ETEINT 0
6
#define DUREE_BASE_ALLUME 500
7
#define DUREE_BASE_ETEINT 500

Question

Complétez le programme pour que la fonction loop() ressemble à ceci :

1
void loop() {
2
  if(i > 9) {i = 0;}
3
  if(motif[i] == 1){ 
4
    allume();
5
  }
6
  else{
7
    eteint();
8
  }
9
  i++;
10
}

Question

Proposer une nouvelle modification pour que le contenu de la fonction loop() soit celui indiqué ci-dessous :

1
void loop() {
2
  if(i > 9) {i = 0;}
3
  commandeLed(motif[i]);
4
  i++;
5
}

Solution

1
#define PORT_LED 4
2
#define ALLUME 1
3
#define ETEINT 0
4
#define DUREE_BASE_ALLUME 500
5
#define DUREE_BASE_ETEINT 500
6
int i=0;
7
int motif[10];
8
9
/* Definition des fonctions */
10
void allume(){
11
    digitalWrite(PORT_LED, ALLUME);   // Allume la LED
12
    delay(DUREE_BASE_ALLUME); 
13
}
14
void eteint(){
15
    digitalWrite(PORT_LED, ETEINT);    // Eteint la LED
16
    delay(DUREE_BASE_ETEINT);
17
}
18
void commande_led(int m){ //Permet le choix allume/eteint en fonction du paramètre transmis
19
 if(m == 1){
20
    allume();
21
  }
22
  else{
23
    eteint();
24
  }
25
}
26
/* Programme principal */
27
void setup() {
28
  pinMode(PORT_LED, OUTPUT);
29
  Serial.begin(9600);//Initialise le port série (pour l'affichage dans la fenêtre Moniteur)
30
  motif[0] = 1;
31
  motif[1] = 1;
32
  motif[2] = 0;
33
  motif[3] = 1;
34
  motif[4] = 1;
35
  motif[5] = 0;
36
  motif[6] = 1;
37
  motif[7] = 1;
38
  motif[8] = 0;
39
  motif[9] = 1;
40
}
41
void loop() {
42
  if(i > 9) {i = 0;}
43
     commande_led(motif[i]);
44
  i++;
45
}