Arduino 2-Digit 7-Segment Display with Buttons: Sketch | Part 5

by Natalia

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:

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);
  }

You might also enjoy:

  1. Arduino 2-Digit 7-Segment Display Counter: Sketch | Part 3
  2. Arduino 2-Digit 7-Segment Display with Buttons | Part 4
  3. Arduino 2-Digit 7-Segment Display Counter | Part 1
  4. Arduino 2-Digit 7-Segment Display Counter: Circuit | Part 2

{ 2 comments… read them below or add one }

Joe September 26, 2011 at 12:48 pm

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

Reply

Natalia October 3, 2011 at 2:43 pm

Joe,
yes, with a few tweaks you can drive another display, or maybe you could use a 4-digit display. Some people prefer to use a dedicated driver like the Maxim MAX7219 take care of that. Here is an excellent tutorial/review on how to use one: http://tronixstuff.wordpress.com/2010/07/09/review-maxim-max7219-led-display-driver-ic/

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: