ESP32 PWM Output

Schematics, Example Code and Q&A

ESP32 PWM Output

Postby Daniel » Sun Apr 16, 2017 5:03 pm

analogWrite is not implemented in the Arduino environment. There is a much better set of PWM controllers available. The code below demonstrates how to get PWM output on a pin.

Code: Select all
// Code for PWM drive of a small motor
// ESP32 does not support analogWrite but has ledcWrite instead
// There are 16 PWM channels numbered 0-15
// Resulotion is programmable.  I tested 5-12 bits
// Frequency is programmable.  I tested 1kHz to 100kHz, all accurate
// This code is placed in the public domain

#define MotorPin 23
#define pwmCh 0
#define pwmResolution 8   // 8 bit resolution
#define pwmFrequency  10000

void setup() {
  // Choose the pwm controller to use on the IO-pin
  ledcAttachPin(MotorPin, pwmCh);
  // Set the frequency and resolution
  ledcSetup(pwmCh, pwmFrequency, pwmResolution); // 10 kHz PWM, 8-bit resolution
  // Set the duty cycle
  ledcWrite(pwmCh, 127);

uint8_t dutyCycle = 12 ;
void loop() {
  // increase the duty cycle every 20ms
  ledcWrite(pwmCh, dutyCycle++ );
  delay( 20 );
Posts: 109
Joined: Tue Nov 13, 2012 5:10 pm

Re: ESP32 PWM Output

Postby Airhead » Wed Feb 27, 2019 11:56 pm

I'm finding that the LEDs don't turn OFF, but stay on if dimly, with dutyCycle = 255 (they're pulled up, so full on is 0).

How can I effect full off? Once a GPIO gets "attached" [ledcAttachPin(ledPin, ledChannel);], how can I "unAttach"?
Posts: 1
Joined: Sun Feb 24, 2019 7:43 pm

Re: ESP32 PWM Output

Postby Daniel » Thu Mar 28, 2019 12:22 pm

When you want the LEDs completely off, make the pin an input. That's guaranteed to turn them off.

I never noticed this till now.
Posts: 109
Joined: Tue Nov 13, 2012 5:10 pm

Return to ESP32 Related

Who is online

Users browsing this forum: No registered users and 1 guest