Sound Byte Libs 0.5.1-121-g3358a44
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
electrical.hpp
Go to the documentation of this file.
1/**
2 * @file electrical.hpp
3 * @brief Electrical description of an analog port โ€” the jack-to-converter circuit
4 * @ingroup hal
5 *
6 * Describes what sits between a jack and the ADC: the voltage span the full
7 * code range represents, the converter resolution, and whether the front end
8 * inverts. Instances are generated by sloth from the hardware manifests into
9 * `sbl::hw::electrical` (config/electrical.hpp); components derive their
10 * conditioning from them. Hand-written instances are for tests and one-offs.
11 *
12 * Codes are right-aligned unsigned counts, 0 .. (2^bits - 1), as the ADC
13 * drivers deliver them (STM32H7: RM0433 Rev 8 ยง25.6.15, right-aligned by default).
14 */
15
16#ifndef SBL_HW_HAL_ADC_ELECTRICAL_HPP_
17#define SBL_HW_HAL_ADC_ELECTRICAL_HPP_
18
19#include <cstdint>
20
21namespace sbl {
22namespace hal {
23namespace adc {
24
25struct Electrical {
26 float lo_v; ///< Voltage at code 0 (or at full scale, if inverted)
27 float hi_v; ///< Voltage at full scale (or at code 0, if inverted)
28 uint8_t bits; ///< Converter resolution
29 bool inverted; ///< +V at the jack reads as a lower code
30
31 constexpr float counts_max() const {
32 return static_cast<float>((1u << bits) - 1u);
33 }
34
35 constexpr float counts_per_volt() const {
36 return counts_max() / (hi_v - lo_v);
37 }
38
39 /// Code for a voltage at the jack, clamped to the converter's rails.
40 constexpr uint16_t encode(float volts) const {
41 float t = (volts - lo_v) / (hi_v - lo_v);
42 if (t < 0.0f) t = 0.0f;
43 if (t > 1.0f) t = 1.0f;
44 if (inverted) t = 1.0f - t;
45 return static_cast<uint16_t>(t * counts_max() + 0.5f);
46 }
47
48 /// Voltage at the jack for a code.
49 constexpr float decode(uint16_t counts) const {
50 float t = static_cast<float>(counts) / counts_max();
51 if (inverted) t = 1.0f - t;
52 return lo_v + t * (hi_v - lo_v);
53 }
54
55 /// Code that reads as 0 V โ€” the bipolar midpoint. Clamps if 0 V is out of range.
56 constexpr uint16_t midpoint() const { return encode(0.0f); }
57};
58
59} // namespace adc
60} // namespace hal
61} // namespace sbl
62
63#endif // SBL_HW_HAL_ADC_ELECTRICAL_HPP_
Root namespace for all Sound Byte Libs code.
Definition assert.hpp:51
constexpr float counts_max() const
float hi_v
Voltage at full scale (or at code 0, if inverted)
uint8_t bits
Converter resolution.
constexpr uint16_t midpoint() const
Code that reads as 0 V โ€” the bipolar midpoint. Clamps if 0 V is out of range.
constexpr uint16_t encode(float volts) const
Code for a voltage at the jack, clamped to the converter's rails.
bool inverted
+V at the jack reads as a lower code
float lo_v
Voltage at code 0 (or at full scale, if inverted)
constexpr float decode(uint16_t counts) const
Voltage at the jack for a code.
constexpr float counts_per_volt() const