adc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #include "battery.h"
  2. #include "src/interfaces/i2c_controller_interface.h"
  3. #include "ti/driverlib/dl_i2c.h"
  4. #include "ti/driverlib/m0p/dl_core.h"
  5. #include "ti_msp_dl_config.h"
  6. #include "adc.h"
  7. #include <stdint.h>
  8. #include <stdio.h>
  9. volatile bool gRxComplete;
  10. volatile bool gTxComplete;
  11. uint8_t gTxPacket[I2C_TX_MAX_PACKET_SIZE];
  12. uint8_t gRxPacket[I2C_RX_MAX_PACKET_SIZE];
  13. uint32_t gTxADClen, gTxADCcount;
  14. uint32_t gRxADClen, gRxADCcount;
  15. static ADC_PARAMS adc_params;
  16. static ADC_MeasurementState adc_state = ADC_STATE_CONFIGURE;
  17. /*
  18. * Creating Configuartion Register as mentioned in the datasheet: https://ww1.microchip.com/downloads/aemDocuments/documents/OTH/ProductDocuments/DataSheets/22226a.pdf
  19. * Under section 5.2 Configuration Register
  20. * The function is private to ADC and is can only be called in this file
  21. */
  22. static uint8_t ADC_ConstructConfigBytes(ADC_PARAMS params) {
  23. uint8_t config = 0;
  24. config |= ((params.channel) << 5); // Channel Selection (Bits 6-5)
  25. config |= (1 << 4); // One-Shot Mode
  26. switch (params.resolution) {
  27. case 12:
  28. config |= (0b00 << 2);
  29. break;
  30. case 14:
  31. config |= (0b01 << 2);
  32. break;
  33. case 16:
  34. config |= (0b10 << 2);
  35. break;
  36. default:
  37. printf("ERROR: Invalid Resolution!\n");
  38. return 0;
  39. }
  40. switch (params.gain) {
  41. case 1:
  42. config |= (0b00);
  43. break;
  44. case 2:
  45. config |= (0b01);
  46. break;
  47. case 4:
  48. config |= (0b10);
  49. break;
  50. default:
  51. printf("ERROR: Invalid Gain!\n");
  52. return 0;
  53. }
  54. return config;
  55. }
  56. /* Tansmit Data from MCU to ADC: Function to SET configuration to ADC over
  57. * I2C*/
  58. void ADC_SetConfigurationBytes(ADC_PARAMS params) {
  59. // **Construct Configuration Byte**
  60. uint8_t config_byte = ADC_ConstructConfigBytes(params);
  61. // Wait for I2C Bus to be Free**
  62. while (DL_I2C_getControllerStatus(I2C_controller_INST) &
  63. DL_I2C_CONTROLLER_STATUS_BUSY_BUS)
  64. ;
  65. // **Start I2C Write Transaction**
  66. // Prepare TX Buffer:
  67. gTxPacket[0] = config_byte;
  68. gTxADClen = 1;
  69. gTxADCcount = 0;
  70. gTxComplete = false;
  71. i2c_hal.write(ADC_TARGET_BASE_ADDRESS, gTxPacket, gTxADClen);
  72. //DL_I2C_flushControllerTXFIFO(I2C_controller_INST);
  73. //DL_I2C_fillControllerTXFIFO(I2C_controller_INST, (uint8_t *)&gTxPacket, 1);
  74. //DL_I2C_startControllerTransfer(I2C_controller_INST, ADC_TARGET_BASE_ADDRESS,
  75. // DL_I2C_CONTROLLER_DIRECTION_TX, gTxADClen);
  76. // DL_I2C_enableInterrupt(I2C_controller_INST,
  77. // DL_I2C_INTERRUPT_CONTROLLER_TXFIFO_TRIGGER);
  78. // while(!gTxComplete);
  79. // **Ensure STOP Condition is Sent**
  80. //while (DL_I2C_getControllerStatus(I2C_controller_INST) &
  81. // DL_I2C_CONTROLLER_STATUS_BUSY_BUS)
  82. // ;
  83. // printf("Configuration Sent Successfully for 0x%X!\n", config_byte);
  84. }
  85. /*
  86. READY BIT:
  87. This bit is the data ready flag. In read mode, this bit indicates if the
  88. output register has been updated with a latest conversion result. In One-Shot
  89. Conversion mode, writing this bit to “1” initiates a new conversion.
  90. 1= Output Register has not been updated
  91. 0= Output Register has been updated
  92. */
  93. bool ADC_CheckReadyBit(uint8_t slot_id, ADC_PARAMS params) {
  94. // Buffer for ADC data (MSB, LSB, Config Byte)
  95. uint8_t adc_data[3];
  96. uint8_t adc_address = ADC_TARGET_BASE_ADDRESS + slot_id;
  97. //printf("Reading ADC Data from MCP3428 for channel: %u\n", params.channel);
  98. gRxADClen = 3;
  99. gRxADCcount = 0;
  100. gRxComplete = false;
  101. i2c_hal.read(adc_address, gRxADClen);
  102. //DL_I2C_startControllerTransfer(I2C_controller_INST, adc_address,
  103. // DL_I2C_CONTROLLER_DIRECTION_RX, gRxADClen);
  104. //DL_I2C_enableInterrupt(I2C_controller_INST,
  105. // DL_I2C_INTERRUPT_CONTROLLER_RXFIFO_TRIGGER);
  106. //while (DL_I2C_getControllerStatus(I2C_controller_INST) &
  107. // DL_I2C_CONTROLLER_STATUS_BUSY_BUS)
  108. // ;
  109. //while (!gRxComplete)
  110. // ;
  111. uint8_t config_adc_byte = gRxPacket[2];
  112. // Ready bit is bit 7
  113. bool ready = (config_adc_byte & 0x80) == 0;
  114. //printf("Slot: %d | Config Byte: 0x%02X | READY Bit: %d\n", slot_id,
  115. // config_adc_byte, ready);
  116. return ready;
  117. }
  118. /*
  119. Function to read ADC DATA: This function simply retrieves the ADC raw digital
  120. output as 16-bit signed integer.
  121. * The value returned is not yet converted to VOLTAGE.
  122. * adc_data[2]: Buffer with an array of size 2, to store two bytes of ADC data.
  123. * Since, the ADC output consists of two 8-bit bytes:
  124. * - adc_data[0] (MSB)
  125. * - adc_data[1] (LSB)
  126. * Next, we verify if the the I2C bus is busy using the function in the
  127. driverlib: DL_I2C_get ControllerStatus
  128. * - Prevents collisions by ensuring no two I2C device is using the same
  129. bus before initializing.
  130. * BEGIN I2C READ operation to request 2 bytes from the ADC->
  131. DL_I2C_startControllerTransfer()
  132. * Parameters:
  133. - I2C_controller_INST: Refererence to the I2C instance bring used.
  134. - DEF_TARGET_ADDR_ADC: Address of the ADC
  135. - DL_I2C_CONTROLLER_DIRECTION_RX: Indicates that we want to receive the data
  136. from ADC
  137. - 2: Specifies that we expect 2 bytes from the ADC
  138. * WAIT for the data to be received: (DL_I2C_getControllerStatus())
  139. - Waits until the ADC sends the data over I2C.
  140. - Ensures that the data transfer is complete before proceeding.
  141. * READ the two bytes of ADc Data:
  142. - adc_data[0] : MSB
  143. - adc_data[1] : LSB
  144. - adc_data[2] : config_bytes
  145. ADC sends its 16-bit value in two parts over 8-bit I2C data frames.
  146. * COMBINE the two bytes into 16-bit Integer:
  147. - Shifts the MSB(first byte) left by 8 bits to make space for LSB.
  148. - Performs a bitwise OR operation to combine MSB and LSB into a single
  149. 16-bit number.
  150. * PRINT HEXADEC and DECIMAL format for DEBUGGING.
  151. * Output code is in binary and is proportional to the Input Voltage and PGA
  152. settings.
  153. * From the datasheet:
  154. https://ww1.microchip.com/downloads/aemDocuments/documents/OTH/ProductDocuments/DataSheets/22226a.pdf
  155. - Equation 4.4 is being used to convert the output codes to input voltage
  156. * The ACK bits after conversion is issued by the Master, when the device
  157. receives a READ command, it outputs two data bytes followed by a configuration
  158. register in 16 bit conversion mode the MSB(=sign bit) of the first data type is
  159. D15.
  160. */
  161. int16_t ADC_ReadData(uint8_t slot_id, ADC_PARAMS params) {
  162. // Buffer for ADC data (MSB, LSB, Config Byte)
  163. uint8_t adc_data[3] = {0};
  164. int16_t raw_adc = 0;
  165. uint8_t bytes_to_read = 3;
  166. uint8_t adc_address = ADC_TARGET_BASE_ADDRESS + slot_id;
  167. // printf("Reading ADC Data from MCP3428 for channel: %u\n", params.channel);
  168. //if (DL_I2C_getControllerStatus(I2C_controller_INST) &
  169. // DL_I2C_CONTROLLER_STATUS_BUSY_BUS) {
  170. // printf("Error: I2C bus stuck! Resetting..\n");
  171. // DL_I2C_resetControllerTransfer(I2C_controller_INST);
  172. //}
  173. gRxADClen = bytes_to_read;
  174. gRxADCcount = 0;
  175. gRxComplete = false;
  176. i2c_hal.read(adc_address, gRxADClen);
  177. //DL_I2C_startControllerTransfer(I2C_controller_INST, adc_address,
  178. // DL_I2C_CONTROLLER_DIRECTION_RX, gRxADClen);
  179. //DL_I2C_enableInterrupt(I2C_controller_INST,
  180. // DL_I2C_INTERRUPT_CONTROLLER_RXFIFO_TRIGGER);
  181. //while (DL_I2C_getControllerStatus(I2C_controller_INST) &
  182. // DL_I2C_CONTROLLER_STATUS_BUSY_BUS)
  183. // ;
  184. //while (!gRxComplete)
  185. // ;
  186. uint8_t msb = gRxPacket[0];
  187. uint8_t lsb = gRxPacket[1];
  188. uint8_t config_adc_byte = gRxPacket[2];
  189. //printf("MSB: 0x%02X, LSB: 0x%02X\n", msb, lsb);
  190. uint8_t gain_setting = (config_adc_byte & 0x03);
  191. uint8_t gain_multiplier = (1 << gain_setting); // Gain values: 1, 2, 4, 8
  192. if (params.resolution == 16) {
  193. raw_adc = (msb << 8) | lsb;
  194. if (raw_adc > 32767)
  195. raw_adc -= 65536;
  196. } else if (params.resolution == 14) {
  197. raw_adc = ((msb & 0b00111111) << 8) | lsb;
  198. if (raw_adc > 8191)
  199. raw_adc -= 16384;
  200. } else if (params.resolution == 12) {
  201. raw_adc = ((msb & 0b00001111) << 8) | lsb;
  202. if (raw_adc > 2047)
  203. raw_adc -= 4096;
  204. }
  205. //printf("Raw ADC Value: 0x%0X (%d)\n", raw_adc, raw_adc);
  206. return raw_adc;
  207. }
  208. // **Interrupt handler for ADC Read Completion**
  209. void I2C_ADC_IRQHandler(void) {
  210. if (DL_I2C_getPendingInterrupt(I2C_controller_INST) ==
  211. DL_I2C_IIDX_CONTROLLER_RXFIFO_TRIGGER) {
  212. gRxComplete = true;
  213. }
  214. }
  215. /* Function to Convert ADC Reading to Voltage */
  216. uint16_t ADC_ConvertToVoltage(int16_t adc_value, ADC_PARAMS params) {
  217. uint16_t measured_voltage = 0;
  218. uint16_t LSB = 0;
  219. uint32_t max_adc_value = 1;
  220. switch (params.resolution) {
  221. case 12: // 12-bit
  222. max_adc_value = 4095;
  223. break;
  224. case 14: // 14-bit
  225. max_adc_value = 16383;
  226. break;
  227. case 16: // 16-bit
  228. max_adc_value = 65535;
  229. break;
  230. default:
  231. printf("Error: Unknown ADC Resolution!\n");
  232. return 0;
  233. }
  234. measured_voltage = (((uint32_t)adc_value) * 2.7);
  235. return (uint16_t)measured_voltage;
  236. }
  237. /* Function to Convert ADC Reading to Voltage */
  238. uint16_t ADC_ConvertToCurrent(int16_t adc_value, ADC_PARAMS params) {
  239. int16_t current_mA = 0;
  240. // uint8_t r_shunt= 0.1;
  241. // Convert ADC value to voltage across shunt resistor:
  242. uint16_t voltage_mV = ADC_ConvertToVoltage(adc_value, params);
  243. uint8_t gain_multiplier = (1 << (params.gain - 1));
  244. // Convert voltage drop across shunt resistor to current
  245. current_mA = (adc_value) * (10 * gain_multiplier);
  246. // printf("Converted Current: %d mA.\n", current_mA);
  247. return (int16_t)current_mA;
  248. }
  249. void Battery_UpdateADCReading(uint8_t slot, uint8_t channel) {
  250. while (adc_state != ADC_STATE_DONE) {
  251. switch (adc_state) {
  252. case ADC_STATE_CONFIGURE:
  253. adc_params.channel = channel;
  254. //printf("Channel: %d\n", adc_params.channel);
  255. adc_params.resolution = 12;
  256. adc_params.continuous = 0;
  257. adc_params.gain = 1;
  258. ADC_SetConfigurationBytes(adc_params);
  259. adc_state = ADC_STATE_WAIT;
  260. break;
  261. case ADC_STATE_WAIT:
  262. if (ADC_CheckReadyBit(slot, adc_params)) {
  263. adc_state = ADC_STATE_READ;
  264. }
  265. break;
  266. case ADC_STATE_READ:
  267. if (channel == 0) {
  268. int16_t raw_adc_voltage = ADC_ReadData(slot, adc_params);
  269. batteries[slot].voltage =
  270. ADC_ConvertToVoltage(raw_adc_voltage, adc_params); // Double check voltage dividers later on to get the right value (possibly instead of 2)
  271. printf("[ADC] Battery voltage for slot %d is %u mV.\n", slot,
  272. batteries[slot].voltage);
  273. adc_state = ADC_STATE_DONE;
  274. } else if (channel == 1) {
  275. int16_t raw_adc_current = ADC_ReadData(slot, adc_params);
  276. batteries[slot].current =
  277. ADC_ConvertToCurrent(raw_adc_current, adc_params);
  278. printf("[ADC] Battery current for slot %d is %u mA.\n", slot,
  279. batteries[slot].current);
  280. adc_state = ADC_STATE_DONE;
  281. }
  282. break;
  283. default:
  284. channel = 0;
  285. adc_state = ADC_STATE_CONFIGURE;
  286. break;
  287. }
  288. }
  289. adc_state = ADC_STATE_CONFIGURE;
  290. }
  291. void Battery_ReadState(uint8_t slot_id) {
  292. uint16_t voltage_mv = batteries[slot_id].voltage;
  293. uint16_t min_voltage = batteries[slot_id].min_voltage;
  294. uint16_t max_voltage = batteries[slot_id].max_voltage;
  295. /* Changing the battery states based on adc values*/
  296. if (voltage_mv < 500) {
  297. batteries[slot_id].state = STATE_EMPTY;
  298. } else if (voltage_mv >= 500 && voltage_mv < 3000) { //TODO: change the voltage_mv to min_voltage
  299. batteries[slot_id].state = STATE_BATTERY_DETECTED;
  300. } else if (voltage_mv >= 3000 && voltage_mv < 4200) {
  301. batteries[slot_id].state = STATE_MEASUREMENT_IN_PROGRESS;
  302. }
  303. // once MCU is done reading ADC:
  304. else if (adc_state== ADC_STATE_DONE && batteries[slot_id].state== STATE_MEASUREMENT_IN_PROGRESS) {
  305. batteries[slot_id].state = STATE_MEASUREMENT_DONE;
  306. } else {
  307. batteries[slot_id].state = STATE_OVERCHARGING;
  308. }
  309. }