Hi, how can i convert this code into a finite state or switch case?
#include <SPI.h>
// initialize the library with the numbers of the interface pins
int ledPin = 13; // LED connected to digital pin 13
int inPin = 10; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int cnt =0; // var for counting the presses
int tog =0; //bit used to toggle and keep track of when the button is pressd or not
void setup() // run once, when the sketch starts
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
pinMode(inPin, INPUT); // declare pushbutton as input
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() // run over and over again
{
val = digitalRead(inPin); // read input value
if (val == HIGH) { // check if the input is HIGH (button released)
digitalWrite(ledPin, LOW); // turn LED OFF
if (tog ==0){
tog++;
}
else{
while ( tog == 1) {
cnt++;
tog = 2;
}
}
}
else
{
digitalWrite(ledPin, HIGH); // turn LED ON
tog =0;
}
}
I tried to extract from your code the intended behavior. If I understand it correctly you want the LED to reflect the button state and to increment a counter when the button is pressed. I don't know what button you are using, typically button do not give clean transitions and you want to filter them out (called 'denouncing') If you want an example, let me know.
Here is an outline of one way to achieve the above logic (without the denouncing). I did not try to compile, you will need to clean it up.
boolean lastKeyState;
void setup() {
lastKeyState = HIGH;
// the rest is the same as your example
}
loop() {
// Read key. LOW means PRESSED.
boolean newKeyState = digitalRead(inPin);
// Track key changes. Increment counter if key changed state from HIGH to LOW.
if (lastKeyState == HIGH && newKeyState == LOW ) {
cnt++
}
// Remember new key state for next loop() iteration.
lastKeyState = newKeyState;
// Update led to reflect new key state
// I think this can also be written as: digialWrite(ledPin, !newKeyState).
if (newKeyState == LOW) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
If I understand it correctly you want the LED to reflect the button state and to increment a counter when the button is pressed. I don't know what button you are using
Yes, its a counter for a push button switch. Thanks. I'll try this code.
Autocorrect is really more trouble than it's worth on technical forums - progmem is another one it hates that has caught me out repeatedly. Debouncing!
If I understand it correctly you want the LED to reflect the button state and to increment a counter when the button is pressed. I don't know what button you are using
Yes, its a counter for a push button switch. Thanks. I'll try this code.
If you will see multiple counts per button press this is a button debouncing issue (thanks wildbill for the correction).