/*
State Change and Blink State
October 26-28, 2023
*/
// circuit connections
const int buttonPin = 2; // pushbutton to pin 2, to Gnd with 10 kOhm resistor
const int ledPin = 3; // LED to pin 3 with 220 ohm resistor
int ledState = LOW;
int currentButtonState; // current state of button
int lastButtonState; // previous state of the button
int numBlinks = 3; // set the desired # of blinks here
const long interval = 250; // interval time for blinking here, in milliseconds
// Below derives stopInterval from numBlinks and interval, so only
// the above need to be adjusted if changes desired
// Note: each blink is an on/off sequence, so multiply numBlinks by two
const long stopInterval = interval * (numBlinks*2) + interval;
unsigned long currentTime = 0;
unsigned long previousTime = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
currentButtonState = digitalRead(buttonPin);
}
void loop() {
currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
currentTime = millis();
//Serial.print("currentTime: ");
//Serial.println(currentTime);
// toggle state of LED
ledState = !ledState;
Serial.print("ledState: ");
Serial.println(ledState);
// control LED according to the toggled state
//digitalWrite(ledPin, ledState); //turns the LED on or off based on the variable
blinkPattern2(ledState);
}
lastButtonState = currentButtonState; // save the last state
}
/*
// compare the buttonState to its previous state
if (currentButtonState != lastButtonState) {
// if the state has changed, increment the counter
if (currentButtonState == HIGH) {
unsigned long currentTime = millis();
blinkPattern();
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
} else {
digitalWrite(ledPin, LOW);
// (buttonState == LOW)
}
// Delay a little bit to avoid bouncing
//delay(50);
}
}
*/
void blinkPattern2(int state) {
digitalWrite(ledPin, state);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
digitalWrite(ledPin, state);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
digitalWrite(ledPin, state);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
ledState = !ledState;
Serial.print("ledState: ");
Serial.println(ledState);
}
void blinkPattern(int state) {
//previousTime = millis();
//if (state) {
// for a certain amount of time, blink the LED
// to work fully, nesting if statements was needed
if (millis() - currentTime <= stopInterval) {
if (currentTime - previousTime >= interval) {
previousTime = currentTime;
state = !state;
digitalWrite(ledPin, state);
// Serial.println(previousTime);
}
}
// after a certain time, stop blinking LED
if (currentTime > stopInterval) {
state = HIGH; // this works for LOW, too
digitalWrite(ledPin, state);
}
//}
}