How to get a 4 / 8 MHz clock from PWM?

Posts: 13
Joined: Fri Sep 21, 2018 1:21 pm

How to get a 4 / 8 MHz clock from PWM?

Postby nockieboy » Fri Sep 21, 2018 1:35 pm


I'm extremely new to the ESP32 and micro-controllers in general. I'm using the Arduino IDE for the ESP32. Basically, all I want is an accurate 4 MHz or 8 MHz, 50% duty, clock signal from my ESP32.

I have followed several tutorials using LEDC to set up PWM signals for LED dimming etc. and, as best I can tell, the ESP32 should be more than capable of producing an 8 MHz PWM signal with up to 3-bit resolution - although I only need 50% duty, so I'm trying for a 1-bit resolution.

When I check the signal I'm getting on my oscilloscope, the results are definitely NOT 4 or 8 MHz clock signals. Either my code is wrong, or I'm really not reading my oscilloscope properly (which is entirely possible - it's a really old 'scope and I'm no electronics engineer). However, I thought I'd ask here to see if there's any issues with my code:

Code: Select all

// PWM vars
int freq = 1000000;   // 4 MHz frequency initially
int PWMChannel = 0;   // PWM channel
int resolution = 1;   // Only need 50% duty cycle, this should allow up to 40 MHz clock speed?
const int PWM_1 = 13;  // GPIO pin to use for PWM signal

void setup() {
  // Initialise PWM
  ledcSetup(PWMChannel, freq, resolution);
  ledcAttachPin(PWM_1, PWMChannel);
  // Set PWM channel
  ledcWrite(PWMChannel, 1);
Elsewhere in the code, I have a couple of functions to change the frequency:

Code: Select all

ledcSetup(PWMChannel, 2000000, resolution); // Seems to be come out at approx 7.2 MHz on the 'scope
ledcWrite(PWMChannel, 1);
And this one:

Code: Select all

ledcSetup(PWMChannel, 1000000, resolution); // Very approximately 4 MHz
ledcWrite(PWMChannel, 1);
I arrived at frequencies of 1000000 and 2000000 for ledcSetup by experimentation. I'd assumed originally that 8000000 and 4000000 should have been the right ones to use?

Can anyone shine a light on what's going on here? I'm entirely prepared to accept that it's my oscilloscope skills that are miserably below par, but would appreciate confirmation that the code is correct, or not as the case may be! :?


Who is online

Users browsing this forum: No registered users and 6 guests