How to drive 595 shift registers with ATmega168
Driving a shift register using an AVR chip’s built-in hardware is really quite easy. Most of their offerings have an SPI module, or Serial Peripheral Interface. A shift register is exactly that, a peripheral device that communicates via a serial line. All we need to do is hook up our connections and use a few pieces of simple code. Join me after the break to see how that’s done.
Just want to know how shift registers work? Check in on my other post on that topic.
The first thing to consider is that it may not be necessary to connect the Clear and Enable pins to the microcontroller. If there are relatively few shift registers being used together it may be easier to shift in all zeros and latch them to the registers. But if timing is a big issue you may want this capability. For this example I have just connected the SCLR pin to VCC and the enable pin to GND.
This leaves three control pins: SI, SCK, and RCK. It is possible to drive SCK and RCK from the same signal, but that’s for another tutorial. My test hardware, the ATmega168, has pins meant to drive each of these controls. Note that the serial and storage clocks (SCK and RCK) for both shift register chips are hooked together on two data buses. The Serial In of the first chip (SI) is connected to the microcontroller. The QH prime pin of this first chip is connected to the SI pin of the second chip to cascade the data from one to the next.
Using the AVR SPI hardware
Accessing the SPI hardware is pretty simple. There’s only a few things that need to happen to get it running:
- Define which pins we’re using and set them to outputs
- Enable SPI and set it to Master mode
- pull the SS pin low
- Write our data to the SPDR, it will automatically be strobed into the shift registers
- Toggle the latch to display the data on the LEDs
The definitions are easy enough. I can’t just choose any pins, the SPI outputs are specific pins which can be looked up in the datasheet:
#define SHIFT_REGISTER DDRB#define SHIFT_PORT PORTB#define DATA (1<<PB3)//MOSI (SI)#define LATCH (1<<PB2)//SS(RCK)#define CLOCK (1<<PB5)//SCK(SCK)
SHIFT_REGISTER |= (DATA | LATCH | CLOCK);//Set control pins as outputsSHIFT_PORT &= ~(DATA | LATCH | CLOCK);//Set control pins low
Enabling SPI in Master mode is a one-liner. But there are other clock prescaling options that you can choose from if you need to. I’ll leave that up to you to explore:
For more detail: How to drive 595 shift registers with ATmega168
Leave a Comment
You must be logged in to post a comment.