AnalogIn_ADS1115.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "AnalogIn_ADS1115.h"
  2. AnalogSource_ADS1115::AnalogSource_ADS1115(int16_t pin):
  3. _pin(pin),
  4. _value(0.0f)
  5. {
  6. }
  7. void AnalogSource_ADS1115::set_pin(uint8_t pin)
  8. {
  9. if (_pin == pin) {
  10. return;
  11. }
  12. _pin = pin;
  13. }
  14. float AnalogSource_ADS1115::read_average()
  15. {
  16. return read_latest();
  17. }
  18. float AnalogSource_ADS1115::read_latest()
  19. {
  20. return _value;
  21. }
  22. float AnalogSource_ADS1115::voltage_average()
  23. {
  24. return _value;
  25. }
  26. float AnalogSource_ADS1115::voltage_latest()
  27. {
  28. return _value;
  29. }
  30. float AnalogSource_ADS1115::voltage_average_ratiometric()
  31. {
  32. return _value;
  33. }
  34. extern const AP_HAL::HAL &hal;
  35. AnalogIn_ADS1115::AnalogIn_ADS1115()
  36. {
  37. _adc = new AP_ADC_ADS1115();
  38. _channels_number = _adc->get_channels_number();
  39. }
  40. AP_HAL::AnalogSource* AnalogIn_ADS1115::channel(int16_t pin)
  41. {
  42. for (uint8_t j = 0; j < _channels_number; j++) {
  43. if (_channels[j] == nullptr) {
  44. _channels[j] = new AnalogSource_ADS1115(pin);
  45. return _channels[j];
  46. }
  47. }
  48. hal.console->printf("Out of analog channels\n");
  49. return nullptr;
  50. }
  51. void AnalogIn_ADS1115::init()
  52. {
  53. _adc->init();
  54. hal.scheduler->register_timer_process(FUNCTOR_BIND_MEMBER(&AnalogIn_ADS1115::_update, void));
  55. }
  56. void AnalogIn_ADS1115::_update()
  57. {
  58. if (AP_HAL::micros() - _last_update_timestamp < 100000) {
  59. return;
  60. }
  61. adc_report_s reports[ADS1115_ADC_MAX_CHANNELS];
  62. size_t rc = _adc->read(reports, 6);
  63. for (size_t i = 0; i < rc; i++) {
  64. for (uint8_t j=0; j < rc; j++) {
  65. AnalogSource_ADS1115 *source = _channels[j];
  66. if (source != nullptr && reports[i].id == source->_pin) {
  67. source->_value = reports[i].data / 1000;
  68. }
  69. }
  70. }
  71. _last_update_timestamp = AP_HAL::micros();
  72. }