/*  
    display.pde
    
    Serial 7-segment display test, using multiple display units.
    Works with the Sparkfun 4-digit 7-segment display.

    Eric Ayars
    3/15/12

*/

#define SER1TX 4
#define SER1RX 3
#define SER2TX 6
#define SER2RX 5

#include <SoftwareSerial.h>
SoftwareSerial Display1(SER1RX, SER1TX);
SoftwareSerial Display2(SER2RX, SER2TX);

int delayTime=100;
unsigned int count=0;
unsigned int dcount=9999;

void fourdigit(int x, SoftwareSerial Display) {
    /*
    prints a 4-digit number on a sparkfun 7-segment serial display.
    Can be used to operate multiple displays, each as a separate 
    SoftwareSerial object.
    */

    byte d1,d2,d3,d4;       // each digit

    // Calculate the digits

    d4 = x%10;              // ones digit
    x = x/10;

    if (x) {                // Tens digit, if needed.
        d3 = x%10;
        x = x/10;
    } else {
        d3 = 0x78;          // Not needed, so blank.
    }

    if (x) {                // Hundreds digit, if needed.
        d2 = x%10;
        x = x/10;
    } else {
        d2 = 0x78;          // Not needed, so blank.
    }

    if (x) {                // Thousands digit, if needed.
        d1 = x%10;
        x = x/10;
    } else {
        d1 = 0x78;          // Not needed, so blank.
    }

    if (x) {                // Uh-oh. Still more digits left!
        d1 = '-';
        d2 = '-';
        d3 = '-';
        d4 = '-';
    }
    
    // Now write them
    Display.write(0x76);    // Clears the display, set pointer to digit 1.
    Display.write(d1);
    Display.write(d2);
    Display.write(d3);
    Display.write(d4);
}
    
void setup() {
    // Set up display 1
    Display1.begin(9600);
    delay(50);
    Display1.write(0x7A);   // brightness command bit
    Display1.write(0x01);   // set brightness to brightest value

    // Set up display 2
    Display2.begin(9600);
    delay(50);
    Display2.write(0x7A);   // brightness command bit
    Display2.write(0x01);   // set brightness to brightest value
}

void loop() {
    fourdigit(count, Display1);
    fourdigit(dcount, Display2);
    delay(delayTime);
    count++;
    dcount--;
}