From 7105380682f1ab9b3f1ab06363fce0c3f2d816aa Mon Sep 17 00:00:00 2001 From: BlackMark Date: Thu, 26 May 2016 21:40:24 +0200 Subject: [PATCH] Initial commit --- spi.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ spi.h | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 spi.cpp create mode 100644 spi.h diff --git a/spi.cpp b/spi.cpp new file mode 100644 index 0000000..f83ed9f --- /dev/null +++ b/spi.cpp @@ -0,0 +1,54 @@ +#include "spi.h" + +void spiInit() +{ + SPCR |= ( 1 << SPE ) | ( 1 << MSTR ); +} + +void spiEnd() +{ + SPCR = 0; + SPSR = 0; +} + +void spiSetClockDiv( SPIClock enmClockDiv ) +{ + bool bSPI2X = ( static_cast( enmClockDiv ) >> 2 ) & 1; + bool bSPR1 = ( static_cast( enmClockDiv ) >> 1 ) & 1; + bool bSPR0 = ( static_cast( enmClockDiv ) >> 0 ) & 1; + + SPCR &= ~( 1 << SPR1 | 1 << SPR0 ); + SPSR &= ~( 1 << SPI2X ); + + SPCR |= ( bSPR1 << SPR1 | bSPR0 << SPR0 ); + SPSR |= ( bSPI2X << SPI2X ); +} + +void spiSetDataMode( SPIMode enmMode ) +{ + bool bCPOL = ( static_cast( enmMode ) >> 1 ) & 1; + bool bCPHA = ( static_cast( enmMode ) >> 0 ) & 1; + + SPCR &= ~( 1 << CPOL | 1 << CPHA ); + + SPCR |= ( bCPOL << CPOL | bCPHA << CPHA ); +} + +void spiSetBitOrder( bool bLSBFirst ) +{ + if( bLSBFirst ) + { + SPCR |= ( 1 << DORD ); + } + else + { + SPCR &= ~( 1 << DORD ); + } +} + +uint8_t spiTransfer( uint8_t ui8Data ) +{ + SPDR = ui8Data; + while( !( SPSR & ( 1 << SPIF ) ) ); + return SPDR; +} \ No newline at end of file diff --git a/spi.h b/spi.h new file mode 100644 index 0000000..3f589e5 --- /dev/null +++ b/spi.h @@ -0,0 +1,34 @@ +#ifndef SPI_H +#define SPI_H + +#include + +enum class SPIClock +{ + CLOCKDIV_4 = 0, + CLOCKDIV_16 = 1, + CLOCKDIV_64 = 2, + CLOCKDIV_128 = 3, + + CLOCKDIV2X_2 = 4, + CLOCKDIV2X_8 = 5, + CLOCKDIV2X_32 = 6, + CLOCKDIV2X_64 = 7 +}; + +enum class SPIMode +{ + MODE0 = 0, + MODE1 = 1, + MODE2 = 2, + MODE3 = 3 +}; + +void spiInit(); +void spiEnd(); +void spiSetClockDiv( SPIClock enmClockDiv ); +void spiSetDataMode( SPIMode enmMode ); +void spiSetBitOrder( bool bLSBFirst ); +uint8_t spiTransfer( uint8_t ui8Data ); + +#endif \ No newline at end of file