1 | ////////////////////////////////////////// TWI_M_start //////////////////////////////////////////
|
2 |
|
3 | /*
|
4 | starting TWI with slave's address and choosing mode between MT and MR
|
5 |
|
6 | read_or_write=1: MR read_or_write=0: MT option is for first sending (initialization)
|
7 |
|
8 | returns TWI_M_START_FAILED_1, TWI_M_START_FAILED_2 or START_SUCCEED
|
9 | */
|
10 | int8_t TWI_M_start(uint8_t address, uint8_t read_or_write, uint8_t option)
|
11 | {
|
12 |
|
13 | TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); // enable interrupt flag, send start, enable TWI
|
14 |
|
15 | while( ! ( TWCR & (1 << TWINT) ) ); // wait for operation
|
16 |
|
17 | if( ( (TW_STATUS) != M_START ) && ( (TW_STATUS) != M_REPEADED_START ) ) // checking error
|
18 | {
|
19 |
|
20 | TWI_M_stop();
|
21 | return TWI_M_START_FAILED_1; // return error
|
22 |
|
23 | }
|
24 |
|
25 | TWDR = ( (address << 1) + read_or_write) | option; // choosing slave showing if MR or MT mode starts
|
26 | //TWDR = (address) + read_or_write; // choosing slave showing if MR or MT mode starts
|
27 | TWCR = (1 << TWINT) | (1 << TWEN); // TWINT bit has to be set for transmission
|
28 |
|
29 | while( ! ( TWCR & (1 << TWINT) ) ); // wait for operation
|
30 |
|
31 | //if( ( (TW_STATUS & 0b11111000) != MT_SLA_W_TRANS_ACK_REC ) && ( (TW_STATUS & 0b11111000) != MR_SLA_R_TRANS_ACK_REC ) ) // checking error // TWSR // 0x18 // 0x40
|
32 | if( ( (TW_STATUS) != MT_SLA_W_TRANS_ACK_REC ) && ( (TW_STATUS) != MR_SLA_R_TRANS_ACK_REC ) )
|
33 | {
|
34 |
|
35 | TWI_M_stop();
|
36 | return TWI_M_START_FAILED_2;
|
37 |
|
38 | }
|
39 |
|
40 | return START_SUCCEED;
|
41 |
|
42 | }
|
43 |
|
44 | //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
|
45 |
|
46 |
|
47 | ////////////////////////////////////////// TWI_M_write //////////////////////////////////////////
|
48 |
|
49 | /*
|
50 | writes in TWI data register
|
51 |
|
52 | returns MT_DATA_TRAMS_FAILED or MT_DATA_TRANS_SUCCEED
|
53 | */
|
54 | int8_t TWI_M_write(uint8_t data)
|
55 | {
|
56 |
|
57 | TWDR = data; // send data
|
58 |
|
59 | TWCR = (1 << TWINT) | (1 << TWEN); // TWINT bit has to be set for transmission
|
60 |
|
61 | while( ! ( TWCR & (1 << TWINT) ) ); // wait for operation
|
62 |
|
63 | if( ( (TW_STATUS) != MT_DATA_TRANS_ACK_RETURN ) && ( (TW_STATUS) != MT_DATA_TRANS_NACK_RETURN ) ) // checking error
|
64 | {
|
65 |
|
66 | TWI_M_stop();
|
67 | return MT_DATA_TRANS_FAILED;
|
68 |
|
69 | }
|
70 |
|
71 | return MT_DATA_TRANS_SUCCEED;
|
72 |
|
73 | }
|
74 |
|
75 | //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | ////////////////////////////////////////// TWI_M_stop //////////////////////////////////////////
|
82 |
|
83 | /*
|
84 | stops TWI
|
85 |
|
86 | no return
|
87 | */
|
88 | void TWI_M_stop()
|
89 | {
|
90 |
|
91 | TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
|
92 |
|
93 | }
|
94 |
|
95 | //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
|