Changing brightness of LED with switch


hey guys!

i'm trying pretty make light turns on button, , when it's on, can change brightness using potentiometer. should simple, right? i've got sort of , running, it's changing brightness when press button, opposed changing continuously after button has been pressed, , until gets pressed again. clues i'm doing wrong? popped code beneath. i've frankensteined various sources, seems it's close? love help, thank :).




int inpin = 2; //button pin
const int analoginpin = a0;  // analog input pin potentiometer attached to
const int analogoutpin = 9; // analog output pin led attached to

int state = high;
int reading;
int previous = low;

long time = 0;
long debounce = 200;

int sensorvalue = 0;        // value read pot
int outputvalue = 0;        // value output pwm (analog out)

void setup() {
  // initialize serial communications @ 9600 bps:
  serial.begin(9600);
  pinmode (inpin, input);
}

void loop() {
 
  reading = digitalread (inpin); //find out button to
  outputvalue = map(sensorvalue, 0, 1023, 0, 255);  //mapping analog range can output.
 
  if (reading == high && previous == low && millis() - time > debounce) {
  sensorvalue = analogread(analoginpin);         //reading pot value, , storing in 'sensorvalue'.   
 
  analogwrite(analogoutpin, outputvalue);     //assign pot value led.     

  // print results serial monitor:
  serial.print("sensor = " );                       
  serial.print(sensorvalue);     
  serial.print("\t output = ");     
  serial.println(outputvalue);   

  // wait 2 milliseconds before next loop
  // analog-to-digital converter settle
  // after last reading:
  delay(2);                     
   

    time = millis();   
  }

  previous = reading;
 
 
 
 
}

some bugs:

  outputvalue = map(sensorvalue, 0, 1023, 0, 255);  //mapping analog range can output.
this makes sense after sensorvalue has been read.
 
  if (reading == high && previous == low && millis() - time > debounce) {
this condition enters block if switch pressed. use variable, ledon, remember whether led switched on or off. toggle variable whenever above conditions true. perform remaining statements when ledon true.

  sensorvalue = analogread(analoginpin);         //reading pot value, , storing in 'sensorvalue'.
now can map sensorvalue , set brightness accordingly.
 


Arduino Forum > Using Arduino > Sensors > Changing brightness of LED with switch


arduino

Comments