Hello.
I am writing a program in which I use millis. I wanted to write a code that if I hold the button for more than 50 milliseconds and less than 1000 milliseconds, something would happen. But the code is considering only "more than 50 ms" I don't understand what is wrong in my code. I would kindly ask for anybody's help.
for (int i = 0; i < numOfInputs; i++)
{
if (digitalRead(inputPins_) != lastInputState*) _
_ {_ lastDebounceTime = millis(); //lastDebounceTime was set 0 in int _ } if ((millis() - lastDebounceTime) > 50 && (millis() - lastDebounceTime) < 1000 )[/color] { if (digitalRead(inputPins) != inputState) { inputFlags = HIGH; }}}*_
It's best if we can see all of the code, especially in this example since we don't know the data types used or how they are initialized. Before you post your code using code tags, please read the three posts that are at the top of this Forum. They will tell you how to get the best responses to your questions.
Start a timer when the button is pressed. Check the timer when the button is released.
const byte ButtonPin = 2;
const unsigned long DebounceTime = 10;
boolean ButtonWasPressed; // Defaults to 'false'
unsigned long ButtonStateChangeTime = 0; // Debounce timer common to all buttons
unsigned long ButtonPressTime = 0;
void setup()
{
Serial.begin(115200);
pinMode (ButtonPin, INPUT_PULLUP); // Button between Pin and Ground
}
void loop()
{
unsigned long currentTime = millis();
boolean buttonIsPressed = digitalRead(ButtonPin) == LOW; // Active LOW
// Check for button state change and do debounce
if (buttonIsPressed != ButtonWasPressed &&
currentTime - ButtonStateChangeTime > DebounceTime)
{
// Button state has changed
ButtonStateChangeTime = currentTime;
ButtonWasPressed = buttonIsPressed;
if (ButtonWasPressed)
{
// Button was just pressed
ButtonPressTime = currentTime;
}
else
{
// Button was just released
unsigned long buttonHoldTime = currentTime - ButtonPressTime;
if (buttonHoldTime >= 50 && buttonHoldTime <= 1000)
{
// DO THAT THING YOU DO WHEN THE BUTTON IS DOWN
// BETWEEN 50 AND 1000 MILLISECONDS
}
}
}
}