Thursday, January 20, 2011

7-Segment Display on Arduino

A new package with electronic components arrived today, so let's get busy.

First I want to show you a seven segment display which I hooked up to the Arduino. The display is from sparkfun and it is really easy to connect and to control it. You can control it via SPI or via serial. For more info refer to the datasheet. I used the serial communication, so I only would need one wire to transmit data to the component. You just have to connect the Vcc pin to 5V of the Arduino and the GND pin to GND. Then you only need to connect the RX pin to one of the digital ports of the Arduino. For sending data to the component I used the NewSoftSerial library.

The example program I wrote is a simple seconds counter.
#include "NewSoftSerial.h"

//The second parameter (TX) is the digital port which sends data to the display.
//The first parameter (RX) isn ot used.
NewSoftSerial mySerial(2, 3);
int minutes;
int deciminutes;
int seconds;
int deciseconds;

void setup() {
  Serial.begin(9600);
  // set the data rate for the NewSoftSerial port
  mySerial.begin(9600);
  //all digits off
  mySerial.print("xxxx");
  //activate colon
  mySerial.print(0x77, BYTE);
  mySerial.print(0x10, BYTE);
  //reset display
  mySerial.print(0x76, BYTE);
}

void loop() {
  seconds++;
  if(seconds > 9) {
    seconds = 0;
    deciseconds++;
  }
  if(deciseconds > 5) {
    deciseconds = 0;
    minutes++;
  }
  if(minutes > 9) {
    minutes = 0;
    deciminutes++;
  }
  if(deciminutes > 9) {
    deciminutes = 0;
    mySerial.print("xxxx");
  }
  if(deciminutes > 0) {
    mySerial.print(deciminutes);
    mySerial.print(minutes);
    mySerial.print(deciseconds);
    mySerial.print(seconds);
  } else {
    mySerial.print("x");
    if(minutes > 0) {
      mySerial.print(minutes);
      mySerial.print(deciseconds);
      mySerial.print(seconds);
    } else {
      mySerial.print("x");
      if(deciseconds > 0) {
        mySerial.print(deciseconds);
        mySerial.print(seconds);
      } else {
        mySerial.print("x");
        mySerial.print(seconds);
      }
    }
  }
  delay(1000); 
}
Here is a small demonstration. You could also use the module as a timer, a counter or simply a digital clock.