adc.c 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "src/battery_data/battery.h"
  2. #include "src/peripherals/adc/adc.h"
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include "src/peripherals/adc/adc_interface.h"
  6. #include "src/interfaces/i2c_controller.h"
  7. #include "src/config.h"
  8. //static ADC_Params adc_params;
  9. static ADC_MeasurementState adc_state = ADC_STATE_CONFIGURE;
  10. void updateADCReading(uint8_t slot, uint8_t channel) {
  11. //printf("Slot: %d, Channel: %d\n", slot, channel);
  12. ADC_Params adc_params= {0};
  13. while (adc_state != ADC_STATE_DONE) {
  14. switch (adc_state) {
  15. case ADC_STATE_CONFIGURE:
  16. adc_params.channel = channel;
  17. adc_params.resolution = 12;
  18. adc_params.continuous = ADC_MEASUREMENT_IS_CONTINUOUS;
  19. adc_params.gain = 1;
  20. //printf("Config: Memory address of batteries: %p\n", &batteries[0]);
  21. adc_hal.configure(slot, &adc_params);
  22. if (adc_params.continuous == 1) {
  23. // in one shot mode we wait first to get the result
  24. adc_state = ADC_STATE_WAIT;
  25. } else {
  26. // in continuous mode we can directly read
  27. adc_state = ADC_STATE_READ;
  28. delay_cycles(ADC_CONTINUOUS_DELAY_CYCLES);
  29. }
  30. break;
  31. case ADC_STATE_WAIT:
  32. if(adc_hal.is_ready(slot, &adc_params)){
  33. adc_state = ADC_STATE_READ;
  34. }
  35. break;
  36. case ADC_STATE_READ:
  37. if (channel == 0) {
  38. int16_t raw_adc_voltage = adc_hal.read_raw(slot, &adc_params);
  39. battery_slots[slot].measurement.voltage =
  40. adc_hal.convert_voltage(raw_adc_voltage, &adc_params);
  41. adc_state = ADC_STATE_DONE;
  42. #ifdef DEBUG_ADC
  43. printf("[ADC] Battery Voltage in slot %d is %d mV.\n", slot, battery_slots[slot].measurement.voltage);
  44. #endif
  45. } else if (channel == 1) {
  46. int16_t raw_adc_current = adc_hal.read_raw(slot, &adc_params);
  47. battery_slots[slot].measurement.current =
  48. adc_hal.convert_current(raw_adc_current, &adc_params);
  49. adc_state = ADC_STATE_DONE;
  50. #ifdef DEBUG_ADC
  51. printf("[ADC] Battery Current in slot %d is %d mA.\n", slot, battery_slots[slot].measurement.current);
  52. #endif
  53. } else if (channel == 2) {
  54. // @fixme: this is the third adc channel, needed for current meausrement on disharge mode
  55. int16_t raw_adc_voltage = adc_hal.read_raw(slot, &adc_params);
  56. battery_slots[slot].measurement.voltage =
  57. adc_hal.convert_voltage(raw_adc_voltage, &adc_params);
  58. adc_state = ADC_STATE_DONE;
  59. #ifdef DEBUG_ADC
  60. printf("[ADC] Ch3 Voltage in slot %d is %d mV.\n", slot, battery_slots[slot].measurement.voltage);
  61. #endif
  62. }
  63. break;
  64. default:
  65. channel = 0;
  66. adc_state = ADC_STATE_CONFIGURE;
  67. break;
  68. }
  69. }
  70. adc_state = ADC_STATE_CONFIGURE;
  71. }