SMILEY’S WORKSHOP ☺
bits out on the serial data output pin 9
(Q) which we monitor with our MISO
(Master In Slave Out) pin. We can see
this process in action in the following
code snippet:
Code Snippet:
uint8_t my_data_in = 0;
// Clear slave select
// so data won’t show while
// shifting
clear_ss();
// load 8 bits from the 597 into
// my_data_in byte
for (i=7; i>=0; i—)
{
// Toggle the clock to get the
// next bit
toggle_clock();
// If data pin = 1 set it
// in my_data otherwise
// do nothing since my_data_in is
// initialized to 0
if (get_miso_bit())
my_data_in |= (1 << i);
uart_send_bit(1);
}
else
{
uart_send_bit(0);
}
}
// Set slave select to transfer data
// from serial to parallel registers
set_ss();
This snippet is part of Shift_Register.c code that you
can get in the Workshop28.zip from Nuts & Volts. When
you set the DIP switch to 0xAA (binary 10101010), run
the program while communicating with Brays terminal,
and move the lowest bit from 0 to 1 you get the output
shown in Figure 9.
Software SPI Pins
SPI uses four pins: MOSI, MISO, SCLK, and /SS. For
us to use these in software, we must designate specific
pins from specific ports and then we must set them up for
data direction (input or output). While any pins common
to all the boards we are writing our code for would be
okay to use, we will define the following:
#define mosi_port PORTB
#define mosi_port_pin PORTB2
#define mosi_ddr DDRB
#define mosi_port_pins PINB
#define miso_port PORTB
#define miso_port_pin PORTB1
#define miso_ddr DDRB
#define miso_port_pins PINB
#define sclk_port PORTD
#define sclk_port_pin PORTD7
#define sclk_ddr DDRD
■ FIGURE 8. Parallel-In-Serial-Out Schematic.
#define ss_port PORTB
#define ss_port_pin PORTB0
#define ss_ddr DDRB
We then set the data direction as follows:
void setup_pins()
{
// Initialize MISO as input
// set DDR pin register to 0
miso_ddr &= ~(1<<miso_port_pin);
// Initialize MOSI, SCLK, AND /SS as
outputs
// set DDR pin registers to 1
mosi_ddr |= (1<<mosi_port_pin);
sclk_ddr |= (1<<sclk_port_pin);
ss_ddr |= (1<<ss_port_pin);
}
■ FIGURE 9. Output of ShiftRegister.C in Brays Terminal.
November 2010 63