Volatile Quantities #606
-
I really like the library and now I'm going to the hardware and need to declare some variables volatile, because they are set from interrupts. It happens to be, that some of those should be quantities. But it seems that volatile is not really supported. For now I go with: template<mp_units::Quantity Quantity>
constexpr Quantity fromVolatile(const volatile Quantity& quantity) noexcept {
return std::bit_cast<Quantity>(quantity);
} What's your take on that? Also using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
This is an excellent question. It took me so long because I was unsure what to answer at first. I asked a few experts in the domain about this. The answer I got was similar to my initial feeling. The standard library has tried to get away from supporting For example, let's consider analog-to-digital converters (ADCs). They often do some measurements and then expose that value in a special purpose register. Those values will be some uint in some custom ADC units. Maybe the ADC measures in the range [-10, 10] volts, but that is expressed in the range [0, 65535] in the register. We read a inline constexpr struct hw_origin final : relative_point_origin<absolute<si::volt>(-10)> {} hw_origin;
inline constexpr struct hw_unit final : named_unit<"hw", mag_ratio<20, std::numeric_limits<std::uint16_t>::max()> * si::volt, hw_origin> {} hw_unit;
extern volatile std::uint16_t hw_value;
QuantityPointOf<isq::voltage> auto read_hw()
{
std::uint16_t local_value = hw_value;
return absolute<hw_unit>(local_value);
} quantity_point qp = read_hw();
std::println("{} ({})", qp.quantity_from_zero(), qp.in<double>(V).quantity_from_zero()); https://godbolt.org/z/Y3b334acE Please let me know your thoughts. |
Beta Was this translation helpful? Give feedback.
This is an excellent question. It took me so long because I was unsure what to answer at first. I asked a few experts in the domain about this. The answer I got was similar to my initial feeling.
The standard library has tried to get away from supporting
volatile
user types.atomic_signal_fence
is supposed to be the mechanism used to synchronize between interrupts / signals and other code, and notvolatile
. When communicating with special function registers, those should bevolatile
primitive types, and then quickly turned into quantities afterwards. Such solution is much easier and more robust.For example, let's consider analog-to-digital converters (ADCs). They often do some measuremen…