adc.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. adc_hal.configure(slot, &adc_params);
  34. if (adc_params.continuous != 1) {
  35. // in one shot mode we wait first to get the result
  36. adc_state = ADC_STATE_WAIT;
  37. } else {
  38. // in continuous mode we can directly read
  39. adc_state = ADC_STATE_READ;
  40. delay_cycles(ADC_CONTINUOUS_DELAY_CYCLES);
  41. }
  42. break;
  43. case ADC_STATE_WAIT:
  44. if(adc_hal.is_ready(slot, &adc_params)){
  45. adc_state = ADC_STATE_READ;
  46. }
  47. break;
  48. case ADC_STATE_READ:
  49. adc_voltage = adc_hal.read_voltage(slot, &adc_params);
  50. #ifdef DEBUG_ADC
  51. printf("[ADC] ADC reading completed. Slot %d Channel %d is %d \n", slot, channel, adc_voltage);
  52. #endif
  53. adc_state = ADC_STATE_DONE;
  54. break;
  55. default:
  56. channel = 0;
  57. adc_state = ADC_STATE_CONFIGURE;
  58. break;
  59. }
  60. }
  61. adc_state = ADC_STATE_CONFIGURE;
  62. return adc_voltage;
  63. }