I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!
It worked generally but sometimes while turning the potentiometer, the LED would be stuck at a fixed level of brightness. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.
I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?
*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.
-----------------------------Fade sketch edited by me----------------------
/*
Fade, edited with maximum intensity controlled by potentiometer reading
*/
int led = 11; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
int potPin = A0; // set the pin that reads the potentiometer voltage
int potValue = 0; // declare and initialize potValue
int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
//read the voltage at the pot
potValue = analogRead(potPin);
//convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
potValueConverted = round(potValue/4);
// set the brightness of pin 11:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
Serial.println(brightness);
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= potValueConverted) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}