1 | void SPI2_Init(void)
|
2 | {
|
3 | GPIO_InitTypeDef GPIO_InitStructure;
|
4 | SPI_InitTypeDef SPI_InitStructure;
|
5 |
|
6 | RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
|
7 | RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
|
8 | RCC_APB2PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
|
9 |
|
10 | SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
|
11 | SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
|
12 | SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
|
13 | SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
|
14 | SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
|
15 | SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
|
16 | SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
|
17 | SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
|
18 | SPI_InitStructure.SPI_CRCPolynomial = 7;
|
19 | SPI_Init(SPI2, &SPI_InitStructure);
|
20 |
|
21 | // Connect SPI pins to AF
|
22 | GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_SPI2);
|
23 | GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_SPI2);
|
24 | GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2);
|
25 |
|
26 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
27 | GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
28 | GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
29 | GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
30 |
|
31 | // SPI SCK pin configuration
|
32 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
|
33 | GPIO_Init(GPIOB, &GPIO_InitStructure);
|
34 |
|
35 | // SPI MISO pin configuration
|
36 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
|
37 | GPIO_Init(GPIOB, &GPIO_InitStructure);
|
38 |
|
39 | // SPI MOSI pin configuration
|
40 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
|
41 | GPIO_Init(GPIOB, &GPIO_InitStructure);
|
42 |
|
43 | // CS as output
|
44 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
|
45 | GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
46 | GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
47 | GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
48 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
|
49 | GPIO_Init(GPIOA, &GPIO_InitStructure);
|
50 |
|
51 | SPI_Cmd(SPI2, ENABLE);
|
52 | }
|
53 |
|
54 | void SPI2_TxByte(uint8_t byte)
|
55 | {
|
56 | while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_TXE) == RESET);
|
57 | SPI_I2S_SendData(SPI2, byte);
|
58 | }
|