22 July, 2015

Arduino: output multiple numbers to a digital LED display

In the previous article I was describing how to output number into this LED display:

But it is much interesting to display multiple numbers on a single LED module (for example: temperature and moisture or distance and time). It is pretty simple to write it in C.

Like in a previous example DIN, CS and CLK are connected with arduino through these pins: 7, 6 and 5. Here is the working prototype:

Output 2 numbers to led display

In this example are implemented two counters: 2-digits, and 5-digits. The first counter increments from 0 to 99, and then resets on reaching the maximum values. The second - reduces from 99999 to 0, and resets after the zero. In each cycle a digital display shows both numbers at the same time, with an empty place as a separator between them.

Code sample:

#include <LedControl.h>

const int DIN_PIN = 7;
const int CS_PIN = 6;
const int CLK_PIN = 5;

LedControl display = LedControl(DIN_PIN, CLK_PIN, CS_PIN);

void setup() {
  display.clearDisplay(0);
  display.shutdown(0, false);
  display.setIntensity(0, 10);
}

void displayString(const char *chars8) {
  display.clearDisplay(0);
  for (int i = 0; i < 8 && chars8[i] != 0; i++) {
    display.setChar(0, 7 - i, chars8[i], false);
  }
}

int counter1 = 0;
long counter2 = 99999;

char chars[9] = {};

void loop() {
  snprintf(chars, 9, "%-2d %5ld", counter1, counter2);
  displayString(chars);

  counter1++;
  counter2--;

  if (counter1 > 99) {
    counter1 = 0;
  }

  if (counter2 < 0) {
    counter2 = 99999;
  }

  delay(250);
}

In this example two numbers are packed into the char array and then displayed via the displayString() function. I use snprintf() function for this; it is much safe then sprintf().

The first number is aligned on the left edge of the display, the second - on the right.

This code requires LedControl library.

Set of components used in this example:

No comments: