Jan312010

Arduino: cascading shift registers to drive 7-segment displays with PC input

Published by paul at 3:33 PM under Arduino | Example Code | Example Movies | LED Projects | Shift Registers

In the last post I figured out how to drive a 74HC595 shift register to control 8 LEDs from only 3 digital outputs of the Arduino. Now I've taken that a step further and cascaded (sometimes called daisy-chained) four 595s together to drive 7-segment displays and also added code to accept input from the PC.

Instead of using 10-LED bar graphs like I did last time, I've moved on to 7-segment displays - which are more challenging and provide a more meaningful output. The 7-segment displays I have are common-cathode, wired as shown below:

    a           a - pin 14       dp (decimal point) - pin 9
   ---          b - pin 13       common cathode - pins 12 and 4
f |   | b       c - pin 8
   --- g        d - pin 7
e |   | c       e - pin 6
   --- . dp     f - pin 2
    d           g - pin 1
               

The code to illuminate decimal digits on a 7-segment display is pretty straightforward. I assigned each of the 7 segment-pins on the display to an output on the 595, from QA through QG (see the circuit diagram below). Each pin from QA to QG is assigned a binary value of 2 ^ pin#, so figuring out which pins to make high to produce each decimal digit is just a matter of adding together the binary values representing each pin necessary to light up the right segments. You can see this array being initialized in the setup() function.

I've also moved to a proper coding style, with g_ prefixing each global variable to distinguish them from local variables inside functions and methods. It's a good practice to define unchanging variables as const to allow the compiler to optimize the code around them - this also prevents mistakes where the code accidentally tries to change the value - the compiler won't allow it as the variable is effectively read-only and a difficult-to-debug bug is avoided.

To daisy-chain 595s together is really simple - connect the serial output (pin 9) of the 'lowest' 595 to the serial input (pin 14) of the next one in the chain, and connect all the latch (pin 12) and clock (pin 11) inputs together. When the first 595 accepts a new bit, the highest bit in the register will be pushed out of it's serial line as input to the next 595 in the chain. Enough bits must be pushed to fill all the 595s with new data correctly. In the previous post I only had a single 595 so I only had to push 8 bits of data from the Arduino. With two 595s I need to push 16 bits, with the first 8 bits effectively flowing through the first 595 and into the second. And so on with more 595s in the chain.

Care must be taken to push the 8-bit values in the correct order - the 8 bits for the 595 furthest from the Arduino must be pushed first, and the 8 bits for the 595 nearest the Arduino in the chain must be pushed last. I do this in the code in the sendSerialData() function by passing in the number of registers in use, plus a pointer to an array of bytes. Each element in the array has the byte to be pushed to the corresponding register - with the highest register number the furthest away from the Arduino. The code then iterates backwards through the away, pushing each byte in succession.

Rather than doing the obvious count-from-0-to-9999 code, I decided to figure out how to read input from the PC. This is done in the readNumberFromPC() function. If it detects that something has been sent from the PC, it reads each character, with a 10ms delay between each character read to ensure that all characters are received from the PC. Without the delay, the Arduino executes so fast that it may read the first character from the input stream, try again, and the next character hasn't made it over the slow (compared to the Arduino!) link from the PC - resulting in the input being chopped into two parts. This delay doesn't cause a problem with the 595s as their outputs are latched, and so stay the way they were set until the next update - preventing any display flickering.

In the loop() function, the logic to put the correct digit-byte in the register array is hard-coded. In the next rev I'll make this register-count agnostic.

As far as the circuit is concerned, I've got one 220ohm resistor on each 7-segment common cathode going to ground, which produces a bright enough display. I've also added a 100nF decoupling capacitor on the Vcc pin of each 595 to forestall any noise problems.

The complete circuit diagram is as below (click for a larger version):

 

Here's the breadboard layout, with a close up of IC2 (click for larger versions):

  

Once I'd figured out the wiring for one of the displays, adding the other three was pretty easy. At this point I ran out of 595s so I couldn't take the experiment any further, but I do have a bunch more on the way from Jameco.

I took a short (40s) video of the board in action - check it out here on YouTube.

And all the code is below(to download as a text file click here). Drop me a comment if you find this stuff useful!

