blob: 77eb67a41f6670489eb43145491c373bc79da11c (
plain)
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
|
#include "i2c.h"
#include "stm32.h"
void I2C::enable() {
RCC.enable(RCC.I2C1);
asm volatile("nop");
I2C1.CR1 = 0x8000;
I2C1.CR1 = 0;
I2C1.CR2 = 36;
I2C1.TRISE = 37;
I2C1.CCR = 180;
I2C1.CR1 = 1;
}
void I2C::write_reg(uint8_t addr, uint8_t reg, uint8_t data) {
I2C1.CR1 |= 0x100;
while(!(I2C1.SR1 & 0x01));
I2C1.DR = (addr << 1) | 0;
while (!(I2C1.SR1 & 0x02));
I2C1.SR2;
I2C1.DR = reg;
while (!(I2C1.SR1 & 0x80));
I2C1.DR = data;
while (!(I2C1.SR1 & 0x04));
I2C1.CR1 |= 0x200;
}
void I2C::read_reg(uint8_t addr, uint8_t reg, uint8_t len, uint8_t* buf) {
I2C1.CR1 |= 0x100;
while(!(I2C1.SR1 & 0x01));
I2C1.DR = (addr << 1) | 0;
while (!(I2C1.SR1 & 0x02));
I2C1.SR2;
I2C1.DR = reg;
while (!(I2C1.SR1 & 0x80));
I2C1.CR1 |= 0x100;
while(!(I2C1.SR1 & 0x01));
I2C1.DR = (addr << 1) | 1;
while (!(I2C1.SR1 & 0x02));
I2C1.SR2;
I2C1.CR1 |= 0x400; // Set ACK.
while(len) {
if(len == 3) {
while (!(I2C1.SR1 & 0x04)); // Wait for BTF
I2C1.CR1 &= ~0x400; // Clear ACK.
*buf++ = I2C1.DR;
len--;
I2C1.CR1 |= 0x200; // Set STOP.
*buf++ = I2C1.DR;
len--;
} else {
while (!(I2C1.SR1 & 0x40)); // Wait for RXNE
*buf++ = I2C1.DR;
len--;
}
}
}
|