spi.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. #if defined(__cplusplus)
  14. extern "C" {
  15. #endif //defined(__cplusplus)
  16. static inline void spi_init()
  17. {
  18. DDRB &= ~((1 << DD_SCK) | (1 << DD_MOSI) | (1 << DD_MISO));
  19. DDRB |= (1 << DD_SS) | (1 << DD_SCK) | (1 << DD_MOSI);
  20. PORTB &= ~((1 << DD_SCK) | (1 << DD_MOSI) | (1 << DD_MISO));
  21. PORTB |= (1 << DD_SS);
  22. SPCR = SPI_SPCR(0, 0, 0, 1, 0); //SPE=1, MSTR=1 (0x50)
  23. SPSR = 0x00;
  24. }
  25. static inline void spi_setup(uint8_t spcr, uint8_t spsr)
  26. {
  27. SPCR = spcr;
  28. SPSR = spsr;
  29. }
  30. static inline uint8_t spi_txrx(uint8_t tx)
  31. {
  32. SPDR = tx;
  33. while (!(SPSR & (1 << SPIF)));
  34. return SPDR;
  35. }
  36. #if defined(__cplusplus)
  37. }
  38. #endif //defined(__cplusplus)
  39. #endif //SPI_H