00001 /************************************************************************* 00002 Author: $Author: dennis $ 00003 File: $HeadURL: file:///home/dennis/svn-store/avr-source/mptry-fat32/html/spi_8c-source.html $ 00004 Date: $Date: 2008-09-17 19:39:04 +0200 (Mi, 17. Sep 2008) $ 00005 Revision: $Revision: 111 $ 00006 Id: $Id: spi_8c-source.html 111 2008-09-17 17:39:04Z dennis $ 00007 Licence: GNU General Public License 00008 *************************************************************************/ 00009 00010 #include "spi.h" 00011 00012 #include <avr/io.h> 00013 00020 uint8_t spi_init() { 00021 /* enable outputs for MOSI, SCK, SS, input for MISO */ 00022 configure_pin_mosi(); 00023 configure_pin_sck(); 00024 configure_pin_ss(); 00025 configure_pin_miso(); 00026 00027 /* initialize SPI with lowest frequency; max. 400kHz during identification mode of card */ 00028 /*| SPR1 | SPR0 | SCK-Frequenz | 00029 ---------------------------------- 00030 | 0 | 0 | clk/4 | 00031 | 0 | 1 | clk/16 |<-- max for my experimental board with long lines 00032 | 1 | 0 | clk/64 | 00033 | 1 | 1 | clk/128 |*/ 00034 00035 00036 SPCR = (0 << SPIE) | /* SPI Interrupt Enable */ 00037 (1 << SPE) | /* SPI Enable */ 00038 (0 << DORD) | /* Data Order: MSB first */ 00039 (1 << MSTR) | /* Master mode */ 00040 (0 << CPOL) | /* Clock Polarity: SCK low when idle */ 00041 (0 << CPHA) | /* Clock Phase: sample on rising SCK edge */ 00042 (1 << SPR1) | /* Clock Frequency: f_OSC / 64 */ 00043 (0 << SPR0); 00044 SPSR &= ~(1 << SPI2X); /* No doubled clock frequency */ 00045 return 0; 00046 } 00047 uint8_t spi_set_maxspeed() { 00054 /* switch to highest SPI frequency possible */ 00055 //SPCR &= ~((1 << SPR1) | ~(1 << SPR0)); /* Clock Frequency: f_OSC / 4 */ 00056 SPCR &= ~(1 << SPR1); 00057 SPCR |= (1 << SPR0); /* Clock Frequency: f_OSC / 16 now */ 00058 SPSR |= (1 << SPI2X); /* Doubled Clock Frequency --> f_OSC / 8 */ 00059 return 0; 00060 } 00061 00069 uint8_t spi_read_byte() { 00070 /* send dummy data for receiving some */ 00071 SPDR = 0xff; 00072 /* wait for dummy byte to be shifted out */ 00073 while(!(SPSR & (1 << SPIF))) 00074 ; 00075 /* wait for byte to be shifted in */ 00076 SPSR &= ~(1 << SPIF); 00077 00078 return SPDR; 00079 } 00080 00088 uint8_t spi_write_byte( int8_t byte ) { 00089 SPDR = byte; 00090 /* wait for byte to be shifted out */ 00091 while(!(SPSR & (1 << SPIF))) 00092 ; 00093 SPSR &= ~(1 << SPIF); 00094 return SPDR; 00095 }