Skip to content

Commit a36ef2a

Browse files
arcaome-no-dev
authored andcommitted
Added LEDC Software Fade example (espressif#202)
* Added LEDC Fade exmaple * Renamed LEDCFade example to LEDCSoftwareFade Added valueMax parameter for ledcAnalogWrite * Remove usage of LED_BUILTIN constant to solve CI errors
1 parent 8c1e701 commit a36ef2a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
LEDC Software Fade
3+
4+
This example shows how to software fade LED
5+
using the ledcWrite function.
6+
7+
Code adapted from original Arduino Fade example:
8+
https://www.arduino.cc/en/Tutorial/Fade
9+
10+
This example code is in the public domain.
11+
*/
12+
13+
// use first channel of 16 channels (started from zero)
14+
#define LEDC_CHANNEL_0 0
15+
16+
// use 13 bit precission for LEDC timer
17+
#define LEDC_TIMER_13_BIT 13
18+
19+
// use 5000 Hz as a LEDC base frequency
20+
#define LEDC_BASE_FREQ 5000
21+
22+
// fade LED PIN (replace with LED_BUILTIN constant for built-in LED)
23+
#define LED_PIN 5
24+
25+
int brightness = 0; // how bright the LED is
26+
int fadeAmount = 5; // how many points to fade the LED by
27+
28+
// Arduino like analogWrite
29+
// value has to be between 0 and valueMax
30+
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) {
31+
// calculate duty
32+
uint32_t duty = (LEDC_BASE_FREQ / valueMax) * min(value, valueMax);
33+
34+
// write duty to LEDC
35+
ledcWrite(channel, duty);
36+
}
37+
38+
void setup() {
39+
// Setup timer and attach timer to a led pin
40+
ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
41+
ledcAttachPin(LED_PIN, LEDC_CHANNEL_0);
42+
}
43+
44+
void loop() {
45+
// set the brightness on LEDC channel 0
46+
ledcAnalogWrite(LEDC_CHANNEL_0, brightness);
47+
48+
// change the brightness for next time through the loop:
49+
brightness = brightness + fadeAmount;
50+
51+
// reverse the direction of the fading at the ends of the fade:
52+
if (brightness <= 0 || brightness >= 255) {
53+
fadeAmount = -fadeAmount;
54+
}
55+
// wait for 30 milliseconds to see the dimming effect
56+
delay(30);
57+
}

0 commit comments

Comments
 (0)