• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2>
3  *
4  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
5  * You may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *        http://www.st.com/software_license_agreement_liberty_v2
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "spi.h"
18 #include "stm32f4xx_conf.h"
19 
Spi1Init(void)20 void Spi1Init(void)
21 {
22     GPIO_InitTypeDef gpioInitStructure;
23     SPI_InitTypeDef spiInitStructure;
24 
25     RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
26     RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
27 
28     gpioInitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_4 | GPIO_Pin_3;
29     gpioInitStructure.GPIO_Mode = GPIO_Mode_AF;
30     gpioInitStructure.GPIO_OType = GPIO_OType_PP;
31     gpioInitStructure.GPIO_Speed = GPIO_Speed_100MHz;
32     gpioInitStructure.GPIO_PuPd = GPIO_PuPd_UP;
33     GPIO_Init(GPIOB, &gpioInitStructure);
34 
35     GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_SPI1);
36     GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_SPI1);
37     GPIO_PinAFConfig(GPIOB, GPIO_PinSource3, GPIO_AF_SPI1);
38 
39     RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE);
40     RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE);
41 
42     spiInitStructure.SPI_CRCPolynomial = 7;
43     spiInitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
44     spiInitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
45     spiInitStructure.SPI_Mode = SPI_Mode_Master;
46     spiInitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
47     spiInitStructure.SPI_DataSize = SPI_DataSize_8b;
48     spiInitStructure.SPI_NSS = SPI_NSS_Soft;
49     spiInitStructure.SPI_CPOL = SPI_CPOL_High;
50     spiInitStructure.SPI_CPHA = SPI_CPHA_2Edge;
51 
52     SPI_Init(SPI1, &spiInitStructure);
53     SPI_Cmd(SPI1, ENABLE);
54     Spi1ReadWriteByte(0xff);
55 }
56 
Spi1SetSpeed(u8 spiBaudRatePrescaler)57 void Spi1SetSpeed(u8 spiBaudRatePrescaler)
58 {
59     assert_param(IS_SPI_BAUDRATE_PRESCALER(spiBaudRatePrescaler));
60     SPI1->CR1 &= 0XFFC7;
61     SPI1->CR1 |= spiBaudRatePrescaler;
62     SPI_Cmd(SPI1, ENABLE);
63 }
64 
Spi1ReadWriteByte(u8 txData)65 u8 Spi1ReadWriteByte(u8 txData)
66 {
67     while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET) {
68         ;
69     }
70 
71     SPI_I2S_SendData(SPI1, txData);
72 
73     while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET) {
74         ;
75     }
76 
77     return SPI_I2S_ReceiveData(SPI1);
78 }
79