Sound Byte Libs 0.5.1-340-gab5b79a
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 section 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 { return static_cast<float>((1u << bits) - 1u); }
32
33 constexpr float counts_per_volt() const { return counts_max() / (hi_v - lo_v); }
34
35 /** Code for a voltage at the jack, clamped to the converter's rails. */
36 constexpr uint16_t encode(float volts) const {
37 float t = (volts - lo_v) / (hi_v - lo_v);
38 if (t < 0.0f) {
39 t = 0.0f;
40 }
41 if (t > 1.0f) {
42 t = 1.0f;
43 }
44 if (inverted) {
45 t = 1.0f - t;
46 }
47 // t is clamped to [0, 1], so adding 0.5 rounds to nearest.
48 return static_cast<uint16_t>(t * counts_max() + 0.5f); // NOLINT(bugprone-incorrect-roundings)
49 }
50
51 /** Voltage at the jack for a code. */
52 constexpr float decode(uint16_t counts) const {
53 float t = static_cast<float>(counts) / counts_max();
54 if (inverted) {
55 t = 1.0f - t;
56 }
57 return lo_v + t * (hi_v - lo_v);
58 }
59
60 /** Code that reads as 0 V - the bipolar midpoint. Clamps if 0 V is out of range. */
61 constexpr uint16_t midpoint() const { return encode(0.0f); }
62};
63
64} // namespace adc
65} // namespace hal
66} // namespace sbl
67
68#endif // SBL_HW_HAL_ADC_ELECTRICAL_HPP_
Root namespace for all Sound Byte Libs code.
constexpr uint16_t midpoint() const
constexpr uint16_t encode(float volts) const
constexpr float decode(uint16_t counts) const