Page 1 of 1

ESP32 PWM Output

PostPosted: Sun Apr 16, 2017 5:03 pm
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 );

Re: ESP32 PWM Output

PostPosted: Wed Feb 27, 2019 11:56 pm
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"?

Re: ESP32 PWM Output

PostPosted: Thu Mar 28, 2019 12:22 pm
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.