Toggle on off help

byte digitOne[10]= {0x80, 0xF2, 0x48, 0x60, 0x32, 0x24, 0x04, 0xF0, 0x00, 0x30};
// a=1 b=2 c=3 d=4 e=5 f=6 g=7

int tensdigit;  
int unitdigit;
int counter=0;

void setup(){
  DDRD |= B11111110;
  DDRB |= B00000110;
  PORTD = 0x00;
  PORTB = 0x00;
}

void loop(){
  if(digitalRead(11) == 1){
  counter++;
    if(counter==100) 
     counter=0;
    delay(500);
  }

  tensdigit = counter / 10;  

  unitdigit = counter % 10;

  PORTB |= B00000100;
  PORTB &= B11111101;
  number(tensdigit);
  delay(50);

  PORTB |= B00000010;
  PORTB &= B11111011;
  number(unitdigit);
  delay(50);
}

void number(int number){
  PORTD = digitOne[number];
}

How can i add a toggle on off button to this? i tried a lot but it didn't work. I just want to counter go up only 1 times after i press it. And it wont keep going up while im holding it down

See the StateChangeDetection example in the IDE

It looks like you are using your button on Arduino Pin 12 which is PB4 on PORT B. You must configure PB4 pin mode (DDRB) as INPUT (or INPUT_PULLUP) using a "mask" on PINB. You are using PORTx and masking bits in your code... here is a chart showing PINx also...

DDRxn  PORTxn  state
  0       0    INPUT
  0       1    INPUT_PULLUP
  1       0    OUTPUT LOW
  1       1    OUTPUT HIGH

1 Like

Why not just use the pinMode() function ?

Original sketch is using bit masking.

I know, but I don't see the point of doing that instead of pinMode() in setup()

See if this little sketch helps with toggling and debouncing button input.

void setup()
{
  Serial.begin(9600);
  pinMode(LED_BUILTIN,OUTPUT);
  pinMode(11,INPUT);
}

void loop()
{
  static byte counter = 0;
  static bool this11 = false,
              last11 = false;
              
  this11 = digitalRead(11);
  if(this11 != last11)
  {
    last11 = this11;
    delay(50); // debounce time, 50ms
    if(digitalRead(11) == this11 && this11) //pin 11 is HIGH
      {
        digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));
        if(++counter >= 100) // counter rollover
        {
          counter = 0; 
        }
        Serial.println(counter);
      }
  }
}
  

Practice binary mathmagic. I understand your meaning, knowing the IDE will do better bitmath than I will. It is akin to ham with cw... why? other than enjoying "Hello, World!" in ham.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.