spi.h 880 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //spi.h - hardware SPI
  2. #ifndef SPI_H
  3. #define SPI_H
  4. #include <inttypes.h>
  5. #include <avr/io.h>
  6. #include "config.h"
  7. #define SPI_SPCR(rat, pha, pol, mst, dor) ((rat & 3) | (pha?(1<<CPHA):0) | (pol?(1<<CPOL):0) | (mst?(1<<MSTR):0) | (dor?(1<<DORD):0) | (1<<SPE))
  8. #define SPI_SPSR(rat) ((rat & 4)?(1<<SPI2X):0)
  9. #define DD_SS 0
  10. #define DD_SCK 1
  11. #define DD_MOSI 2
  12. #define DD_MISO 3
  13. inline void spi_init()
  14. {
  15. DDRB &= ~((1 << DD_SCK) | (1 << DD_MOSI) | (1 << DD_MISO));
  16. DDRB |= (1 << DD_SS) | (1 << DD_SCK) | (1 << DD_MOSI);
  17. PORTB &= ~((1 << DD_SCK) | (1 << DD_MOSI) | (1 << DD_MISO));
  18. PORTB |= (1 << DD_SS);
  19. SPCR = SPI_SPCR(0, 0, 0, 1, 0); //SPE=1, MSTR=1 (0x50)
  20. SPSR = 0x00;
  21. }
  22. inline void spi_setup(uint8_t spcr, uint8_t spsr)
  23. {
  24. SPCR = spcr;
  25. SPSR = spsr;
  26. }
  27. inline uint8_t spi_txrx(uint8_t tx)
  28. {
  29. SPDR = tx;
  30. while (!(SPSR & (1 << SPIF)));
  31. return SPDR;
  32. }
  33. #endif //SPI_H