LED Brightness Control Using Potentiometer

AliToufaily
AliToufaily

Solving Approach:

How do you plan to solve it?

Connect potentiometer to analogInput, use the measured value (0 to 5V corresponds to 0-1023 analog measurement) to drive the output on pwm pin 9 (0 to 255).

 

Code

// C++ code
//
#define inputPin	0
#define pwmPin  9

int inputSpread = (1023);
int analogInput = 0;

void setup()
{
  pinMode(pwmPin, OUTPUT);
  analogWrite(pwmPin, 0);

  analogInput = analogRead(inputPin);

  Serial.begin(9600);
  Serial.print("AnalogInput: "); Serial.println(analogInput);

}


void loop()
{
  int newValue;
  int output;
  
  newValue= analogRead(inputPin);

  if (newValue != analogInput) {
    analogInput = newValue;
    Serial.print("AnalogInput: "); Serial.print(analogInput);
    output = 255.0 * analogInput / inputSpread;  // float arithmatics 
    output &= 0xFF ; // cutoff at 8-bits
    Serial.print(" PWM Output: "); Serial.println(output);
    analogWrite(pwmPin, output);
  }
}

Output

Video

Add video of output (know more)

 

 

 

 

Photo of Output

Add a photo of your hardware showing the output.

 

 

 

 

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!