ESP32C3 cannot drive a servo and pwm output correctly

OK - I think I have it now…
I took the examples for multiple servos and pwm from the ESP32Servo library and cobbled together the below code. At first, it did not work - until I attached the pwm pin before attaching the servo - now it works. Thanks again for the help…



 /* modified from the examples in the 
  * ESP32 Servo Library
  */
 
 #include <ESP32Servo.h>
#include <ESP32PWM.h>


 // create  servo object 
 Servo servo1;

 // Published values for SG90 servos; adjust if needed
 int minUs = 1000;
 int maxUs = 2000;
 
 // These are all GPIO pins on the ESP32
 // Recommended pins include 2,4,12-19,21-23,25-27,32-33 
 int servo1Pin = 7;
 int LedPin=21;
 
 int pos = 0;      // position in degrees
 ESP32PWM pwm;

 void setup() {
     // Allow allocation of all timers
     ESP32PWM::allocateTimer(0);
     ESP32PWM::allocateTimer(1);
     ESP32PWM::allocateTimer(2);
     ESP32PWM::allocateTimer(3);
     Serial.begin(115200);
     servo1.setPeriodHertz(50);      // Standard 50hz servo
    
 pwm.attachPin(LedPin, 10000);//10khz  // important to do this before the servo attach!!!!
  servo1.attach(servo1Pin, minUs, maxUs);
 }
 
 void loop() {
 
     for (pos = 0; pos <= 180; pos += 1) { // sweep from 0 degrees to 180 degrees
         // in steps of 1 degree
         servo1.write(pos);
         delay(1);             // waits 20ms for the servo to reach the position
     }
     for (pos = 180; pos >= 0; pos -= 1) { // sweep from 180 degrees to 0 degrees
         servo1.write(pos);
         delay(1);
     }
 
  

// fade the LED on thisPin from off to brightest:
	for (float brightness = 0; brightness <= 0.5; brightness += 0.001) {
		// Write a unit vector value from 0.0 to 1.0
		pwm.writeScaled(brightness);
		delay(2);
	}
	
	for (float brightness = 0.5; brightness >= 0; brightness -= 0.001) {
        	pwm.writeScaled(brightness);
		delay(2);
	}

 
     delay(1000);
 
 }
 

1 Like