forked from WiseLord/ampcontrol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi2c.c
80 lines (57 loc) · 1.22 KB
/
i2c.c
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
#include "i2c.h"
#include <avr/io.h>
void I2CInit(void)
{
// SCL = F_CPU / (16 + 2 * TWBR * prescaler)
// SCL = 16000000 / (16 + 2 * 18 * 4)
TWBR = 18;
TWSR = (0<<TWPS1) | (1<<TWPS0); // Prescaler = 4
TWCR |= (1<<TWEN); // Enable TWI
return;
}
void I2CStart(uint8_t addr)
{
uint8_t i = 0;
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTA); // Start
while(bit_is_clear(TWCR, TWINT)) {
if (i++ > 250) // Avoid endless loop
return;
}
I2CWriteByte(addr);
return;
}
void I2CStop(void)
{
uint8_t i = 0;
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Stop
while (bit_is_set(TWCR, TWSTO)) { // Wait for TWSTO
if (i++ > 250) // Avoid endless loop
break;
}
return;
}
void I2CWriteByte(uint8_t data)
{
uint8_t i = 0;
TWDR = data;
TWCR = (1<<TWEN) | (1<<TWINT); // Start data transfer
while (bit_is_clear(TWCR, TWINT)) { // Wait for finish
if (i++ > 250) // Avoid endless loop
break;
}
return;
}
uint8_t I2CReadByte(uint8_t ack)
{
uint8_t i = 0;
if (ack)
TWCR |= (1<<TWEA);
else
TWCR &= ~(1<<TWEA);
TWCR |= (1 << TWINT);
while (bit_is_clear(TWCR, TWINT)) { // Wait for finish
if (i++ > 250) // Avoid endless loop
break;
}
return TWDR;
}