Skip to content

Commit 00d50fa

Browse files
committed
samples: fade_led: Refactor LED fade logic
Move the LED fade logic from the main loop into a separate update_fade_statefunction to improve code modularity and reusability. This change makes the code easier to maintain and extend with new fade patterns. Signed-off-by: Gomaa Mohammed Eldebaby <[email protected]>
1 parent 85e1353 commit 00d50fa

File tree

1 file changed

+20
-15
lines changed
  • samples/basic/fade_led/src

1 file changed

+20
-15
lines changed

samples/basic/fade_led/src/main.c

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,25 @@ static const struct pwm_dt_spec pwm_leds[] = {LISTIFY(MAX_LEDS, PWM_LED, ())};
2424
#define NUM_STEPS 50U
2525
#define SLEEP_MSEC 25U
2626

27+
static void update_fade_state(size_t i, uint32_t *pulse_widths, uint32_t *steps, uint8_t *dirs)
28+
{
29+
if (dirs[i] == 1) {
30+
if (pulse_widths[i] + steps[i] >= pwm_leds[i].period) {
31+
pulse_widths[i] = pwm_leds[i].period;
32+
dirs[i] = 0U;
33+
} else {
34+
pulse_widths[i] += steps[i];
35+
}
36+
} else {
37+
if (pulse_widths[i] <= steps[i]) {
38+
pulse_widths[i] = 0;
39+
dirs[i] = 1U;
40+
} else {
41+
pulse_widths[i] -= steps[i];
42+
}
43+
}
44+
}
45+
2746
int main(void)
2847
{
2948
uint32_t pulse_widths[ARRAY_SIZE(pwm_leds)];
@@ -52,21 +71,7 @@ int main(void)
5271
printk("LED %d: Using pulse width %d%%\n", i,
5372
100 * pulse_widths[i] / pwm_leds[i].period);
5473

55-
if (dirs[i] == 1) {
56-
if (pulse_widths[i] + steps[i] >= pwm_leds[i].period) {
57-
pulse_widths[i] = pwm_leds[i].period;
58-
dirs[i] = 0U;
59-
} else {
60-
pulse_widths[i] += steps[i];
61-
}
62-
} else {
63-
if (pulse_widths[i] <= steps[i]) {
64-
pulse_widths[i] = 0;
65-
dirs[i] = 1U;
66-
} else {
67-
pulse_widths[i] -= steps[i];
68-
}
69-
}
74+
update_fade_state(i, pulse_widths, steps, dirs);
7075
}
7176

7277
k_sleep(K_MSEC(SLEEP_MSEC));

0 commit comments

Comments
 (0)