File tree 1 file changed +69
-0
lines changed
1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * TWISLAVE.c
3
+ *
4
+ * Created: 10-09-2018 16:04:50
5
+ * Author: HP
6
+ */
7
+
8
+ #include <avr/io.h>
9
+ #ifndef TWI_FREQ
10
+ #define TWI_FREQ 100000L
11
+ #define F_CPU 16000000
12
+ #endif
13
+ void I2C_Init () /* I2C initialize function */
14
+ {
15
+ TWBR = ((F_CPU / TWI_FREQ ) - 16 ) / 2 ; /* Get bit rate register value by formula */
16
+ }
17
+ uint8_t I2C_Start (void )/* I2C start function */
18
+ {
19
+ uint8_t status ;
20
+ int x ;
21
+ DDRB = 0b11111111 ; /* Declare variable */
22
+ TWCR = (1 <<TWSTA )|(1 <<TWEN )|(1 <<TWINT ); /* Enable TWI, generate START */
23
+ while (!(TWCR & (1 <<TWINT )))
24
+ {PORTB |=4 ;
25
+ } /* Wait until TWI finish its current job */
26
+ status = TWSR & 0xF8 ; /* Read TWI status register */
27
+ if (status != 0x08 ) /* Check weather START transmitted or not? */
28
+ return 0 ; /* Return 0 to indicate start condition fail */
29
+ TWDR = 0b01111110 ; /* Write SLA+W in TWI data register */
30
+ TWCR = (1 <<TWEN )|(1 <<TWINT );
31
+ /* Enable TWI & clear interrupt flag */
32
+ while (!(TWCR & (1 <<TWINT )));
33
+ /* Wait until TWI finish its current job */
34
+ status = TWSR & 0xF8 ; /* Read TWI status register */
35
+ if (status == 0x18 ) /* Check for SLA+W transmitted &ack received */
36
+ PORTB |=1 ;
37
+ if (status == 0x20 )
38
+ PORTB = 2 ;
39
+
40
+ }
41
+ void I2C_Stop ()
42
+ {
43
+ TWCR = (1 <<TWSTO )|(1 <<TWINT )|(1 <<TWEN );
44
+ while (TWCR & (1 <<TWSTO ));
45
+ }
46
+ void I2C_Send (char x )
47
+ { uint8_t stat ;
48
+ TWDR = x ;
49
+ TWCR = (1 <<TWINT )|(1 <<TWEN );
50
+
51
+ while (!(TWCR & (1 <<TWINT )));
52
+ stat = TWSR & 0xF8 ;
53
+ if (stat == 0x28 )
54
+ PORTB |=8 ;
55
+ if (stat == 0x30 )
56
+ PORTB |=16 ;
57
+ }
58
+ int main ()
59
+ {I2C_Init ();
60
+
61
+ I2C_Start ();
62
+ I2C_Send ();
63
+ I2C_Stop ();
64
+
65
+
66
+
67
+ }
68
+
69
+
You can’t perform that action at this time.
0 commit comments