adc.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. uint16_t read_adc_channel(uint8_t slot, uint8_t channel) {
  11. //printf("Slot: %d, Channel: %d\n", slot, channel);
  12. ADC_Params adc_params= {0};
  13. uint16_t adc_voltage = 0;
  14. while (adc_state != ADC_STATE_DONE) {
  15. switch (adc_state) {
  16. case ADC_STATE_CONFIGURE:
  17. adc_params.channel = channel;
  18. adc_params.continuous = ADC_MEASUREMENT_IS_CONTINUOUS;
  19. if (channel == 0 || channel == 3) {
  20. // voltage measurement
  21. // -> we can measure directly
  22. adc_params.gain = 1;
  23. adc_params.resolution = 12;
  24. adc_params.factor = 1;
  25. } else {
  26. // current measurement
  27. // -> maximum gain, max resolution
  28. adc_params.gain = 8;
  29. adc_params.resolution = 16;
  30. adc_params.factor = 1000; // get microvolts
  31. }
  32. //printf("Config: Memory address of batteries: %p\n", &batteries[0]);
  33. if (!adc_hal.configure(slot, &adc_params)) {
  34. return 0xffff;
  35. }
  36. if (adc_params.continuous != 1) {
  37. // in one shot mode we wait first to get the result
  38. adc_state = ADC_STATE_WAIT;
  39. } else {
  40. // in continuous mode we can directly read
  41. adc_state = ADC_STATE_READ;
  42. if (adc_params.resolution == 16) {
  43. delay_cycles(ADC_CONTINUOUS_DELAY_CYCLES_SHUNT);
  44. } else {
  45. delay_cycles(ADC_CONTINUOUS_DELAY_CYCLES_VOLTAGES);
  46. }
  47. }
  48. break;
  49. case ADC_STATE_WAIT:
  50. if(adc_hal.is_ready(slot, &adc_params)){
  51. adc_state = ADC_STATE_READ;
  52. }
  53. break;
  54. case ADC_STATE_READ:
  55. adc_voltage = adc_hal.read_voltage(slot, &adc_params);
  56. #ifdef DEBUG_ADC
  57. printf("[ADC] ADC reading completed. Slot %d Channel %d is %d \n", slot, channel, adc_voltage);
  58. #endif
  59. adc_state = ADC_STATE_DONE;
  60. break;
  61. default:
  62. channel = 0;
  63. adc_state = ADC_STATE_CONFIGURE;
  64. break;
  65. }
  66. }
  67. adc_state = ADC_STATE_CONFIGURE;
  68. return adc_voltage;
  69. }