-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSPI_BitBang.cpp
112 lines (79 loc) · 2.08 KB
/
SPI_BitBang.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//--------------------------------------------------------------------------------
//
// Bit bang data.
//
// Author: VIncent Gijsen
// STM8S103 / STM8S003
// BITBang SPI
// 8 bit, MSB first, clock eval on traing rising edge
// INactive clock High,
//
#include "main.h"
#include "stm8s_gpio.h"
#include "SPI_BitBang.h"
#include "delay.h"
#define DATA_LOW GPIO_WriteLow(_pMosi, (GPIO_Pin_TypeDef)_mosi)
#define DATA_HIGH GPIO_WriteHigh(_pMosi, (GPIO_Pin_TypeDef)_mosi)
#define CLOCK_LOW GPIO_WriteLow(_pClk, (GPIO_Pin_TypeDef)_clk)
#define CLOCK_HIGH GPIO_WriteHigh(_pClk, (GPIO_Pin_TypeDef)_clk)
#define MISO GPIO_ReadInputPin(_pMiso, (GPIO_Pin_TypeDef)_miso)
SPI_BitBang::SPI_BitBang(GPIO_TypeDef * pClk,
GPIO_TypeDef * pMosi,
GPIO_TypeDef * pMiso,
const uint8_t clk,
const uint8_t mosi,
const uint8_t miso)
{
_pClk = pClk;
_pMosi = pMosi;
_pMiso = pMiso;
_clk = clk;
_mosi = mosi;
_miso = miso;
_delay = 1;
_mode = MODE0;
_rate = FAST;
}
void SPI_BitBang::begin(){
GPIO_Init(_pClk, (GPIO_Pin_TypeDef)_clk, GPIO_MODE_OUT_PP_LOW_SLOW);
GPIO_Init(_pMosi, (GPIO_Pin_TypeDef)_mosi, GPIO_MODE_OUT_PP_LOW_SLOW); //output, pp
GPIO_Init(_pMiso, (GPIO_Pin_TypeDef)_miso, GPIO_MODE_IN_FL_NO_IT); //init as input,floating, no interupt
SPI_BitBang::setDataRate(_rate);
CLOCK_LOW;
DATA_LOW;
}
void SPI_BitBang::setDataMode(SPI_BitBang::DataMode mode){
_mode = mode;
}
void SPI_BitBang::setDataRate(SPI_BitBang::DataRate rate){
switch(rate){
case SLOW:
_delay = 100;
break;
case FAST:
_delay = 1;
break;
}
};
uint8_t SPI_BitBang::transfer(uint8_t b)
{
uint8_t res = 0;
for(uint8_t _bit = 0;_bit < 8;_bit++)
{
CLOCK_HIGH;
__delay_cycles(_delay);
if (b&0x80)
DATA_HIGH;
else
DATA_LOW;
b <<= 1;
CLOCK_LOW;
__delay_cycles(_delay);
res <<=1;
if(MISO !=0){
res |=1;
}
__delay_cycles(_delay);
}
return res;
}