Button to turn on/off potentiometer controlled LED

Essentially I am wanting to combine the StateChangeDectection (Digital) and Calibration (Analog) examples. I am wanting a press and release of a button to switch the LED off or have the brightness controlled by the potentiometer. However, pressing the button doesnt seem to change the state of the LED in a controlled manner, i.e. after pressing the button 4 times turn off or after 1 press turn on.

I'm not sure if its my code (probably is) or the setup of my breadboard. I have attached my setup and the code below.

Any ideas?

// These constants won't change:
const int sensorPin = A0;    // pin that the sensor is attached to
const int ledPin = 9;        // pin that the LED is attached to
const int buttonPin = 4;     // pin button attached to

// variables:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
int buttonState = 0;      // initial state of button
int lastState = 0;        //initial last state of button
int counter = 0;          // start counter at 0

void setup() {
  // turn on built in LED to signal the start of the calibration period:
  pinMode(13, OUTPUT);
  pinMode(buttonPin,INPUT);
  digitalWrite(13, HIGH);
  analogWrite(ledPin,0);

  // calibrate during the first ten seconds
  while (millis() < 10000) {
    sensorValue = analogRead(sensorPin);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }

  // signal the end of the calibration period
  digitalWrite(13, LOW);
}

void loop() {
  // read the sensor and button:
  sensorValue = analogRead(sensorPin);
  buttonState = digitalRead(buttonPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);

  
if (buttonState != lastState) 
{
  if (buttonState == HIGH) {
      counter++;
  }

  delay(50);    
}
  lastState = buttonState;
  
if (counter % 2 == 1) {
  analogWrite(ledPin,sensorValue);  
} else {
    analogWrite(ledPin,0); 
}

Hi,
OPs Circuit..


You button is connected to Pin2 not Pin4 as in your code.

Tom... :slight_smile:

The classic error with those tactile switches is to wire them as if they were rotated through +/- 90 degrees. If you use only two diagonally opposite pins, you can't go wrong. From your diagram, it is not clear if this is a problem but if you get any sort of reaction from the button, it is probably correct.