-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi2c.c
More file actions
51 lines (36 loc) · 888 Bytes
/
i2c.c
File metadata and controls
51 lines (36 loc) · 888 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
44
45
46
47
48
49
50
51
/*
* i2c.c
*
* Created: 2/4/2022 1:43:16 PM
* Author: Ali
*/
#include <avr/io.h>
#include <util/twi.h>
#include <util/delay.h>
void start_twi(uint8_t addr){
TWBR=0x0a; //pre-scaler setting
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
while(!(TWCR & (1<<TWINT)))
;
if((TWSR & 0xF8) !=TW_START);
// Some error checking required
//Write SLA+W (7bit address + R/W flag) to the TWDR and send it
TWDR = ((addr & 0x7f)<<1);
TWCR = (1<<TWINT) | (1<<TWEN);// To be checked
while (!(TWCR & (1<<TWINT)))
;
if((TWSR & 0xF8) != TW_MT_SLA_ACK);
// Some error checking required
}
void i2c_send(uint8_t data)
{
TWDR = data;
TWCR = (1<<TWINT) | (1<<TWEN);
_delay_us(1);
while (!(TWCR & (1<<TWINT)))
;
if((TWSR & 0xF8) != TW_MT_DATA_ACK);
}
void stop_twi(){
TWCR=(1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
}