/**
* Reads a potentiometer on A5 and uses the value to control
* LED brightness via PWM on GPIO 13.
*
* Demonstrates: analogRead (12-bit), map(), ledcWrite (8-bit PWM),
* and preprocessor defines for portable code.
*
* See: https://makeabilitylab.github.io/physcomp/esp32/pot-fade
*/
// Preprocessor defines for cross-platform portability ---
#if defined(ESP32)
const int MAX_ANALOG_VAL = 4095; // ESP32 has a 12-bit ADC (0-4095)
#else
const int MAX_ANALOG_VAL = 1023; // AVR Arduinos have a 10-bit ADC (0-1023)
#endif
const int LED_OUTPUT_PIN = 1;
const int POT_INPUT_PIN = 4;
const int PWM_FREQ = 5000; // 5 kHz PWM frequency
const int PWM_RESOLUTION = 8; // 8-bit resolution: duty cycle 0-255
const int MAX_DUTY_CYCLE = (1 << PWM_RESOLUTION) - 1; // 2^8 - 1 = 255
void setup() {
Serial.begin(115200);
// Attach PWM to the LED pin (v3.x API — channel assigned automatically)
ledcAttach(LED_OUTPUT_PIN, PWM_FREQ, PWM_RESOLUTION);
}
void loop() {
// Read the potentiometer (returns 0-4095 on the ESP32's 12-bit ADC)
int potVal = analogRead(POT_INPUT_PIN);
// Map the 12-bit input (0-4095) to the 8-bit PWM range (0-255)
int dutyCycle = map(potVal, 0, MAX_ANALOG_VAL, 0, MAX_DUTY_CYCLE);
// Set the LED brightness
ledcWrite(LED_OUTPUT_PIN, dutyCycle);
// Print both values for debugging (use Serial Plotter to visualize!)
Serial.print("PotVal:");
Serial.print(potVal);
Serial.print(", DutyCycle:");
Serial.println(dutyCycle);
delay(10); // Small delay for stable readings
}