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: 98
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