USI_TWI_Master.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*****************************************************************************
  2. *
  3. *
  4. * File USI_TWI_Master.c compiled with gcc
  5. * Date Friday, 10/31/08 Boo!
  6. * Updated by jkl
  7. *
  8. * AppNote : AVR310 - Using the USI module as a TWI Master
  9. *
  10. * Extensively modified to provide complete I2C driver.
  11. *
  12. *Notes:
  13. * - T4_TWI and T2_TWI delays are modified to work with 1MHz default clock
  14. * and now use hard code values. They would need to change
  15. * for other clock rates. Refer to the Apps Note.
  16. *
  17. * 12/17/08 Added USI_TWI_Start_Memory_Read Routine -jkl
  18. * Note msg buffer will have slave adrs ( with write bit set) and memory adrs;
  19. * length should be these two bytes plus the number of bytes to read.
  20. ****************************************************************************/
  21. #include <avr/interrupt.h>
  22. #include <util/delay.h>
  23. #include <avr/io.h>
  24. #include "USI_TWI_Master.h"
  25. unsigned char USI_TWI_Start_Transceiver_With_Data( unsigned char * , unsigned char );
  26. unsigned char USI_TWI_Master_Transfer( unsigned char );
  27. unsigned char USI_TWI_Master_Start( void );
  28. union USI_TWI_state
  29. {
  30. unsigned char errorState; // Can reuse the TWI_state for error states since it will not be needed if there is an error.
  31. struct
  32. {
  33. unsigned char addressMode : 1;
  34. unsigned char masterWriteDataMode : 1;
  35. unsigned char memReadMode : 1;
  36. unsigned char unused : 5;
  37. };
  38. } USI_TWI_state;
  39. /*---------------------------------------------------------------
  40. USI TWI single master initialization function
  41. ---------------------------------------------------------------*/
  42. void USI_TWI_Master_Initialise( void )
  43. {
  44. PORT_USI |= (1<<PIN_USI_SDA); // Enable pullup on SDA, to set high as released state.
  45. PORT_USI |= (1<<PIN_USI_SCL); // Enable pullup on SCL, to set high as released state.
  46. DDR_USI |= (1<<PIN_USI_SCL); // Enable SCL as output.
  47. DDR_USI |= (1<<PIN_USI_SDA); // Enable SDA as output.
  48. USIDR = 0xFF; // Preload dataregister with "released level" data.
  49. USICR = (0<<USISIE)|(0<<USIOIE)| // Disable Interrupts.
  50. (1<<USIWM1)|(0<<USIWM0)| // Set USI in Two-wire mode.
  51. (1<<USICS1)|(0<<USICS0)|(1<<USICLK)| // Software stobe as counter clock source
  52. (0<<USITC);
  53. USISR = (1<<USISIF)|(1<<USIOIF)|(1<<USIPF)|(1<<USIDC)| // Clear flags,
  54. (0x0<<USICNT0); // and reset counter.
  55. }
  56. /*---------------------------------------------------------------
  57. Use this function to get hold of the error message from the last transmission
  58. ---------------------------------------------------------------*/
  59. unsigned char USI_TWI_Get_State_Info( void )
  60. {
  61. return ( USI_TWI_state.errorState ); // Return error state.
  62. }
  63. /*---------------------------------------------------------------
  64. USI Random (memory) Read function. This function sets up for call
  65. to USI_TWI_Start_Transceiver_With_Data which does the work.
  66. Doesn't matter if read/write bit is set or cleared, it'll be set
  67. correctly in this function.
  68. The msgSize is passed to USI_TWI_Start_Transceiver_With_Data.
  69. Success or error code is returned. Error codes are defined in
  70. USI_TWI_Master.h
  71. ---------------------------------------------------------------*/
  72. unsigned char USI_TWI_Start_Random_Read( unsigned char *msg, unsigned char msgSize)
  73. {
  74. *(msg) &= ~(TRUE<<TWI_READ_BIT); // clear the read bit if it's set
  75. USI_TWI_state.errorState = 0;
  76. USI_TWI_state.memReadMode = TRUE;
  77. return (USI_TWI_Start_Transceiver_With_Data( msg, msgSize));
  78. }
  79. /*---------------------------------------------------------------
  80. USI Normal Read / Write Function
  81. Transmit and receive function. LSB of first byte in buffer
  82. indicates if a read or write cycles is performed. If set a read
  83. operation is performed.
  84. Function generates (Repeated) Start Condition, sends address and
  85. R/W, Reads/Writes Data, and verifies/sends ACK.
  86. Success or error code is returned. Error codes are defined in
  87. USI_TWI_Master.h
  88. ---------------------------------------------------------------*/
  89. unsigned char USI_TWI_Start_Read_Write( unsigned char *msg, unsigned char msgSize)
  90. {
  91. USI_TWI_state.errorState = 0; // Clears all mode bits also
  92. return (USI_TWI_Start_Transceiver_With_Data( msg, msgSize));
  93. }
  94. /*---------------------------------------------------------------
  95. USI Transmit and receive function. LSB of first byte in buffer
  96. indicates if a read or write cycles is performed. If set a read
  97. operation is performed.
  98. Function generates (Repeated) Start Condition, sends address and
  99. R/W, Reads/Writes Data, and verifies/sends ACK.
  100. This function also handles Random Read function if the memReadMode
  101. bit is set. In that case, the function will:
  102. The address in memory will be the second
  103. byte and is written *without* sending a STOP.
  104. Then the Read bit is set (lsb of first byte), the byte count is
  105. adjusted (if needed), and the function function starts over by sending
  106. the slave address again and reading the data.
  107. Success or error code is returned. Error codes are defined in
  108. USI_TWI_Master.h
  109. ---------------------------------------------------------------*/
  110. unsigned char USI_TWI_Start_Transceiver_With_Data( unsigned char *msg, unsigned char msgSize)
  111. {
  112. unsigned char const tempUSISR_8bit = (1<<USISIF)|(1<<USIOIF)|(1<<USIPF)|(1<<USIDC)| // Prepare register value to: Clear flags, and
  113. (0x0<<USICNT0); // set USI to shift 8 bits i.e. count 16 clock edges.
  114. unsigned char const tempUSISR_1bit = (1<<USISIF)|(1<<USIOIF)|(1<<USIPF)|(1<<USIDC)| // Prepare register value to: Clear flags, and
  115. (0xE<<USICNT0); // set USI to shift 1 bit i.e. count 2 clock edges.
  116. unsigned char *savedMsg;
  117. unsigned char savedMsgSize;
  118. //This clear must be done before calling this function so that memReadMode can be specified.
  119. // USI_TWI_state.errorState = 0; // Clears all mode bits also
  120. USI_TWI_state.addressMode = TRUE; // Always true for first byte
  121. #ifdef PARAM_VERIFICATION
  122. if(msg > (unsigned char*)RAMEND) // Test if address is outside SRAM space
  123. {
  124. USI_TWI_state.errorState = USI_TWI_DATA_OUT_OF_BOUND;
  125. return (FALSE);
  126. }
  127. if(msgSize <= 1) // Test if the transmission buffer is empty
  128. {
  129. USI_TWI_state.errorState = USI_TWI_NO_DATA;
  130. return (FALSE);
  131. }
  132. #endif
  133. #ifdef NOISE_TESTING // Test if any unexpected conditions have arrived prior to this execution.
  134. if( USISR & (1<<USISIF) )
  135. {
  136. USI_TWI_state.errorState = USI_TWI_UE_START_CON;
  137. return (FALSE);
  138. }
  139. if( USISR & (1<<USIPF) )
  140. {
  141. USI_TWI_state.errorState = USI_TWI_UE_STOP_CON;
  142. return (FALSE);
  143. }
  144. if( USISR & (1<<USIDC) )
  145. {
  146. USI_TWI_state.errorState = USI_TWI_UE_DATA_COL;
  147. return (FALSE);
  148. }
  149. #endif
  150. if ( !(*msg & (1<<TWI_READ_BIT)) ) // The LSB in the address byte determines if is a masterRead or masterWrite operation.
  151. {
  152. USI_TWI_state.masterWriteDataMode = TRUE;
  153. }
  154. // if (USI_TWI_state.memReadMode)
  155. // {
  156. savedMsg = msg;
  157. savedMsgSize = msgSize;
  158. // }
  159. if ( !USI_TWI_Master_Start( ))
  160. {
  161. return (FALSE); // Send a START condition on the TWI bus.
  162. }
  163. /*Write address and Read/Write data */
  164. do
  165. {
  166. /* If masterWrite cycle (or inital address tranmission)*/
  167. if (USI_TWI_state.addressMode || USI_TWI_state.masterWriteDataMode)
  168. {
  169. /* Write a byte */
  170. PORT_USI &= ~(1<<PIN_USI_SCL); // Pull SCL LOW.
  171. USIDR = *(msg++); // Setup data.
  172. USI_TWI_Master_Transfer( tempUSISR_8bit ); // Send 8 bits on bus.
  173. /* Clock and verify (N)ACK from slave */
  174. DDR_USI &= ~(1<<PIN_USI_SDA); // Enable SDA as input.
  175. if( USI_TWI_Master_Transfer( tempUSISR_1bit ) & (1<<TWI_NACK_BIT) )
  176. {
  177. if ( USI_TWI_state.addressMode )
  178. USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
  179. else
  180. USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
  181. return (FALSE);
  182. }
  183. if ((!USI_TWI_state.addressMode) && USI_TWI_state.memReadMode)// means memory start address has been written
  184. {
  185. msg = savedMsg; // start at slave address again
  186. *(msg) |= (TRUE<<TWI_READ_BIT); // set the Read Bit on Slave address
  187. USI_TWI_state.errorState = 0;
  188. USI_TWI_state.addressMode = TRUE; // Now set up for the Read cycle
  189. msgSize = savedMsgSize; // Set byte count correctly
  190. // NOte that the length should be Slave adrs byte + # bytes to read + 1 (gets decremented below)
  191. if ( !USI_TWI_Master_Start( ))
  192. {
  193. USI_TWI_state.errorState = USI_TWI_BAD_MEM_READ;
  194. return (FALSE); // Send a START condition on the TWI bus.
  195. }
  196. }
  197. else
  198. {
  199. USI_TWI_state.addressMode = FALSE; // Only perform address transmission once.
  200. }
  201. }
  202. /* Else masterRead cycle*/
  203. else
  204. {
  205. /* Read a data byte */
  206. DDR_USI &= ~(1<<PIN_USI_SDA); // Enable SDA as input.
  207. *(msg++) = USI_TWI_Master_Transfer( tempUSISR_8bit );
  208. /* Prepare to generate ACK (or NACK in case of End Of Transmission) */
  209. if( msgSize == 1) // If transmission of last byte was performed.
  210. {
  211. USIDR = 0xFF; // Load NACK to confirm End Of Transmission.
  212. }
  213. else
  214. {
  215. USIDR = 0x00; // Load ACK. Set data register bit 7 (output for SDA) low.
  216. }
  217. USI_TWI_Master_Transfer( tempUSISR_1bit ); // Generate ACK/NACK.
  218. }
  219. }while( --msgSize) ; // Until all data sent/received.
  220. // usually a stop condition is sent here, but TinyWireM needs to choose whether or not to send it
  221. /* Transmission successfully completed*/
  222. return (TRUE);
  223. }
  224. /*---------------------------------------------------------------
  225. Core function for shifting data in and out from the USI.
  226. Data to be sent has to be placed into the USIDR prior to calling
  227. this function. Data read, will be return'ed from the function.
  228. ---------------------------------------------------------------*/
  229. unsigned char USI_TWI_Master_Transfer( unsigned char temp )
  230. {
  231. USISR = temp; // Set USISR according to temp.
  232. // Prepare clocking.
  233. temp = (0<<USISIE)|(0<<USIOIE)| // Interrupts disabled
  234. (1<<USIWM1)|(0<<USIWM0)| // Set USI in Two-wire mode.
  235. (1<<USICS1)|(0<<USICS0)|(1<<USICLK)| // Software clock strobe as source.
  236. (1<<USITC); // Toggle Clock Port.
  237. do
  238. {
  239. _delay_us(T2_TWI);
  240. USICR = temp; // Generate positve SCL edge.
  241. while( !(PIN_USI & (1<<PIN_USI_SCL)) );// Wait for SCL to go high.
  242. _delay_us(T4_TWI);
  243. USICR = temp; // Generate negative SCL edge.
  244. }while( !(USISR & (1<<USIOIF)) ); // Check for transfer complete.
  245. _delay_us(T2_TWI);
  246. temp = USIDR; // Read out data.
  247. USIDR = 0xFF; // Release SDA.
  248. DDR_USI |= (1<<PIN_USI_SDA); // Enable SDA as output.
  249. return temp; // Return the data from the USIDR
  250. }
  251. /*---------------------------------------------------------------
  252. Function for generating a TWI Start Condition.
  253. ---------------------------------------------------------------*/
  254. unsigned char USI_TWI_Master_Start( void )
  255. {
  256. /* Release SCL to ensure that (repeated) Start can be performed */
  257. PORT_USI |= (1<<PIN_USI_SCL); // Release SCL.
  258. while( !(PORT_USI & (1<<PIN_USI_SCL)) ); // Verify that SCL becomes high.
  259. _delay_us(T2_TWI);
  260. /* Generate Start Condition */
  261. PORT_USI &= ~(1<<PIN_USI_SDA); // Force SDA LOW.
  262. _delay_us(T4_TWI);
  263. PORT_USI &= ~(1<<PIN_USI_SCL); // Pull SCL LOW.
  264. PORT_USI |= (1<<PIN_USI_SDA); // Release SDA.
  265. #ifdef SIGNAL_VERIFY
  266. if( !(USISR & (1<<USISIF)) )
  267. {
  268. USI_TWI_state.errorState = USI_TWI_MISSING_START_CON;
  269. return (FALSE);
  270. }
  271. #endif
  272. return (TRUE);
  273. }
  274. /*---------------------------------------------------------------
  275. Function for generating a TWI Stop Condition. Used to release
  276. the TWI bus.
  277. ---------------------------------------------------------------*/
  278. unsigned char USI_TWI_Master_Stop( void )
  279. {
  280. PORT_USI &= ~(1<<PIN_USI_SDA); // Pull SDA low.
  281. PORT_USI |= (1<<PIN_USI_SCL); // Release SCL.
  282. while( !(PIN_USI & (1<<PIN_USI_SCL)) ); // Wait for SCL to go high.
  283. _delay_us(T4_TWI);
  284. PORT_USI |= (1<<PIN_USI_SDA); // Release SDA.
  285. _delay_us(T2_TWI);
  286. #ifdef SIGNAL_VERIFY
  287. if( !(USISR & (1<<USIPF)) )
  288. {
  289. USI_TWI_state.errorState = USI_TWI_MISSING_STOP_CON;
  290. return (FALSE);
  291. }
  292. #endif
  293. return (TRUE);
  294. }