-
Notifications
You must be signed in to change notification settings - Fork 6
/
I2C.c
76 lines (57 loc) · 1.56 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
#include "I2C.h"
#define F_SCL 400000UL // SCL frequency
#define Prescaler 1
#define TWBR_val ((((F_CPU / F_SCL) / Prescaler) - 16 ) / 2)
void I2C_master_init(void)
{
TWBR = 12; // for 400K scl and 16Mhz freq uc
}
void I2C_master_start()
{
// transmit START condition
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
// wait for end of transmission
while( GETBIT(TWCR,TWINT) == 0);
}
void I2C_master_addr(uint8_t addr)
{ // for write op you should put 0 on LSB
// load slave address into data register
TWDR = addr<<1; // write operation
// start transmission of address
TWCR = (1<<TWINT) | (1<<TWEN);
// wait for end of transmission
while( GETBIT(TWCR,TWINT) == 0);
}
void I2C_master_write(uint8_t data)
{
// load data into data register
TWDR = data;
// start transmission of data
TWCR = (1<<TWINT) | (1<<TWEN);
// wait for end of transmission
while( !(TWCR & (1<<TWINT)) );
// while( GETBIT(TWCR,TWINT) == 0);
}
void I2C_master_stop(void)
{
// transmit STOP condition
TWCR = (1<<TWINT) | (1<<TWSTO) | 1<<TWEN;
}
void I2C_slave_Init(uint8_t My_Add){
TWAR = My_Add<<1;
}
uint8_t I2C_slave_avialable(){
TWCR = (1<<TWEN) | (1<<TWINT) |(1<<TWEA);
while( GETBIT(TWCR,TWINT) == 0);
if(TWSR == 0x60) return 1;
else return 0;
}
uint8_t I2C_slave_read(void)
{
// start TWI module and acknowledge data after reception
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
// wait for end of transmission
while( GETBIT(TWCR,TWINT) == 0);
// return received data from TWDR
return TWDR;
}