1 | void init_SPI1(void){
|
2 |
|
3 | GPIO_InitTypeDef GPIO_InitStruct;
|
4 | SPI_InitTypeDef SPI_InitStruct;
|
5 |
|
6 | // enable clock for used IO pins
|
7 | RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
|
8 |
|
9 | /* configure pins used by SPI1
|
10 | * PA5 = SCK
|
11 | * PA6 = MISO
|
12 | * PA7 = MOSI
|
13 | */
|
14 | GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_6 | GPIO_Pin_5;
|
15 | GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
|
16 | GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
|
17 | GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
|
18 | GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
|
19 | GPIO_Init(GPIOA, &GPIO_InitStruct);
|
20 |
|
21 | // connect SPI1 pins to SPI alternate function
|
22 | GPIO_PinAFConfig(GPIOA, GPIO_PinSource5, GPIO_AF_SPI1);
|
23 | GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_SPI1);
|
24 | GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_SPI1);
|
25 |
|
26 | // enable clock for used IO pins
|
27 | RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
|
28 |
|
29 | /* Configure the chip select pin
|
30 | in this case we will use PE7 */
|
31 | GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7;
|
32 | GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
|
33 | GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
|
34 | GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
|
35 | GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
|
36 | GPIO_Init(GPIOE, &GPIO_InitStruct);
|
37 |
|
38 | GPIOE->BSRRL |= GPIO_Pin_7; // set PE7 high
|
39 |
|
40 | // enable peripheral clock
|
41 | RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
|
42 |
|
43 | /* configure SPI1 in Mode 0
|
44 | * CPOL = 0 --> clock is low when idle
|
45 | * CPHA = 0 --> data is sampled at the first edge
|
46 | */
|
47 | //SPI_InitStruct.SPI_Direction = SPI_Direction_2Lines_FullDuplex; // set to full duplex mode, seperate MOSI and MISO lines
|
48 | SPI_InitStruct.SPI_Direction = SPI_Direction_1Line_Tx;
|
49 | SPI_InitStruct.SPI_Mode = SPI_Mode_Master; // transmit in master mode, NSS pin has to be always high
|
50 | SPI_InitStruct.SPI_DataSize = SPI_DataSize_8b; // one packet of data is 8 bits wide
|
51 | SPI_InitStruct.SPI_CPOL = SPI_CPOL_Low; // clock is low when idle
|
52 | SPI_InitStruct.SPI_CPHA = SPI_CPHA_1Edge; // data sampled at first edge
|
53 | SPI_InitStruct.SPI_NSS = SPI_NSS_Soft; // set the NSS management to internal and pull internal NSS high
|
54 | SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; // SPI frequency
|
55 | SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;// data is transmitted MSB first
|
56 | SPI_Init(SPI1, &SPI_InitStruct);
|
57 |
|
58 | SPI_Cmd(SPI1, ENABLE); // enable SPI1
|
59 | }
|