Hey guys!
I'm trying to pretty much make a light that turns on with a button, and then when it's on, you can change the brightness using a potentiometer. Should be simple, right? I've got it sort of up and running, but it's only changing the brightness when you press the button, as opposed to changing continuously after the button has been pressed, and until it gets pressed again. Any clues as to what I'm doing wrong? Popped my code beneath. I've Frankensteined it together from various sources, but it seems like it's close? Would love some help, thank you :).
int inPin = 2; //button pin
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to
int state = HIGH;
int reading;
int previous = LOW;
long time = 0;
long debounce = 200;
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
pinMode (inPin, INPUT);
}
void loop() {
reading = digitalRead (inPin); //find out what the button is up to
outputValue = map(sensorValue, 0, 1023, 0, 255); //mapping analog range to what can be output.
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
sensorValue = analogRead(analogInPin); //reading pot value, and storing it in 'sensorValue'.
analogWrite(analogOutPin, outputValue); //assign pot value to LED.
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
time = millis();
}
previous = reading;
}