This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
in202:seance_4:led [2021/04/11 16:14] bmonsuez created |
in202:seance_4:led [2022/11/18 10:47] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
====== Création d'une classe LED ====== | ====== Création d'une classe LED ====== | ||
+ | |||
+ | ====== Pourquoi créer une classe LED ====== | ||
+ | |||
+ | Quand nous analysons le code : | ||
+ | |||
+ | <code cpp> | ||
+ | /* | ||
+ | Blink | ||
+ | */ | ||
+ | |||
+ | // the setup function runs once when you press reset or power the board | ||
+ | void setup() { | ||
+ | // initialize digital pin LED_BUILTIN as an output. | ||
+ | pinMode(LED_BUILTIN, OUTPUT); | ||
+ | } | ||
+ | |||
+ | // the loop function runs over and over again forever | ||
+ | void loop() { | ||
+ | digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) | ||
+ | delay(1000); // wait for a second | ||
+ | digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW | ||
+ | delay(1000); // wait for a second | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | Nous voyons que le pseudo-code équivalent serait : | ||
+ | |||
+ | <code> | ||
+ | Initialisation: | ||
+ | port LED_BUILDIN est un composant LED. Donc le port est en écriture. | ||
+ | | ||
+ | Loop: | ||
+ | allume la LED. | ||
+ | attend une seconde. | ||
+ | eteint la LED. | ||
+ | attend une seconde. | ||
+ | </code> | ||
+ | |||
+ | Si nous avions une classe ''Led'', nous pourrions réécrire le code comme suit : | ||
+ | |||
+ | <code cpp> | ||
+ | |||
+ | Led builtinLed(LED_BUILTIN); | ||
+ | // Crée un objet LED connecté au port LED_BUILTIN | ||
+ | | ||
+ | void setup() {} | ||
+ | |||
+ | void loop() { | ||
+ | builtinLed = true; | ||
+ | delay(1000); | ||
+ | builtinLed = false; | ||
+ | delay(1000); | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | Le code serait nettement plus lisible. | ||
+ | |||
+ | On pourrait même inverser l'état de la led et le code se réduirait à : | ||
+ | |||
+ | <code cpp> | ||
+ | |||
+ | Led builtinLed(LED_BUILTIN); | ||
+ | // Crée un objet LED connecté au port LED_BUILTIN | ||
+ | | ||
+ | void setup() {} | ||
+ | |||
+ | void loop() { | ||
+ | builtinLed = !(builtinLed; | ||
+ | delay(1000); | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | |||
+ | ====== Action : Créer une classe Led ====== | ||
+ | |||
+ | Nous vous proposons de créer une classe ''Led'' ayant l'entête suivante : | ||
+ | |||
+ | <code cpp> | ||
+ | class Led | ||
+ | { | ||
+ | public: | ||
+ | Led(uint32_t thePin); | ||
+ | Led& operator = (bool isOn); | ||
+ | operator bool() const; | ||
+ | Led& operator ~(); // Optionel. | ||
+ | }; | ||
+ | <code> | ||
+ | |||
+ | |||
+ | |||
+ | </code> | ||
+ | |||
+ | |||
+ | | ||