Advertisement
learnelectronics

ESP32 Servo control

Jan 2nd, 2018
3,271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. /*
  2.  * ESP32 Servo control
  3.  *
  4.  * learnelectronics
  5.  * 2 JAN 2018
  6.  *
  7.  * www.youtube.com/c/learnelectronics
  8.  *
  9.  *
  10.  * Sketch adapted from original code by MJRobot
  11.  *
  12.  */
  13.  
  14.  
  15.  #define ANALOG_PIN_0 32                          //we need to tell the ESP32 what pin we want for the analog read
  16.  int analog_value = 0;                            //set our initial value as 0
  17.  
  18.  
  19.  #define SERVO_PIN 5                              //we need to tell the ESP32 what pin the servo is on
  20.  int freq = 50;                                   //servos operate @ 50Hz so we ned to set the freq to that value
  21.  int channel = 0;                                 //which channel do we want to use
  22.  int resolution = 8;                              //set out resolution for a resonable value
  23.  int dutyCycle = 21;                              //this is about the halfway point (90deg)
  24.  
  25.  void setup()
  26.  {
  27.   Serial.begin(115200);                           //serial comms @ 115200
  28.   delay(1000);                                    // wait one
  29.   Serial.println("ESP32 Servo Control");          //intro
  30.   ledcSetup(channel, freq, resolution);           //we need to setup the ledc function with channel, freq, and resultion
  31.   ledcAttachPin(SERVO_PIN,channel);               //then we attach our servo
  32.   ledcWrite(channel,dutyCycle);                   //reset the servo
  33.  }
  34.  
  35.  void loop()
  36.  {
  37.   analog_value = analogRead(ANALOG_PIN_0);        //read the value from the pot
  38.   Serial.print(analog_value);                     //print the value to serial
  39.   Serial.print(" Duty Cycle -> ");                //print words
  40.   Serial.println(dutyCycle);                      //print out the duty cycle
  41.   dutyCycle = map(analog_value, 0, 4095, 10, 33); //calculate duty cycle
  42.   ledcWrite(channel, dutyCycle);                  //write the current duty cycle to the servo
  43.   delay(50);                                      //wait 50mS
  44.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement