Skip to content

Commit c153f5f

Browse files
committed
Allow to change default PWM frequency
Default is PWM_FREQUENCY (1000Hz). Call `analogWriteFrequency(freq)` before `analogWrite(pin, val)` to use the new frequency. Note that no compute/check is performed to ensure the requested freq. This is dependent on how the computation is currently done in analogWrite. This limitation will be remove when Timer management will be done. Signed-off-by: Frederic.Pillon <[email protected]>
1 parent 36d47f1 commit c153f5f

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

Diff for: cores/arduino/wiring_analog.c

+7-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ uint32_t g_anOutputPinConfigured[MAX_NB_PORT] = {0};
2929

3030
static int _readResolution = 10;
3131
static int _writeResolution = 8;
32+
static uint32_t _writeFreq = PWM_FREQUENCY;
3233

3334
void analogReadResolution(int res)
3435
{
@@ -40,6 +41,11 @@ void analogWriteResolution(int res)
4041
_writeResolution = res;
4142
}
4243

44+
void analogWriteFrequency(uint32_t freq)
45+
{
46+
_writeFreq = freq;
47+
}
48+
4349
static inline uint32_t mapResolution(uint32_t value, uint32_t from, uint32_t to)
4450
{
4551
if (from == to) {
@@ -97,7 +103,7 @@ void analogWrite(uint32_t ulPin, uint32_t ulValue)
97103
set_pin_configured(p, g_anOutputPinConfigured);
98104
}
99105
ulValue = mapResolution(ulValue, _writeResolution, PWM_RESOLUTION);
100-
pwm_start(p, PWM_FREQUENCY * PWM_MAX_DUTY_CYCLE,
106+
pwm_start(p, _writeFreq * PWM_MAX_DUTY_CYCLE,
101107
PWM_MAX_DUTY_CYCLE,
102108
ulValue, do_init);
103109
} else { //DIGITAL PIN ONLY

Diff for: cores/arduino/wiring_analog.h

+8
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,14 @@ extern void analogReadResolution(int res);
6969
*/
7070
extern void analogWriteResolution(int res);
7171

72+
/*
73+
* \brief Set the frequency of analogWrite. Default is PWM_FREQUENCY (1000) in Hertz.
74+
*
75+
* \param freq
76+
*/
77+
extern void analogWriteFrequency(uint32_t freq);
78+
79+
7280
extern void analogOutputInit(void) ;
7381

7482
#ifdef __cplusplus

0 commit comments

Comments
 (0)