Go Down

Topic: button plus switch/case scenerio (Read 453 times) previous topic - next topic

anderscrib

So, I am still learning. Any thoughts on how to combine this
Code: [Select]
const int LED = 13; //pin for LED
const int BUTTON = 7; //push button pin
int val = 0; //val used to store state of pin
int old_val = 0; //stores previous state of val
int state = 0; //0 = LED off and 1 = LED on
void setup () {
  pinMode(LED,OUTPUT); //LED is output
  pinMode(BUTTON, INPUT); //BUTTON is input
}
void loop (){
  val = digitalRead(BUTTON); //read input and store it
  //check transition
  if((val == HIGH) && (old_val == LOW)){
    state = 1 - state;
    delay(10);
  }
    old_val== val; //val is now old..store it
    if (state == 1){
      digitalWrite(LED,HIGH); //turn LED on
    }else{
      digitalWrite(LED,LOW);
    }
}
momentary button with a Switch/ Case function? The end result I'd like would be push button= LED goes on..Push button= LED blinks..Push button=throb....push button= off..
Any guidance from the community would be great

pYro_65

This may be a start, I haven't tested it but you can give it a try and see.

Code: [Select]
const int BUTTON = 7; //push button pin
const int LED = 13; //pin for LED

void setup () {
  pinMode(LED,OUTPUT); //LED is output
  pinMode(BUTTON, INPUT); //BUTTON is input
}

void loop()
  {
    static byte b_State = 0;
    static bool b_OnLastLoop = false;
    static unsigned long  u_LastTime = 0;
    static bool  b_Flag = false;
   
    //If pressed increment state.
    if( ( digitalRead( BUTTON ) == HIGH ) && !b_OnLastLoop  ){

      b_OnLastLoop = true;

      switch( ++b_State ){
     
        case 1:
          digitalWrite( LED, HIGH );
          break;

        case 2:
          b_Flag = true;
          u_LastTime = millis();
          break;

        case 3:

          b_State = 0;
          digitalWrite( LED, LOW );
          break;
      }
    }else{

      if( digitalRead( BUTTON ) == LOW ) b_OnLastLoop = false;

      if( b_State == 2 ){

        unsigned long u_NewTime = millis();
   
        if( ( u_NewTime - u_LastTime )  >= 1000 ) {

          digitalWrite( LED, b_Flag ? LOW : HIGH );
          b_Flag = !b_Flag;
          u_LastTime = u_NewTime;
        }
      }
    }
    return;
  }

anderscrib

Wow, Thanks pYro_65..
That is way more complex than I thought it would be and introduces more for me to digest.. I'll have to spend some time on that one.
Did you write that on the fly?

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy