Hi All,
I'm currently playing with the concept of nested states (toggle states) and a) having an issue when returning to the original state and b) not sure if there is a better way of writing the code I currently have.
I have one button that toggles between state 0 & state 1. When I press and hold the same button for a period of 1000 ms, the toggle state then changes to state 2. Now I can toggle between state 2 & state 3. The goal is that when I press and hold the same button for another period of time, it returns back to the default state of toggling between 0 & 1. However currently the serial monitor is printing a toggle change state of 0 & 2. Which is not ideal, as would like it to return to state 0 and stay there, until the button is released. Then i can toggle between 0 & 1 again.
I understand it most likely has something to do with the 'timeStamp' variable storing millis() and the duration passed, however I can think of how to improve it.
Here is my code. Any help would be awesome
Thanks
I'm currently playing with the concept of nested states (toggle states) and a) having an issue when returning to the original state and b) not sure if there is a better way of writing the code I currently have.
I have one button that toggles between state 0 & state 1. When I press and hold the same button for a period of 1000 ms, the toggle state then changes to state 2. Now I can toggle between state 2 & state 3. The goal is that when I press and hold the same button for another period of time, it returns back to the default state of toggling between 0 & 1. However currently the serial monitor is printing a toggle change state of 0 & 2. Which is not ideal, as would like it to return to state 0 and stay there, until the button is released. Then i can toggle between 0 & 1 again.
I understand it most likely has something to do with the 'timeStamp' variable storing millis() and the duration passed, however I can think of how to improve it.
Here is my code. Any help would be awesome
Thanks
Code:
int buttonPin = 12;
int ledPin = 13;
int buttonState;
int lastButtonState;
int mode = 0;
unsigned long timeStamp = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonMode();
}
void buttonMode() {
buttonState = digitalRead(buttonPin);
//TOGGLE PRESS
if (buttonState != lastButtonState) {
timeStamp = millis();
if (buttonState == HIGH) {
if (mode == 0) {
mode = 1;
digitalWrite(ledPin, HIGH);
} else {
if (mode == 1) {
mode = 0;
digitalWrite(ledPin, LOW);
}
}
if (mode == 2) {
mode = 3;
} else {
if (mode == 3) {
mode = 2;
}
}
Serial.printf("Button Mode: %d\n", mode);
}
}
//TIMED PRESS
if (buttonState == HIGH) {
if (mode == 0 || mode == 1) {
if ((millis() - timeStamp) > 1000) {
mode = 2;
Serial.printf("Button Mode: %d\n", mode);
}
}
if (mode == 2 || mode == 3) {
if ((millis() - timeStamp) > 2000) {
mode = 0;
Serial.printf("Button Mode: %d\n", mode);
}
}
}
lastButtonState = buttonState;
}