-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySPI.c
More file actions
75 lines (64 loc) · 1.49 KB
/
Copy pathMySPI.c
File metadata and controls
75 lines (64 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "stm32f10x.h"
#define SS_PIN GPIO_Pin_12
#define SCK_PIN GPIO_Pin_13
#define MOSI_PIN GPIO_Pin_15
#define MISO_PIN GPIO_Pin_14
void MySPI_W_SS(uint8_t BitValue)
{
GPIO_WriteBit(GPIOB,SS_PIN,(BitAction)BitValue);
}
void MySPI_W_SCK(uint8_t BitValue)
{
GPIO_WriteBit(GPIOB,SCK_PIN,(BitAction)BitValue);
}
void MySPI_W_MOSI(uint8_t BitValue)
{
GPIO_WriteBit(GPIOB,MOSI_PIN,(BitAction)BitValue);
}
uint8_t MySPI_R_MISO(void)
{
return GPIO_ReadInputDataBit(GPIOB,MISO_PIN);
}
void MySPI_Start(void)
{
MySPI_W_SS(0);
}
void MySPI_Stop(void)
{
MySPI_W_SS(1);
}
void MySPI_Init(void)
{
// 外設時鐘配置
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
// GPIO配置
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=SS_PIN | SCK_PIN | MOSI_PIN; // SS、SCK、MOSI
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin=MISO_PIN; // MISO
GPIO_Init(GPIOB,&GPIO_InitStructure);
// 默認不選中從機
MySPI_W_SS(1);
// 模式0,默認低電位
MySPI_W_SCK(0);
}
uint8_t MySPI_SwapByte(uint8_t ByteSend)
{
uint8_t ByteReceive=0x00; // 從機那裡接收到的數據
uint8_t i;
// 不用管MISO,管MOSI即可因為這裡是主機
for(i=0;i<8;i++)
{
MySPI_W_MOSI(ByteSend & (0x80 >> i));
MySPI_W_SCK(1);
if(MySPI_R_MISO() == 1)
{
ByteReceive |= (0x80 >> i);
}
MySPI_W_SCK(0);
}
return ByteReceive;
}