1 | #include <stdio.h>
|
2 | #include <avr/interrupt.h>
|
3 |
|
4 | #include "TWI_Slave.h"
|
5 |
|
6 | /**
|
7 | * @brief Initialise the TWI Slave Interface
|
8 | * @param[in] Address Slave address
|
9 | * @param[in] Bitrate TWI_Bitrate (Hz)
|
10 | *
|
11 | * @return FALSE Bitrate too high
|
12 | * @return TRUE Bitrate OK
|
13 | */
|
14 | uint8_t TWIS_Init (uint8_t Address, uint32_t Bitrate)
|
15 | {
|
16 | /*
|
17 | ** Set the TWI bitrate
|
18 | ** If TWBR is less 11, then error
|
19 | */
|
20 | TWBR = ((F_CPU/Bitrate)-16)/2;
|
21 | if (TWBR < 11) return FALSE;
|
22 | /*
|
23 | ** Set the TWI slave address
|
24 | */
|
25 | TWAR = (Address << 1);
|
26 | /*
|
27 | ** Activate TWI interface
|
28 | */
|
29 | TWCR = (1<<TWEN)|(1<<TWEA)|(1<<TWIE);
|
30 |
|
31 | return TRUE;
|
32 | }
|
33 | /**
|
34 | * @brief Stop the TWI Slave Interface
|
35 | */
|
36 | void TWIS_Stop (void)
|
37 | {
|
38 | TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO)|(1<<TWEA)|(0<<TWSTA)|(1<<TWSTO)|(0<<TWWC)|(1<<TWIE);
|
39 | }
|
40 |
|
41 | /**
|
42 | * @brief Write a byte to the master
|
43 | *
|
44 | * @param[in] byte to be sent
|
45 | *
|
46 | * @return TRUE OK, Byte sent
|
47 | * @return FALSE Error in byte transmission
|
48 | */
|
49 | void TWIS_Write (uint8_t byte)
|
50 | {
|
51 | TWDR = byte;
|
52 | TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
|
53 | while (!(TWCR & (1<<TWINT)));
|
54 | }
|
55 |
|
56 | /**
|
57 | * @brief Read a byte from the master and request next byte
|
58 | * @return Read byte
|
59 | */
|
60 | uint8_t TWIS_ReadAck (void)
|
61 | {
|
62 | TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
|
63 | while (!(TWCR & (1<<TWINT)));
|
64 | return TWDR;
|
65 | }
|
66 |
|
67 | /**
|
68 | * @brief Read the last byte from the master
|
69 | * @return Read byte
|
70 | */
|
71 | uint8_t TWIS_ReadNack (void)
|
72 | {
|
73 | TWCR = (1<<TWINT)|(1<<TWEN);
|
74 | while (!(TWCR & (1<<TWINT)));
|
75 | return TWDR;
|
76 | }
|
77 |
|
78 | /**
|
79 | * @brief Get the response type to be performed by slave
|
80 | * @param[in] *TWI_ResonseType Pointer to response type
|
81 | * - TWIS_ReadBytes --> Read byte(s) from master
|
82 | * - TWIS_WriteBytes --> Write byte(s) to master
|
83 | *
|
84 | * @return Response required
|
85 | * - TRUE: Yes, response required
|
86 | * - FALSE: No response required
|
87 | */
|
88 | uint8_t TWIS_ResonseRequired (uint8_t *TWI_ResonseType)
|
89 | {
|
90 | *TWI_ResonseType = TWSR;
|
91 | return TWCR & (1<<TWINT);
|
92 | }
|