📄 spi_stm32x.c
字号:
/*----------------------------------------------------------------------------
* R T L - F l a s h F i l e S y s t e m
*----------------------------------------------------------------------------
* Name: SPI_STM32X.C
* Purpose: Serial Peripheral Interface Driver for STM32x
* Rev.: V3.14
*----------------------------------------------------------------------------
* This code is part of the RealView Run-Time Library.
* Copyright (c) 2004-2007 KEIL - An ARM Company. All rights reserved.
*---------------------------------------------------------------------------*/
#include <File_Config.h>
#include <stm32f10x_lib.h> /* STM32F10x Library Definitions */
/* SPI_SR - bit definitions. */
#define RXNE 0x01
#define TXE 0x02
#define BSY 0x80
/*----------------------------------------------------------------------------
* SPI Driver Functions
*----------------------------------------------------------------------------
* Required functions for SPI driver module:
* - void spi_init ()
* - U8 spi_send (U8 outb)
* - void spi_hi_speed (BOOL on)
*---------------------------------------------------------------------------*/
/*--------------------------- spi_init --------------------------------------*/
void spi_init (void) {
/* Initialize and enable the SSP Interface module. */
U32 i;
/* Enable clock for SPI, GPIOA and AFIO. */
RCC->APB2ENR |= 0x00001005;
/* Reset SPI remap (use PA4..PA7). */
AFIO->MAPR &= 0xFFFFFFFE;
/* SPI1_SCK, SPI1_MISO, SPI1_MOSI are SPI pins. */
GPIOA->CRL &= ~0xFFFF0000;
GPIOA->CRL |= 0xB8B30000;
/* Card Sensor PA.8 input */
/* 1 = NO Card, 0 = Card plugged. */
GPIOA->CRH &= ~0x0000000F;
GPIOA->CRH |= 0x00000004;
/* SPI1_NSS is GPIO, output set to high. */
GPIOA->BSRR = 0x00000010;
/* Enable SPI in Master Mode, CPOL=1, CPHA=1 (Clock low-active). */
SPI1->CR1 = 0x006F;
SPI1->CR2 = 0x0000;
/* Send SPI Command with card not selected at 400 KBit. */
for (i = 0; i < 16; i++) {
spi_send (0xFF);
}
/* Enable NSS auto select. */
GPIOA->CRL |= 0x000B0000;
SPI1->CR2 = 0x0004;
}
/*--------------------------- spi_hi_speed ----------------------------------*/
void spi_hi_speed (BOOL on) {
/* Set a SPI clock speed to desired value. */
if (on == __TRUE) {
/* Max. 18 MBit used for Data Transfer. */
SPI1->CR1 &= ~0x0038;
}
else {
/* Max. 400 kBit used in Card Initialization. */
SPI1->CR1 |= 0x0028;
}
}
/*--------------------------- spi_send --------------------------------------*/
U8 spi_send (U8 outb) {
/* Write and Read a byte on SPI interface. */
U8 inb;
/* Wait if TXE cleared, Tx FIFO is full. */
while ((SPI1->SR & TXE) == 0);
SPI1->DR = outb;
/* Wait if RNE cleared, Rx FIFO is empty. */
while ((SPI1->SR & RXNE) == 0);
inb = SPI1->DR;
return (inb);
}
/*----------------------------------------------------------------------------
* end of file
*---------------------------------------------------------------------------*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -