ESP32 PWM Output

Schematics, Example Code and Q&A
Daniel
Posts: 133
Joined: Tue Nov 13, 2012 2:10 pm

ESP32 PWM Output

Unread post by Daniel »

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 );
}
Airhead
Posts: 5
Joined: Sun Feb 24, 2019 4:43 pm

Re: ESP32 PWM Output

Unread post by Airhead »

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"?
Daniel
Posts: 133
Joined: Tue Nov 13, 2012 2:10 pm

Re: ESP32 PWM Output

Unread post by Daniel »

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.
Post Reply