Skip to content

Instantly share code, notes, and snippets.

@elktros
Created March 12, 2021 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elktros/d890053823a749972fc70fdfc73e041c to your computer and use it in GitHub Desktop.
Save elktros/d890053823a749972fc70fdfc73e041c to your computer and use it in GitHub Desktop.
Code for controlling brightness of LED using ESP32 ADC and PWM.
#define ADCPIN A0
const int LEDPin = 16; /* GPIO16 */
uint16_t dutyCycle;
const int PWMFreq = 5000;
const int PWMChannel = 0;
const int PWMResolution = 12;
const int MAX_DUTY_CYCLE = (int)(pow(2, PWMResolution) - 1);
//const int ADC_RESOLUTION = 4095;
void setup()
{
/* Initialize PWM Channels with Frequency and Resolution */
ledcSetup(PWMChannel, PWMFreq, PWMResolution);
/* Attach the LED PWM Channel to the GPIO Pin */
ledcAttachPin(LEDPin, PWMChannel);
}
void loop()
{
/* Read Analog Input from three ADC Inputs */
dutyCycle = analogRead(ADCPIN);
/* Map ADC Output to maximum possible dutycycle */
//redDutyCycle = map(redDutyCycle, 0, ADC_RESOLUTION, 0, RED_MAX_DUTY_CYCLE);
/* Set PWM Output of Channel with desired dutycycle */
ledcWrite(PWMChannel, dutyCycle);
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment