≡ Menu

Arduino 2 Digit 7 Segment Display Sketch (with Buttons) | Part 5

* This is a multi-part post. Here are links to all parts:

Part 1: Intro, bill of materials and simple sketch
Part 2: The circuit for the 2-digit 7-segment counter
Part 3: Sketch broken down in sections, explained
Part 4: Added two buttons, and modified sketch
Part 5: Code for buttons, explained; this post

As you could see from last week’s full Arduino sketch listing, the source code for the 2-digit 7-segment display project using buttons is strikingly similar to the one without the buttons; praise for ‘copy and paste‘! (It is worth noting, though, that ‘copy and paste‘ can be responsible for a higher percentage of bugs than I’d care to admit).

There are just a couple of snippets that I would like to comment on:

2 Digit 7 Segment Display Sketch

The first part of the loop() function checks whether either button has been pressed and increments the value of each digit.

  // check button1
  int val1 = digitalRead(BTN1);
  if (val1 == HIGH) {
    digit1++;
    digit1 %= 10;
    delay(10);
  }

  // check button2
  int val2 = digitalRead(BTN2);
  if (val2 == HIGH) {
    digit2++;
    digit2 %= 10;
    delay(10);
  }

The line

digit1 %= 10;

which is shorthand for

digit1 = digit1 % 10;

accomplishes the same as the line

if (count == 10) count = 0;

that was used on the sketch for the single-digit 7-segment project a couple of months ago. It updates digit1 with the remainder of the division of itself by 10, which will be zero when digit1 is 10. The latter code looks a bit more obvious for beginner programmers.

The last part of the loop() function refreshes the display, and is very similar to the sketch for the 2-digit 7-segment display counter.

  // display number
  unsigned long startTime = millis();
  for (unsigned long elapsed=0; elapsed < 600; elapsed = millis() - startTime) {
    lightDigit1(numbers[digit1]);
    delay(5);
    lightDigit2(numbers[digit2]);
    delay(5);
  }
{ 7 comments… add one }
  • Joe

    hi!:) is it possible to add another 7-segment display using this script with just a few add-ons?

  • Bouke

    hallo,
    Where can I find the diagram for the up/down counter with 2 buttons ???
    regards
    Bouke

Leave a Comment