[Edit: 12/19/10 - here's a link to someone who built a clock based on my code below.]

Next up - replacing some of the shift registers with transistors to allow a bigger fan-out from the Arduino.

/*
  Driving multiple 7-seg displays with 74HC595 shift registers.
 
  Feel free to re-use.
 
   01/30/2010
*/

// This pin gets sets low when I want the 595s to listen
const int  g_pinCommLatch = 6;

// This pin is used by ShiftOut to toggle to say there's another bit to shift
const int  g_pinClock     = 7;

// This pin is used to pass the next bit
const int  g_pinData    = 4;

// Definitions of the 7-bit values for displaying digits
byte g_digits [10];

// Current number being displayed
int g_numberToDisplay = 0;

// Number of shift registers in use
const int g_registers = 4;

// Array of numbers to pass to shift registers
byte g_registerArray [g_registers];

void setup()
{
  pinMode (g_pinCommLatch, OUTPUT);
  pinMode (g_pinClock, OUTPUT);
  pinMode (g_pinData, OUTPUT);
 
  Serial.begin (56600);
 
  // Setup the digits array
  // a = 8 b = 4 c = 2 d = 64 e = 32 f = 1 g = 16
  g_digits [0] = 8 + 4 + 2 + 64 + 32 + 1;
  g_digits [1] = 4 + 2;
  g_digits [2] = 8 + 4 + 16 + 32 + 64;
  g_digits [3] = 8 + 4 + 16 + 2 + 64;
  g_digits [4] = 1 + 16 + 4 + 2;
  g_digits [5] = 8 + 1 + 16 + 2 + 64;
  g_digits [6] = 8 + 1 + 16 + 2 + 64 + 32;
  g_digits [7] = 8 + 4 + 2;
  g_digits [8] = 8 + 4 + 2 + 64 + 32 + 1 + 16;
  g_digits [9] = 8 + 4 + 2 + 1 + 16 + 64;
} // setup

// Simple function to send serial data to one or more shift registers by iterating backwards through an array.
// Although g_registers exists, they may not all be being used, hence the input parameter.
void sendSerialData (
  byte registerCount,  // How many shift registers?
  byte *pValueArray)   // Array of bytes with LSByte in array [0]
{
  // Signal to the 595s to listen for data
  digitalWrite (g_pinCommLatch, LOW);
 
  for (byte reg = registerCount; reg > 0; reg--)
  {
    byte value = pValueArray [reg - 1];
   
    for (byte bitMask = 128; bitMask > 0; bitMask >>= 1)
    {
      digitalWrite (g_pinClock, LOW);
   
      digitalWrite (g_pinData, value & bitMask ? HIGH : LOW);
       
      digitalWrite (g_pinClock, HIGH);
    }
  }
  // Signal to the 595s that I'm done sending
  digitalWrite (g_pinCommLatch, HIGH);
}  // sendSerialData

// Print a message specifying valid inputs, given the number of registers defined and then consume all current input.
void badNumber ()
{
  int dummy;
 
  Serial.print ("Please enter a number from 0 to ");
  for (int loop = 0; loop < g_registers; loop++)
  {
    Serial.print ("9");
  }
  Serial.println (" inclusive.");
 
  while (Serial.available () > 0)
  {
    dummy = Serial.read ();
   
    // Necessary to get all input in one go.
    delay (10);
  }
} //badNumber

// Read a number from the PC with no more digits than the defined number of registers.
// Returns: number to display. If an invalid number was read, the number returned is the current number being displayed
//
int readNumberFromPC ()
{
  byte incomingByte;
  int  numberRead;
  byte incomingCount;
 
  if (Serial.available () > 0)
  {
    numberRead = 0;
    incomingCount = 0;
     
    while (Serial.available () > 0)
    {
      incomingByte = Serial.read () - 48;
      incomingCount++;
     
      if (incomingByte < 0 || incomingByte > 9 || incomingCount > g_registers)
      {
        badNumber ();
        return g_numberToDisplay;
      }
     
      numberRead = 10 * numberRead + incomingByte;
     
      // Necessary to get all input in one go.
      delay (10);
    }

    Serial.print ("Now displaying: ");
    Serial.println (numberRead, DEC);
   
    return numberRead;
  }
 
  return g_numberToDisplay;
} // readNumberFromPC


void loop()
{
  g_numberToDisplay = readNumberFromPC ();
 
  if (g_numberToDisplay < 10)
  {
    g_registerArray [3] = g_digits [0];
    g_registerArray [2] = g_digits [0];
    g_registerArray [1] = g_digits [0];
    g_registerArray [0] = g_digits [g_numberToDisplay];
  }
  else if (g_numberToDisplay < 100)
  {
    g_registerArray [3] = g_digits [0];
    g_registerArray [2] = g_digits [0];
    g_registerArray [1] = g_digits [g_numberToDisplay / 10];
    g_registerArray [0] = g_digits [g_numberToDisplay % 10];
  }
  else if (g_numberToDisplay < 1000)
  {
    g_registerArray [3] = g_digits [0];
    g_registerArray [2] = g_digits [g_numberToDisplay / 100];
    g_registerArray [1] = g_digits [(g_numberToDisplay % 100) / 10];
    g_registerArray [0] = g_digits [g_numberToDisplay % 10];
  }
  else
  {
    g_registerArray [3] = g_digits [g_numberToDisplay / 1000];
    g_registerArray [2] = g_digits [(g_numberToDisplay % 1000) / 100];
    g_registerArray [1] = g_digits [(g_numberToDisplay % 100) / 10];
    g_registerArray [0] = g_digits [g_numberToDisplay % 10];
  }

  sendSerialData (g_registers, g_registerArray);
} // loop



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Currently rated 2.2 by 110 people

  • Currently 2.2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

E-mail | Permalink | Trackback | Post RSSRSS comment feed 5 Responses

Jan282010

Arduino: figuring out shift registers

Published by paul at 10:35 AM under Arduino | LED Projects | Shift Registers

One of the parts that makes possible the scrolling message kit I built over the weekend (see Kit building: Hansen Hobbies mini-scrolling LED sign kit) is a shift register. This is a very neat device that uses at least 2 inputs to load 8 parallel outputs. The idea is to pulse a clock input for each bit of data in the 8-bit register, loading each bit in succession until all 8 bits have been loaded. The shift registers in the kit I made are 74HC164s, which means that the outputs immediately go high or low to relfect the bits as they're loaded into the shift register and shifted along into their desired positions. Many people prefer a latched shift register, where the outputs reflect a steady-state of the register until all 8 new bits have been loaded, and then the outputs change to the new bits in the register (i.e the latched register has two registers - a true shift register and a storage register).

The simple algorithm to load a latched shift-register is:

pull the latch pin low

pull the clock pin low
pull the data pin high or low to reflect bit 1
pull the clock pin high

<repeat for bits 2 through 8>

pull the latch pin high

It's up to you whether you load the 8-bit value as MSB (most-significant-bit) first or LSB (least-significant-bit) first - you'll soon work out if you've got it the wrong way around!

I'm going to use a 74HC595 shift register that can source 35mA per output - perfect for driving the LEDs in my 10-bar LED arrays.

There are two ways to implement the logic above - using the Arduino shiftOut function or writing one yourself. I played around with both to make sure I fully understood what's going on - and I like bit-twiddling in C/C++. The Arduino site has a good language reference on shiftOut (see here) and also a tutorial on using the 74HC595 (see here). I decided to figure out how to use the chip myself so I internalized how to do it in future - but I'm not trying to be a purist and re-inventing the wheel.

The circuit is pretty simple - remember to pull the OutputEnable (active low) pin low and the MemoryClear (active low) pin high.

 

And a photo (click for larger image):

 

The code I used is below, with the two different functions to push data out to the shift register. I had a problem with the code where I originally had the counter variable in the loop() function as a byte and the LEDs counted to the end and then stopped. I put in the serial output to do some testing and connected up with Windows HyperTerminal - so much easier to do it with this than when trying to debug code I'd written in the storage engine of SQL Server :-) Of course as soon as the counter value reached 256, it overflowed and was stored as 0, so no more LEDs being lit up. If you do this, don't forget to hangup before trying to upload a sketch to the Arduino otherwise it won't be able to grab the COM port.

Here's the code:

/*
  Driving a 74HC595 shift register
 
   01/27/2010
*/

// This pin gets sets low when I want the 595 to listen
const int  pinCommLatch = 2;

// This pin is used by ShiftOut to toggle to say there's another bit to shift
const int  pinClock     = 3;

// This pin is used to pass the next bit
const int  pinData    = 4;

void setup()
{
  pinMode (pinCommLatch, OUTPUT);
  pinMode (pinClock, OUTPUT);
  pinMode (pinData, OUTPUT);
 
  //Serial.begin (56600);
} // setup

// Using the builtin shiftOut function
void sendSerialData1 (
  byte  value)
{
  // Signal to the 595 to listen for data
  digitalWrite (pinCommLatch, LOW);
 
  shiftOut (pinData, pinClock, MSBFIRST, value);
 
  // Signal to the 595 that I'm done sending
  digitalWrite (pinCommLatch, HIGH);
}  // sendSerialData1

// Using my own method with as few instructions as possible
// Gotta love C/C++ for bit-twiddling!
void sendSerialData2 (
  byte  value)
{
  // Signal to the 595 to listen for data
  digitalWrite (pinCommLatch, LOW);

  for (byte bitMask = 128; bitMask > 0; bitMask >>= 1)
  {
    digitalWrite (pinClock, LOW);
 
    digitalWrite (pinData, value & bitMask ? HIGH : LOW);
     
    digitalWrite (pinClock, HIGH);
  }
 
  // Signal to the 595 that I'm done sending
  digitalWrite (pinCommLatch, HIGH);
}  // sendSerialData2
 
void loop()
{
  for (int counter = 1; counter < 256; counter++)
  {
    sendSerialData2 (counter);

    delay (75);
  }
} // loop

I recorded a quick video of the code above driving the 595 to get the LEDs to count from 1 to 255 in binary - checkout it on YouTube here.

Next up - daisy-chaining multiple shift-registers.



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Currently rated 3.3 by 29 people

  • Currently 3.275862/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

E-mail | Permalink | Trackback | Post RSSRSS comment feed 1 Responses