Dimming led with one button and toggle on/off led with same button

look this over. it's not what you asking for. i tested this on my hardware (MyHW)

it shows how to cleanly detect a button press and how to use a timestamp to recognize if the button held long enough

#define MyHW
#ifdef MyHW
const int button  = A1;
const int led     = 10;;

#else
const int button  = 2;
const int button1 = 3;
const int led = 4;
#endif

byte butLst;
unsigned long msecBut;
const unsigned long msecLong = 300;

enum { Off = HIGH, On = LOW };

enum { ButNone, ButPress };
int state;

const int LedPwmOff = 0;
const int LedPwmOn  = 255;
int ledPwm = LedPwmOff;

// -----------------------------------------------------------------------------
void loop ()
{
    unsigned long msec = millis ();

    if (ButPress == state && msec - msecBut >= msecLong)  {
        state = ButNone;

        if (LedPwmOff == ledPwm)
            ledPwm = LedPwmOn;
        else
            ledPwm = LedPwmOff;
        analogWrite (led, ledPwm);
    }

    byte but = digitalRead (button);
    if (butLst != but) {        // state change
        butLst = but;
        delay (20);             // debounce

        if (LOW == but) {       // press
            msecBut = msec;
            state   = ButPress;
        }
        else {                  // release
            msecBut = 0;
            state   = ButNone;
        }
    }

}

// -----------------------------------------------------------------------------
void setup ()
{
    pinMode (button, INPUT_PULLUP);
    butLst = digitalRead (button);
    state  = ButNone;

    analogWrite (led, LedPwmOff);
}

Yes I understand the code i write it, the only problem is how to combine dimming led and turning led on/off.
I tried more options for combining but it isnt working i dont know how to do it, I think I need time condition, I just don't know how to do it.

thanks for the help, but I don't really know how to help myself much with this

The code from post#9 works very well on an Uno.
Assuming Arduino Uno, because you didn't tell us which Arduino you're using.

A short press turns the LED on/off, and a long press dims the led.
A second long press dims the LED the other way.
Fully tested, so check your build if it doesn't work.
Leo..

i found that the code in post #9 works and should be studied.

at least on my board, where the LED is active LOW, the PWM value needs to be very high >250 for it to dim and practically full on at 220.

need to understand how to test it (i added prints to report the pwm value to see, not guess, its affect.

@Wawa 's approach is interesting. it's absolutely worth studying and understanding

but it probably couldn't be used if multiple buttons could be used at the same time

I also wrote once a millis() timed version that dims 32 PCA9685 channels with a lookup table for equal brightness steps, which you probably can find on this site if you do a search.
But millis() timing seems too complicated for a beginner with these simple requirements.
Leo..

1 Like

I have arduino UNO, I don't know whay it doesn't works right, I will try it again

Post a picture of the setup, so we can check your connections.
Note that I have used pin2 for the button and pin5 for the LED+resistor.
Leo..

My setup works right, code from post #9 doesnt work, when I download the program the led just stays on, isnt working right.


code from post #9, working pretty good in a simulator..
maybe you need to adjust led or button pin??

OneButtonLedUno

curious, what are those 2 pins i see in pic 2, is shield situated properly??

good luck.. ~q

But in simulator led is just turning on and off, not dimming

sure it does..
first long press brightens, next long press dims..
short presses turn on/off..
hold it down long time..

~q

???

In the sim, did you press/hold the button long enough.
Brightness in the sim is a bit hard to see, but it works.

Where did that board come from (link).
The silkscreen says that the three LEDs are connected to D4, D5, D6.
If so, then the yellow LED should dim.
In the code from post#9 you can change ledPin from 5 to 6, so the green LED dims.
I see that the two buttons are labeled as D2 and D3, so D2 should work.
Leo..

Yea, I changed the pins

Hello!

It's great to see your interest in modifying your program to control a single LED with just one button. I'll be happy to help you with that. Here's an updated code that combines the functionality of both buttons into one:

const int button = 2;
const int led = 6;
int val1;
int inc = 1; // Variable to track whether the LED should be increasing or decreasing in brightness

void setup() {
  pinMode(button, INPUT_PULLUP);
  pinMode(led, OUTPUT);
}

void loop() {
  val1 = digitalRead(button);

  if (val1 == LOW) { // Button is pressed
    if (inc == 1) {
      analogWrite(led, 255); // Turn the LED on at full brightness
      inc = -1; // Set the direction to decrease brightness
    } else {
      analogWrite(led, 0); // Turn the LED off
      inc = 1; // Set the direction to increase brightness
    }

    delay(50); // Small delay to debounce the button
  }

  if (inc == -1) {
    int brightness = analogRead(led); // Read the current LED brightness
    brightness -= 5; // Decrease the brightness gradually
    if (brightness < 0) {
      brightness = 0; // Ensure the brightness does not go below 0
      inc = 1; // Set the direction back to increase brightness
    }
    analogWrite(led, brightness); // Update the LED brightness
    delay(20); // Delay between brightness changes for smoother dimming effect
  }
}

In this updated code, we use the analogWrite function to control the LED brightness instead of turning it on/off directly. When the button is pressed, it checks the current direction of brightness (inc variable) and either turns the LED on at full brightness or turns it off, then changes the direction. By holding the button, the LED gradually decreases in brightness until it reaches 0, at which point it changes the direction back to increasing.

Feel free to adjust the delay values and brightness changes to suit your desired effect.
I hope this will help you.

Hello!

Thanks for your code, but it doesnt works right, when i press the button led turns on and if I press it again it turns off but not everytime.
If i hold down the button, the led is blinking, if I release the button led goes off.

Did you find the solution already to trigger two ( or more ) actions with one button?
If not, search the forum with the following text : "button pressed more than 2 seconds do somethingelse". Two replies down you will find code from Maercello.Romani. Very very well done!!
I made domotica systems on Mega with this code as the basis, I use longpress to start dimming. If the LED is at max, the increase/decrease direction gets reversed. The shortkeypress function is of course for switching ON and OFF. If the level of the LED at switch OFF is kept in a variable, the LED can be switched on again with the same value.
As I understood your request, this should help.

const byte buttonPin = 2;
const byte ledPin = 3;


bool ledOn, dimDown;
byte pwmValue = 0;
int i = 0;
int lastvalue;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode (ledPin, OUTPUT);

}

void loop() {

  if (!digitalRead(buttonPin)) delay(20);
  if (!digitalRead(buttonPin)) {
    delay(500);
    if (!digitalRead(buttonPin)) {
      while (!digitalRead(buttonPin)) {
        if (dimDown) {
          if (pwmValue > 0) pwmValue--;
        }
        else {
          if (pwmValue < 255) pwmValue++;
        }
        lastvalue = pwmValue;
        analogWrite(ledPin, pwmValue);
        delay(15);
      }
      dimDown = !dimDown;
    } else {
      if (ledOn) {
          
          while (i < pwmValue) {
            pwmValue--;
           analogWrite (ledPin,pwmValue);
           delay(15);

          }
           ledOn = false;
        dimDown = false;
      } else {

          while (pwmValue < lastvalue) {
          pwmValue++;
           analogWrite (ledPin,pwmValue);
           delay(15);

          }

        ledOn = true;
      }
    }
  }
}


This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.