615 |
kaklik |
1 |
#ifndef __twi_aap_h__ |
|
|
2 |
#define __two_aap_h__ |
|
|
3 |
|
|
|
4 |
#include <compat/twi.h> |
|
|
5 |
|
|
|
6 |
#include "common.h" |
|
|
7 |
#include "usart.h" |
|
|
8 |
#include "guids.h" |
|
|
9 |
#include "eeprom.h" |
|
|
10 |
//#define SERIAL_DBG |
|
|
11 |
|
|
|
12 |
namespace EEPROM_layout { |
|
|
13 |
const uint16_t TWI_SoftAddr_Ofs = 0xff; |
|
|
14 |
} |
|
|
15 |
|
|
|
16 |
namespace TWI { |
|
|
17 |
const uint8_t GeneralCallAddr = 0; |
|
|
18 |
const size_t UniqueID_Size = 16*3; |
|
|
19 |
const size_t GUID_Size = sizeof(GUID); |
|
|
20 |
|
|
|
21 |
struct sConfigRecord { |
|
|
22 |
uint8_t UniqueID[UniqueID_Size]; |
|
|
23 |
GUID ClassID; |
|
|
24 |
GUID DevID; |
|
|
25 |
}; |
|
|
26 |
|
|
|
27 |
enum TWI_AAPCommands { |
|
|
28 |
TWI_AAPCmd_Reserved = 0, |
|
|
29 |
TWI_AAPCmd_Start = 0x20, |
|
|
30 |
TWI_AAPCmd_End = 0x21, |
|
|
31 |
TWI_AAPCmd_ResetDevices = 0x22, |
|
|
32 |
TWI_AAPCmd_ResetToPermAddress = 0x23, |
|
|
33 |
TWI_AAPCmd_GetConfig = 0x24, |
|
|
34 |
TWI_AAPCmd_AssignAddress = 0x25 |
|
|
35 |
}; |
|
|
36 |
enum MainStates { |
|
|
37 |
MS_Idle = 0, |
|
|
38 |
MS_Addressed, |
|
|
39 |
AAP_CmdGetConfig_GetAddress, |
|
|
40 |
AAP_CmdGetConfig_SendConfig, |
|
|
41 |
AAP_CmdAssignAddress_GetUniqueID, |
|
|
42 |
AAP_CmdAssignAddress_GetAddress, |
|
|
43 |
US_Base |
|
|
44 |
}; |
|
|
45 |
|
|
|
46 |
extern uint8_t State; |
|
|
47 |
extern uint8_t LastCmd; |
|
|
48 |
extern uint8_t SoftAddress; |
|
|
49 |
|
|
|
50 |
inline void Init() { |
|
|
51 |
TWBR = 32; // 100kHz with an 8MHz crystal |
|
|
52 |
// TWBR = 16; // 200kHz with an 8MHz crystal |
|
|
53 |
TWSR = 0; // pre-scaler: 1 |
|
|
54 |
TWCR = (1 << TWEA) | (1 << TWEN) | (1 << TWIE) | (1 << TWINT); |
|
|
55 |
if (TWSR == TW_BUS_ERROR) SETBIT(TWCR,(1 << TWSTO)); // reset TWI |
|
|
56 |
TWAMR = 0; // all address bits matter |
|
|
57 |
State = MS_Idle; |
|
|
58 |
SoftAddress = EEPROM::GetByte(EEPROM_layout::TWI_SoftAddr_Ofs); |
|
|
59 |
if (SoftAddress == 0xff) SoftAddress = 0; |
|
|
60 |
SoftAddress &= 0xfe; |
|
|
61 |
// TWAR = GeneralCallAddr | 1; // General call recognition and slave-receiver mode through address being 0 |
|
|
62 |
TWAR = SoftAddress | 1; |
|
|
63 |
LastCmd = TWI_AAPCmd_Reserved; |
|
|
64 |
} |
|
|
65 |
|
|
|
66 |
// These used in all states, including user states, so make them available. |
|
|
67 |
extern uint8_t TWIStatus; |
|
|
68 |
extern uint8_t TWIData; |
|
|
69 |
extern uint8_t TWIPrevData; |
|
|
70 |
extern uint8_t TWIControl; |
|
|
71 |
|
|
|
72 |
void ResetTWITransmit(); |
|
|
73 |
void ResetTWIReceive(); |
|
|
74 |
void ResetTWI(); |
|
|
75 |
} |
|
|
76 |
|
|
|
77 |
#endif // __twi_aap_h__ |