Subversion Repositories HomeAutomation

Rev

Rev 73 | Blame | Compare with Previous | Last modification | View Log | SVN | RSS feed

  1. /**
  2.  * @file    spi.c
  3.  * SPI drivers for ATmega8.
  4.  *
  5.  * @author  Jimmy Myhrman (jimmy@myhrman.org)
  6.  * @date    2005-11-28
  7.  */
  8.  
  9. /* -----------------------------------------------------------------------------
  10.  * Includes
  11.  * ---------------------------------------------------------------------------*/
  12. #include "spi.h"
  13.  
  14.  
  15. /* -----------------------------------------------------------------------------
  16.  * Functions
  17.  * ---------------------------------------------------------------------------*/
  18.  
  19. /**
  20.  * Initializes the SPI interface to master mode.
  21.  */
  22. void SPI_master_init() {
  23.     DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_CS);  /* MOSI, SCK and SS are outputs */
  24.     SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);            /* enable SPI, Master, set clock rate fck/16 */
  25. }
  26.  
  27. /**
  28.  * Activates the chip select signal, which is active low.
  29.  */
  30. void SPI_chip_select() {
  31.     PORTB &= ~(1<<DD_CS);       /* enable chip select (active low) */
  32. }
  33.  
  34. /**
  35.  * De-activates the chip select signal, which is active low.
  36.  */
  37. void SPI_chip_unselect() {
  38.     PORTB |= (1<<DD_CS);        /* disable chip select (active low) */
  39. }
  40.  
  41. /**
  42.  * Sends a data byte via SPI as a master. The function waits till the byte has
  43.  * been transmitted before it returns.
  44.  *
  45.  * @param byte The data byte to send.
  46.  * @return The received byte.
  47.  */
  48. uint8_t SPI_master_send(uint8_t byte) {
  49.     SPDR = byte;                /* start transmission */
  50.     while(!(SPSR & (1<<SPIF))); /* wait for transmission complete */
  51.     return SPDR;
  52. }
  53.  
  54. /**
  55.  * Initializes the SPI interface to slave mode.
  56.  */
  57. void SPI_slave_init() {
  58.     DDR_SPI = (1<<DD_MISO);     /* set MISO output, all others input */
  59.     SPCR = (1<<SPE);            /* enable SPI */
  60. }
  61.  
  62. /**
  63.  * Reads a data byte from the SPI as a slave. The function waits for a reception
  64.  * to complete and returns the received byte.
  65.  *
  66.  * @return The received byte.
  67.  */
  68. uint8_t SPI_slave_receive(void) {
  69.     while(!(SPSR & (1<<SPIF))); /* wait for reception complete */
  70.     return SPDR;                /* return data register */
  71. }
  72.