Skip to content

Instantly share code, notes, and snippets.

@elktros
Created March 12, 2021 15:19
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/2e7173fb9fc77d8118abe85b45a471eb to your computer and use it in GitHub Desktop.
Save elktros/2e7173fb9fc77d8118abe85b45a471eb to your computer and use it in GitHub Desktop.
ESP32 PWM ADC
const int redLEDPin = 16; /* GPIO16 */
const int greenLEDPin = 17; /* GPIO17 */
const int blueLEDPin = 4; /* GPIO4 */
uint16_t redDutyCycle;
uint16_t greenDutyCycle;
uint16_t blueDutyCycle;
const int redPWMFreq = 5000; /* 5 KHz */
const int redPWMChannel = 0;
const int redPWMResolution = 12;
const int RED_MAX_DUTY_CYCLE = (int)(pow(2, redPWMResolution) - 1);
const int greenPWMFreq = 8000; /* 8 KHz */
const int greenPWMChannel = 2;
const int greenPWMResolution = 13;
const int GREEN_MAX_DUTY_CYCLE = (int)(pow(2, greenPWMResolution) - 1);
const int bluePWMFreq = 10000; /* 10 KHz */
const int bluePWMChannel = 4;
const int bluePWMResolution = 14;
const int BLUE_MAX_DUTY_CYCLE = (int)(pow(2, bluePWMResolution) - 1);
const int ADC_RESOLUTION = 4095; /* 12-bit */
void setup()
{
/* Initialize Serial Port */
Serial.begin(115200);
/* Initialize PWM Channels with Frequency and Resolution */
ledcSetup(redPWMChannel, redPWMFreq, redPWMResolution);
ledcSetup(greenPWMChannel, greenPWMFreq, greenPWMResolution);
ledcSetup(bluePWMChannel, bluePWMFreq, bluePWMResolution);
/* Attach the LED PWM Channel to the GPIO Pin */
ledcAttachPin(redLEDPin, redPWMChannel);
ledcAttachPin(greenLEDPin, greenPWMChannel);
ledcAttachPin(blueLEDPin, bluePWMChannel);
}
void loop()
{
/* Read Analog Input from three ADC Inputs */
redDutyCycle = analogRead(A0);
greenDutyCycle = analogRead(A3);
blueDutyCycle = analogRead(A4);
/* Map ADC Output to maximum possible dutycycle */
//redDutyCycle = map(redDutyCycle, 0, ADC_RESOLUTION, 0, RED_MAX_DUTY_CYCLE);
greenDutyCycle = map(greenDutyCycle, 0, ADC_RESOLUTION, 0, GREEN_MAX_DUTY_CYCLE);
blueDutyCycle = map(blueDutyCycle, 0, ADC_RESOLUTION, 0, BLUE_MAX_DUTY_CYCLE);
/* Set PWM Output of Channel with desired dutycycle */
ledcWrite(redPWMChannel, redDutyCycle);
ledcWrite(greenPWMChannel, greenDutyCycle);
ledcWrite(bluePWMChannel, blueDutyCycle);
Serial.println("RED -- GREEN -- BLUE");
Serial.print(redDutyCycle);
Serial.print(" -- ");
Serial.print(greenDutyCycle);
Serial.print(" -- ");
Serial.print(blueDutyCycle);
Serial.print("\n");
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment