Display de 7 segmentos controlados por 2 push button

 Montagem


Código do arduino

/////// Biblioteca button

#define PULLUP HIGH
#define PULLDOWN LOW

#define CURRENT 0
#define PREVIOUS 1
#define CHANGED 2

class Button{
  public:
    Button(uint8_t buttonPin, uint8_t buttonMode=PULLDOWN);
    void pullup();
    void pulldown();
    bool isPressed();
    bool wasPressed();
    bool stateChanged();
  bool uniquePress();
  private:
    uint8_t pin;
    uint8_t mode;
    uint8_t state;
};

Button::Button(uint8_t buttonPin, uint8_t buttonMode){
  this->pin=buttonPin;
    pinMode(pin,INPUT);
  buttonMode==PULLDOWN ? pulldown() : pullup();
    state = 0;
    bitWrite(state,CURRENT,!mode);
}

/*
|| Set pin HIGH as default
*/
void Button::pullup(void){
  mode=PULLUP;
  digitalWrite(pin,HIGH);
}

/*
|| Set pin LOW as default
*/
void Button::pulldown(void){
  mode=PULLDOWN;
  //digitalWrite(pin,LOW);
}

/*
|| Return the bitWrite(state,CURRENT, of the switch
*/
bool Button::isPressed(void){
    bitWrite(state,PREVIOUS,bitRead(state,CURRENT));
    if (digitalRead(pin) == mode){
        bitWrite(state,CURRENT,false);
    } else {
        bitWrite(state,CURRENT,true);
    }
    if (bitRead(state,CURRENT) != bitRead(state,PREVIOUS)){
        bitWrite(state,CHANGED,true);
    }else{
        bitWrite(state,CHANGED,false);
    }
  return bitRead(state,CURRENT);
}

/*
|| Return true if the button has been pressed
*/
bool Button::wasPressed(void){
    if (bitRead(state,CURRENT)){
        return true;
    } else {
        return false;
    }
}

/*
|| Return true if state has been changed
*/
bool Button::stateChanged(void){
    return bitRead(state,CHANGED);
}

/*
|| Return true if the button is pressed, and was not pressed before
*/
bool Button::uniquePress(void){
    return (isPressed() && stateChanged());
}

////////////////////////

byte tabla7seg[10]={0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f};
byte pines_display[7]={4,5,6,7,8,9,10};
int led = 13;
int8_t cc1=0;
unsigned long t1;

Button b1=Button(2,PULLUP);
Button b2=Button(3,PULLUP);

void muestra7seg(int x){
  for (int i=0;i<7;i++)
    digitalWrite(pines_display[i],bitRead(tabla7seg[x],i));
}

void setup()
{
  pinMode(13, OUTPUT);
  for(int i=0;i<7;i++){
    pinMode(pines_display[i],OUTPUT);
    /* si pongo digitalWrite(pines_display[i],HIGH);primero se
    me enciende cada display hasta tener 8 y luego procede
    a pasar al 0,1,2,3,4,5...*/
  }
  muestra7seg(cc1);
}

void loop()
{
  if (b1.uniquePress()){
    if (++cc1==10) cc1=0;
    muestra7seg(cc1);
  }
  if (b2.uniquePress()){
    if (--cc1==-1) cc1=9;
    /*cuando decremento de 1 pasa a 0 y luego a -1 se nos
    sale de rango, por lo que hay que decirle que pase al
    valor 9*/
    muestra7seg(cc1);
  }
  delay(10);
}

Comentários

Postagens mais visitadas