#include "spi.h" #include "stm32f4xx_gpio.h" #include "stm32f4xx_spi.h" #include "stm32f4xx.h" #if !defined(SPI_HARD) void RF_SPI_SCK_H(void) { GPIO_WriteBit(RF_SPI_SCK_Port, RF_SPI_SCK_IO, Bit_SET); } void RF_SPI_SCK_L(void) { GPIO_WriteBit(RF_SPI_SCK_Port, RF_SPI_SCK_IO, Bit_RESET); } void RF_SPI_MISO_H(void) { GPIO_WriteBit(RF_SPI_MISO_Port, RF_SPI_MISO_IO, Bit_SET); } void RF_SPI_MISO_L(void) { GPIO_WriteBit(RF_SPI_MISO_Port, RF_SPI_MISO_IO, Bit_RESET); } void RF_SPI_MISO_SETMODE(GPIOMode_TypeDef mode) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = RF_SPI_MISO_IO; GPIO_InitStructure.GPIO_Mode = mode; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(RF_SPI_MISO_Port, &GPIO_InitStructure); } uint8_t READ_RF_SPI_MISO(void) { return GPIO_ReadInputDataBit(RF_SPI_MISO_Port, RF_SPI_MISO_IO); } #endif void RF_SPI_NSS_H(void) { GPIO_WriteBit(RF_SPI_NSS_Port, RF_SPI_NSS_IO, Bit_SET); } void RF_SPI_NSS_L(void) { GPIO_WriteBit(RF_SPI_NSS_Port, RF_SPI_NSS_IO, Bit_RESET); } void spi_init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE); //使能GPIOA时钟 GPIO_InitStructure.GPIO_Pin = RF_SPI_MISO_IO; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(RF_SPI_MISO_Port, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = RF_SPI_SCK_IO; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(RF_SPI_SCK_Port, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = RF_SPI_NSS_IO; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(RF_SPI_NSS_Port, &GPIO_InitStructure); //GPIOF9,F10初始化设置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //无上下拉 GPIO_Init(GPIOB, &GPIO_InitStructure);//初始化 GPIO_ResetBits(GPIOB,GPIO_Pin_9); RF_SPI_NSS_H(); } void SpiWrite(uint8_t byteToWrite) { uint8_t i; __set_PRIMASK(1); //全局中断关闭 RF_SPI_MISO_SETMODE(GPIO_Mode_OUT); for(i=0; i<8; i++) { RF_SPI_SCK_L(); if(byteToWrite & 0x80) { RF_SPI_MISO_H(); } else { RF_SPI_MISO_L(); } RF_SPI_SCK_H(); byteToWrite <<= 1; } RF_SPI_MISO_SETMODE(GPIO_Mode_IN); RF_SPI_SCK_L(); __set_PRIMASK(0); //全局中断打开 } uint8_t SpiRead(void) { uint8_t i, temp; temp = 0; __set_PRIMASK(1); //全局中断关闭 for(i=0; i<8; i++) { RF_SPI_SCK_L(); temp <<= 1; RF_SPI_SCK_H(); if(READ_RF_SPI_MISO()) { temp ++; } } RF_SPI_SCK_L(); __set_PRIMASK(0); //全局中断打开 return temp; }