Saturday 8 March 2014

SPI and an example application - Programming ATtiny85 with Arduino as ISP.

In Non-Engineering Speak
The following post explains a communication protocol used to transfer data between two devices synchronously. Data is transferred serially, which means one bit at a time. Due to its special design, at a particular time, as a device is transmitting a particular bit, it also receives a bit from the other device.


What is SPI?

SPI is a synchronous serial transfer data protocol.

The two devices between which the data is being transferred are called the Master and Slave.
There is a full duplex connection between the two. There can only be one master at a time, but the SPI controllers can take turns being masters.

Master - Initiates connection. Provides clock source - SCK.
Slave - Receives data from Master's SPI register and sends data to Master's SPI register, forming a circular buffer.

Both Master and Slave have a 8 bit shift register. Register size can vary depending on the microcontroller, but it should be the same for both Master and Slave.

The SPI interface consists of 3 wires:
1. Serial Clock (SCK)
2. Master In - Slave Out (MISO)
3. Master Out - Slave In (MOSI)
4. (Optional) SS' - Slave select. (If more than 1 slave)

How does it work?




SPI Connections
SPI Circular Buffer Data Flow Animation


At every clock pulse, a bit is transferred from the master to the slave and a bit from the slave to the master as shown in the animation above. The microcontroller can set be set to transfer the least significant or the most significant bit first.


Application of SPI

In this example, In-Circuit Serial Programming (ISP) uses the SPI protocol to communicate between the ATMega328 microcontroller on the Arduino and the ATtiny85 microcontroller on the breadboard.

Here are some points of caution:

- When programming the AVR, the ISP always operates as the Master, and the target system always operates as the Slave.

- GND should be common.

- To stay in SPI mode, the AVR micro reset line has to be kept active (low).

- Reset has to be pulsed to end Chip Erase cycle.

- ISP should keep the entire target system reset for the duration of programming cycle.

- Target system should not attempt to drive SPI lines while reset is active.


Wiring Diagram
Picture of prototype
Follow the instructable for a step by step guide.


References
http://www.atmel.ca/Images/doc0943.pdf
http://maxembedded.com/2013/11/10/serial-peripheral-interface-spi-basics/
http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/