spi

Dependents:   MusicShield

Committer:
Jackson_lv
Date:
Mon Jul 13 09:21:53 2015 +0000
Revision:
0:4a8f916ef7b5
spi

Who changed what in which revision?

UserRevisionLine numberNew contents of line
Jackson_lv 0:4a8f916ef7b5 1 #include "spi.h"
Jackson_lv 0:4a8f916ef7b5 2
Jackson_lv 0:4a8f916ef7b5 3 SPI device(SPI_MOSI, SPI_MISO, SPI_SCK);
Jackson_lv 0:4a8f916ef7b5 4
Jackson_lv 0:4a8f916ef7b5 5 //SPI Init Code,visit SD Card/W25Q64/NRF24L01
Jackson_lv 0:4a8f916ef7b5 6 //SPI PIN Init
Jackson_lv 0:4a8f916ef7b5 7 void SPI_Init(void)
Jackson_lv 0:4a8f916ef7b5 8 {
Jackson_lv 0:4a8f916ef7b5 9
Jackson_lv 0:4a8f916ef7b5 10 //SPI2 clock frequence less than 36Mhz
Jackson_lv 0:4a8f916ef7b5 11 SPI.frequency(36000000/256);
Jackson_lv 0:4a8f916ef7b5 12 SPI_ReadWriteByte(0xff);//start transfer
Jackson_lv 0:4a8f916ef7b5 13 }
Jackson_lv 0:4a8f916ef7b5 14
Jackson_lv 0:4a8f916ef7b5 15
Jackson_lv 0:4a8f916ef7b5 16 //SPI Speed Setting
Jackson_lv 0:4a8f916ef7b5 17 //SpeedSet:0~7
Jackson_lv 0:4a8f916ef7b5 18 //SPI Speed = fAPB1/2^(SpeedSet+1)
Jackson_lv 0:4a8f916ef7b5 19 //APB1 clock usually is 36Mhz
Jackson_lv 0:4a8f916ef7b5 20 void SPI_SetSpeed(uint8_t SpeedSet)
Jackson_lv 0:4a8f916ef7b5 21 {
Jackson_lv 0:4a8f916ef7b5 22 SpeedSet&=0X07; //limit
Jackson_lv 0:4a8f916ef7b5 23 SPI->CR1&=0XFFC7;
Jackson_lv 0:4a8f916ef7b5 24 SPI->CR1|=SpeedSet<<3; //setting SPI speed
Jackson_lv 0:4a8f916ef7b5 25 SPI->CR1|=1<<6; //SPI device enabled
Jackson_lv 0:4a8f916ef7b5 26 }
Jackson_lv 0:4a8f916ef7b5 27
Jackson_lv 0:4a8f916ef7b5 28
Jackson_lv 0:4a8f916ef7b5 29 //SPI readWrite a Byte
Jackson_lv 0:4a8f916ef7b5 30 //TxData:the data to write
Jackson_lv 0:4a8f916ef7b5 31 //return:the data read back
Jackson_lv 0:4a8f916ef7b5 32 u8 SPI_ReadWriteByte(uint8_t TxData)
Jackson_lv 0:4a8f916ef7b5 33 {
Jackson_lv 0:4a8f916ef7b5 34 u16 retry=0;
Jackson_lv 0:4a8f916ef7b5 35 while((SPI->SR&1<<1)==0) //waiting sending array is empty
Jackson_lv 0:4a8f916ef7b5 36 {
Jackson_lv 0:4a8f916ef7b5 37 retry++;
Jackson_lv 0:4a8f916ef7b5 38 if(retry>=0XFFFE)return 0; //out of time quit
Jackson_lv 0:4a8f916ef7b5 39 }
Jackson_lv 0:4a8f916ef7b5 40 SPI->DR=TxData; //send one byte
Jackson_lv 0:4a8f916ef7b5 41 retry=0;
Jackson_lv 0:4a8f916ef7b5 42 while((SPI->SR&1<<0)==0) //waiting received a byte
Jackson_lv 0:4a8f916ef7b5 43 {
Jackson_lv 0:4a8f916ef7b5 44 retry++;
Jackson_lv 0:4a8f916ef7b5 45 if(retry>=0XFFFE)return 0; //out of time quit
Jackson_lv 0:4a8f916ef7b5 46 }
Jackson_lv 0:4a8f916ef7b5 47 return SPI->DR; //return the data read
Jackson_lv 0:4a8f916ef7b5 48 }
Jackson_lv 0:4a8f916ef7b5 49
Jackson_lv 0:4a8f916ef7b5 50
Jackson_lv 0:4a8f916ef7b5 51
Jackson_lv 0:4a8f916ef7b5 52
Jackson_lv 0:4a8f916ef7b5 53
Jackson_lv 0:4a8f916ef7b5 54
Jackson_lv 0:4a8f916ef7b5 55
Jackson_lv 0:4a8f916ef7b5 56