Pages: [1]   Go Down
Author Topic: button plus switch/case scenerio  (Read 416 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 35
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

So, I am still learning. Any thoughts on how to combine this
Code:
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
Logged

North Queensland, Australia
Offline Offline
Edison Member
*
Karma: 70
Posts: 2171
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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;
  }
Logged


Offline Offline
Newbie
*
Karma: 0
Posts: 35
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Pages: [1]   Go Up
Jump to: