-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi2c.cpp
More file actions
43 lines (39 loc) · 703 Bytes
/
i2c.cpp
File metadata and controls
43 lines (39 loc) · 703 Bytes
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
#ifndef I2C_CPP_
#define I2C_CPP_
#include<avr/io.h>
class Twi
{
public:
Twi(void)
{
TWSR = 0x00;
TWBR = 1;
TWCR = (1<<TWEN);
}
void start(void)
{
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while((TWCR & (1<<TWINT))==0);
}
void write(char data)
{
TWDR = data;
TWCR = (1<< TWEN)|(1<<TWINT);
while((TWCR & (1<<TWINT))==0);
}
char read(uint8_t a)
{
if(a) //1 for ACK
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
else //2 for NACK
TWCR = (1<<TWINT)|(1<<TWEN);
while((TWCR&(1<<TWINT))==0);
return TWDR;
}
void stop(void)
{
TWCR = (1<<TWEN)|(1<<TWSTO)|(1<<TWINT);
while(TWCR & (1<<TWSTO));
}
};
#endif