libyggdrasil  v1.0.0
adc.hpp
Go to the documentation of this file.
1  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  * _____.___. .___ .__.__ *
3  * \__ | | ____ ____ __| _/___________ _____|__| | *
4  * / | |/ ___\ / ___\ / __ |\_ __ \__ \ / ___/ | | *
5  * \____ / /_/ > /_/ > /_/ | | | \// __ \_\___ \| | |__ *
6  * / ______\___ /\___ /\____ | |__| (____ /____ >__|____/ *
7  * \/ /_____//_____/ \/ \/ \/ *
8  * - Asgard - *
9  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
10  * This software can be used by students and other personal of the *
11  * Bern University of Applied Sciences under the terms of the MIT *
12  * license. *
13  * For other persons this software is under the terms of the GNU *
14  * General Public License version 2. *
15  * *
16  * Copyright © 2021, Bern University of Applied Sciences. *
17  * All rights reserved. *
18  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
26 #pragma once
27 
29 
30 #include <cmath>
31 
32 namespace bsp::mid::drv {
33 
43  template<auto Context, u8 Index, u32 Offset, u32 MaxValue>
44  struct ADCChannel {
45  ADCChannel(const ADCChannel&) = delete;
46  auto operator=(const ADCChannel&) = delete;
47 
48  constexpr static auto ReferenceVoltage = 3.3;
49 
55  static bool init() {
56  ADCChannel::s_device = open(("/sys/bus/iio/devices/iio:device" + std::to_string(Context) + "/in_voltage" + std::to_string(Index) + "_raw").c_str(), O_RDWR);
57  return ADCChannel::s_device != -1;
58  }
59 
65  static bool deinit() {
66  close(ADCChannel::s_device);
67  return true;
68  }
69 
76  operator float() const noexcept {
77  std::string data(0xFF, 0x00);
78 
79  if (read(ADCChannel::s_device, data.data(), data.size()) <= 0)
80  return 0.0F;
81  lseek(ADCChannel::s_device, 0, 0);
82 
83  return std::max<float>(std::stol(data) - Offset, 0.0F) / MaxValue; // Get the value and transform it to 0.0 to 1.0
84  }
85 
86  private:
87  ADCChannel() = default;
88 
92  template<auto, template<auto, u8, u32, u32> typename>
93  friend struct bsp::drv::ADConverter;
94 
95  static inline int s_device = -1;
96  };
97 
98 }
bsp::mid::drv::ADCChannel
ADC Channel implementation for Asgard.
Definition: adc.hpp:44
bsp::mid::drv::ADCChannel::ReferenceVoltage
constexpr static auto ReferenceVoltage
Definition: adc.hpp:48
bsp::mid::drv::ADCChannel::deinit
static bool deinit()
Deinit function.
Definition: adc.hpp:65
bsp::drv::ADConverter
Base class for ADC abstraction.
Definition: adc.hpp:39
bsp::mid::drv::ADCChannel::ADCChannel
ADCChannel(const ADCChannel &)=delete
bsp::mid::drv::ADCChannel::operator=
auto operator=(const ADCChannel &)=delete
bsp::mid::drv::ADCChannel::init
static bool init()
Init function.
Definition: adc.hpp:55
bsp::mid::drv
Definition: adc.hpp:32
adc.hpp
Frontend for the ADC abstraction.