Have you abandoned the code in #14?
I can't read your code just now. Are these two sketches one with state change detection and the other with debounce?
You need to do both.
As for doing it right, where are you seeing the patterns that you are copying or working from? If you start with something simpler you would be able to see if you did it right or not straight away.
You can trace the code with your finger, but usually it is faster to use serial printing. Place serial print statements in the code all over to see the flow through your code and verify that is is informed
properly by the values of key variables.
If you don't do the finger thing or the printing thing, you are flying blind.
An easier first sketch is to just get something to print
once each time you do press, then release the button.
When you have that working, kick off five blinks where you printed that you saw the button get pressed.
Worry later about how to handle a second button press whilst still counting off the five blinks.
You code may be close, but between the odd formatting, the tiny window I am looking through and a few distractions my inspection will have to wait.
Later: Through the larger window, I see necessary elements in both sketches, but nothing complete in either.
This is parts of your code all mashed together with printing. I hand it to you and hope you take some time to read it line by line, execute it with your finger or by adding even more printing, and perhaps try to fix what I consider to be a defect even though the sketch "works": it continues to write to the output even after count is 0, is just that at that point it is always writing 0.
const int ledPin = 8;
const int button1 = 5;
int ledState = LOW;
int lastButtonState;
unsigned long previousMillis1 = 0;
const long interval = 1000;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
uint8_t counter = 0;
constexpr uint8_t NumberOfCounts {5};
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(button1, INPUT_PULLUP);
}
void loop()
{
unsigned long currentMillis = millis();
if ((millis() - lastDebounceTime) > debounceDelay) // debounce
{
int buttonState = digitalRead(button1);
if (buttonState != lastButtonState) // state change detection
{
if (buttonState == LOW) {
previousMillis1 = currentMillis;
counter = NumberOfCounts;
digitalWrite(ledPin, HIGH);
}
lastButtonState = buttonState;
lastDebounceTime = millis();
}
}
if (currentMillis - previousMillis1 >= interval)
{
Serial.print("timed for blinkation: count = ");
Serial.println(counter);
previousMillis1 = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
{
ledState = HIGH;
if (counter != 0) counter--;
}
else
{
ledState = LOW;
}
Serial.println(" writing to the LED!");
digitalWrite(ledPin, ledState and counter);
}
}
If it doesn't work, try fixing it. ;-)
Tip: Use the Autoformat tool in the IDE until you are automatically writing code with good formatting.
a7