Crée une fonction afficher_batterie(int pourcentage) qui affiche :
- 4 LEDs vertes si > 75%
- 3 LEDs vertes si > 50%
- 2 LEDs jaunes si > 25%
- 1 LED rouge clignotante si ≤ 25%
Solution :
#include <stdio.h>
#include <stdint.h>
/* Stub for playground simulation */
#define NUM_LEDS 4
struct led_rgb { uint8_t r; uint8_t g; uint8_t b; };
static struct led_rgb pixels[NUM_LEDS];
static void *strip = NULL;
static int clignotant = 0;
static void led_strip_update_rgb(void *dev, struct led_rgb *px, int n)
{
(void)dev;
printf("LED strip update (%d LEDs):\n", n);
for (int i = 0; i < n; i++) {
printf(" LED %d: r=%u g=%u b=%u\n", i, px[i].r, px[i].g, px[i].b);
}
}
void eteindre_tout(void)
{
for (int i = 0; i < NUM_LEDS; i++) {
pixels[i].r = 0;
pixels[i].g = 0;
pixels[i].b = 0;
}
}
void afficher_batterie(int pourcentage)
{
eteindre_tout();
if (pourcentage > 75) {
/* 4 LEDs vertes */
for (int i = 0; i < 4; i++) {
pixels[i].g = 255;
}
} else if (pourcentage > 50) {
/* 3 LEDs vertes */
for (int i = 0; i < 3; i++) {
pixels[i].g = 255;
}
} else if (pourcentage > 25) {
/* 2 LEDs jaunes */
for (int i = 0; i < 2; i++) {
pixels[i].r = 255;
pixels[i].g = 128;
}
} else {
/* 1 LED rouge clignotante */
clignotant = !clignotant;
if (clignotant) {
pixels[0].r = 255;
}
}
led_strip_update_rgb(strip, pixels, NUM_LEDS);
}
int main(void)
{
printf("--- Batterie 80%% ---\n");
afficher_batterie(80);
printf("--- Batterie 60%% ---\n");
afficher_batterie(60);
printf("--- Batterie 30%% ---\n");
afficher_batterie(30);
printf("--- Batterie 10%% (appel 1) ---\n");
afficher_batterie(10);
printf("--- Batterie 10%% (appel 2) ---\n");
afficher_batterie(10);
return 0;
}
Solution copiée dans l'éditeur.