beautypg.com

Spi master operation example, Attiny26(l) – Rainbow Electronics ATtiny26L User Manual

Page 69

background image

69

ATtiny26(L)

1477B–AVR–04/02

shifted by one) at negative edges. External clock mode 1 (USICS0 = 1) uses the oppo-
site edges versus mode 0, i.e., samples data at negative and changes the output at
positive edges. The USI clock modes corresponds to the SPI data mode 0 and 1.

Referring to the timing diagram (Figure 41.), a bus transfer involves the following steps:

1.

The slave device and master device sets up its data output and, depending on
the protocol used, enables its output driver (mark A and B). The output is set up
by writing the data to be transmitted to the serial Data Register. Enabling of the
output is done by setting the corresponding bit in the port data direction register
(DDRB2). Note that point A and B does not have any specific order, but both
must be at least one half SCK cycle before point C where the data is sampled.
This must be done to ensure that the data setup requirement is satisfied. The 4-
bit counter is reset to zero.

2.

The master generates a clock pulse by software toggling the SCK line twice (C
and D). The bit value on the slave and master’s data input (DI) pin is sampled by
the USI on the first edge (C), and the data output is changed on the opposite
edge (D). The 4-bit counter will count both edges.

3.

Step 2. is repeated eight times for a comlpete register (byte) transfer.

4.

After eight clock pulses (i.e., 16 clock edges) the counter will overflow and indi-
cate that the transfer is completed. The data bytes transferred must now be
processed before a new transfer can be initiated. The overflow interrupt will
wake up the processor if it is set to Idle mode. Depending of the protocol used
the slave device can now set its output to high impedance.

SPI Master Operation
Example

The following code demonstrates how to use the USI module as a SPI master:

SPITransfer:

out

USIDR,r16

ldi

r16,(1<

out

USISR,r16

ldi

r16,(1<

SPITransfer_loop:

out

USICR,r16

sbis

USISR,USIOIF

rjmp

SPITransfer_loop

in

r16,USIDR

ret

The code is size optimized using only 8 instructions (+ ret). The code example assumes
that the DO and SCK pins are enabled as output in the DDRB Register. The value
stored in register r16 prior to the function is called is transferred to the slave device, and
when the transfer is completed the data received from the slave is stored back into the
r16 register.

The second and third instructions clears the USI Counter Overflow Flag and the USI
counter value. The fourth and fifth instruction set Three-wire mode, positive edge Shift
Register clock, count at USITC strobe, and toggle SCK (PORTB2). The loop is repeated
16 times.