Skip to content

Tracking issue for ADC trait #377

Open

Description

@eldruin

The ADC traits (adc::Channel and adc::OneShot) available on the 0.2.x versions have been removed ahead of the 1.0.0 release. See: #376
This issue servers as a tracking issue until we add them back/reject them.

The reasons were:

  • The traits are quite complicated to use in generic code.
  • It seems users would be better served by inherent methods.
  • Also, these traits are nb-only.

ADC traits as of the 0.2.7 release:

Relevant issues/PRs:

Please feel free to participate, highlight your current use cases, problems and provide solutions.

Activity

  1. ryankurte commented on Apr 28, 2022

    @ryankurte
    Contributor

    the updated spi traits have me wondering if a similar approach would suit for ADCs... something like a shared AdcDevice that is split into separate channels implementing AdcChannel which drivers then take in the same manner as digital pins or any other injected type.

    ADC peripherals would seem to have very similar constraints as sharing as a bus; one ADC peripheral with multiple channels that may be used in different places, and a need to be able to take ownership of the peripheral for more complex behaviors like interleaving or DMA.

    (i think this is also relevant to our previous timer / delay traits, though these do not always need to be exclusive you also often need to be able to duplicate delays or split timers into multiple drivers)

  2. Dirbaio commented on Apr 28, 2022

    @Dirbaio
    Member

    Maybe having a trait for an "ADC device" is not really needed? We could just have this

    trait AdcChannel
        fn read(&mut self) -> Result<u32, Error>;
    }
    

    If the hardware has a single multi-channel ADC it's up to the implementors to do the "sharing" for it. Via RefCell, Mutex, or whatever. Or it could be even a noop for MCU peripheral ADCs: hit the registers directly from read() and ensure the channels are !Send so that the user can't hit the ADC concurrently from multiple threads (irq priority levels).

    need to be able to take ownership of the peripheral for more complex behaviors like interleaving or DMA.

    I don't think making traits for these is feasible, they're incredibly hardware dependent...

  3. ryankurte commented on Apr 29, 2022

    @ryankurte
    Contributor

    Maybe having a trait for an "ADC device" is not really needed? We could just have this

    what i'm mostly wondering is whether this is a consistent problem with spi / i2c / adc / etc. that we can extract in a consistent way, but yeah seems to me like AdcChannel could be a good start.

    I don't think making traits for these is feasible, they're incredibly hardware dependent...

    agreed, but the in the spi model you can still take exclusive ownership of the bus and do whatever is needed via the closure based approach.

  4. eldruin commented on May 11, 2022

    @eldruin
    MemberAuthor

    A complication in the case of ADCs is that some channel combinations can be configured to work in comparison mode, where the measurements taken correspond to the difference between two (otherwise-independent) channels.
    See the ads1x1x driver for an example.

  5. crjeder commented on Jul 14, 2022

    @crjeder
    trait AdcChannel
        fn read(&mut self) -> Result<u32, Error>;
    }
    

    I'd strongly vote for a read() interface for ADC as this would abstract away how the ADC is connected. Could be a GPIO or via SPI.

  6. Ben-PH commented on May 28, 2024

    @Ben-PH

    I would like to propose making the result type generic. Perhaps the vast majority of the time it's a u32, but making it such that it can be any unsigned would make this trait more universally applicable.

  7. darconeous commented on Mar 28, 2025

    @darconeous

    I would like to propose making the result type generic. Perhaps the vast majority of the time it's a u32, but making it such that it can be any unsigned would make this trait more universally applicable.

    So something like this, perhaps?

    trait AdcChannel {
        /// The underlying word type for ADC conversions.
        ///
        /// Typically, this is `u32` or `u16`.
        type Word: Sized + Copy;
    }
    
    trait AdcChannelOneshot : AdcChannel + ErrorType {
        /// Returns a single raw ADC reading.
        ///
        /// Calling this method will initiate an ADC conversion,
        /// block until that conversion is complete, and then return
        /// the raw result (or an error).
        ///
        /// The units are dependent on the hardware configuration,
        /// and are outside of the scope of this trait.
        fn read_oneshot(&mut self) -> Result<<Self as AdcChannel>::Word, <Self as ErrorType>::Error>;
    }
    
    trait AdcChannelOneshotMv : AdcChannel + ErrorType {
        /// Returns a single ADC reading in millivolts.
        ///
        /// Calling this method will initiate an ADC conversion,
        /// block until that conversion is complete, and then return
        /// the result (or an error).
        fn read_oneshot_mv(&mut self) -> Result<<Self as AdcChannel>::Word, <Self as ErrorType>::Error>;
    }

    And maybe some async versions:

    trait AdcChannelOneshotAsync : AdcChannel + ErrorType {
        fn poll_read_oneshot(&mut self, cx: &mut Context<'_>)
            -> Poll<Result<<Self as AdcChannel>::Word, <Self as ErrorType>::Error>>;
    }
    
    // Include traits like `AdcChannelOneshotAsyncExt` (to provide an
    // `async_read_oneshot()` method and a `AdcChannelOneshotAsyncFuture`
    //  struct that would be returned by  `async_read_oneshot()`...

    Having the ability to at least have reads be abstracted away helps make my code portable, so something like this would be very useful.

  8. bnjmn21 commented on Nov 25, 2025

    @bnjmn21

    I think this trait not being implemented is holding back the ecosystem. Many drivers / apps require ADCs and are therefore stuck on pre-1.0. I have the following solution. It is based on @darconeous , changes I made are explained below.

    trait AdcChannelOneshot: ErrorType {
        const ONE_VOLT: u32;
        fn to_mv(raw_value: u32) -> u32 {
            // may be overridden by more optimal impl
            (raw_value * 1000) / Self::ONE_VOLT
        }
        fn read_raw(&mut self) -> Result<u32, <Self as ErrorType>::Error>;
        fn read_mv(&mut self) -> Result<u32, <Self as ErrorType>::Error> {
            // may be overridden by hardware function
            self.read_raw().map(|raw_value| Self::to_mv(raw_value))
        }
    }

    Async versions accordingly.

    Changes:

    • It is rare for an ADC to not support conversion to volts. Therefore we can consolidate everything to one trait.
    • Having the word size be generic like the prior example by darconeous increases complexity significantly in generic code. We would need to add some sort of ´trait Numeric: std::ops::Add + std::ops::Sub + ...´ to be able to even to basic arithmetic on it. Using a u32 makes everything so much easier and has minimal perf impact, especially for the one-shot API.
    • The more idiomatic / recommended / commonly used function not have a longer name than the less safe version. Thereforeread is renamed to read_raw. Having oneshot in every function name is redundant imo.
    • Multiplication / Division (used for conversion to millivolts) is expensive on some architectures, but the conversion isn't always necessary. Therefore we provide the read_raw fn. In this case ONE_VOLT and to_mv helps for doing manual computations, See this example:
      const THRESHOLD: u32 = 3 * Adc::ONE_VOLT;
      if adc.read_raw() > THRESHOLD {
        do_stuff();
      }
      // no runtime conversion = very fast
  9. Ben-PH commented on Nov 25, 2025

    @Ben-PH

    Forcing embedded code to treat ADC values as u32 immediately rules out any hardware that uses some other type without incurring overhead, breaking the zero cost abstraction promise that rust provides.

    Such an approach would be appropriate for a third party library that does not make such promises. Before this project can even consider adding non-zero-cost abstractions, it needs to clearly state that using this library breaks the zero-cost-abstraction guarantee. IMHO, such an approach has no place in a core library.

  10. Dirbaio commented on Nov 25, 2025

    @Dirbaio
    Member

    The goal of embedded-hal never has been to provide zero cost abstractions.

  11. Ben-PH commented on Nov 25, 2025

    @Ben-PH

    ZCA is a core tenant of rust. Unless it's explicitly stated as a non goal to provide ZCA, then the goal of ZCA is implied.

    ETA: Unless I missed it, there isn't a disclaimer in the readme that states embedded-hal is not intended to provide ZCA.

  12. bnjmn21 commented on Nov 25, 2025

    @bnjmn21

    You're right. The design goals of embedded-hal do state that ZCA should be used:

    Must be minimal, and thus easy to implement and zero cost, yet highly composable.

    However if this was ZCA, it wouldn't be minimal, so you have to pick one (Unless someone has a better solution I missed). I specifically chose "minimal" over "zero cost" because this is a one-shot API and a single u16 as u32 cast costs 0 or 1 instructions on 32 bit platforms.

  13. Ben-PH commented on Nov 25, 2025

    @Ben-PH

    The way I read that, is there are two mutually exclusive expectations at play here.

    If the way of rust was to take the easy, non-ZCA approach, it would be a very different language to what it is now.

    minimilism/DX is an aspirational goal that exists on a spectrum. It can always be improved.

    ZCA is Boolean. It's not a measure of how many unecisary instructions occurs, but a question of whether or not unecisary logic pollutes the system, which in itself implies wasted instructions.

    One does not need to abandon the works of minimalism to maintain ZCA, but to abandon ZCA because woking towards minimalism within those constraints is Too Hard™ is about the least rusty thing I can think of.

  14. darconeous commented on Nov 25, 2025

    @darconeous

    Should I just whip up a pull request for my original version?

    These are just very simple, straightforward, zero-cost traits that are easy to use, easy to implement, and provide a useful platform abstractions.

    Seems like an obvious win.

    @bnjmn21 : Honestly, having the type be generic doesn't increase complexity that much IMHO. I also think it is important for the methods to have the _oneshot_ part, to make it explicitly clear how the ADC is being used when reading, and what trait it is coming from.

    Also, I don't think having a ONE_VOLT constant is a good idea because the raw reading for what constitutes one volt is dependent on the configuration of the ADC. It is not at all constant. A viable alternative would be to implement a trait that provides a method that returns this value.

  15. bnjmn21 commented on Nov 25, 2025

    @bnjmn21

    Your last point is definitely something I overlooked, and sure, _oneshot_ can be added.
    But the issue with the word being generic is that with the current trait bounds, you cannot do any arithmetic with them in driver/app code. You would need a trait bound like std::ops::Add + std::ops::Mul + everything else or use a solution like num_traits::sign::Unsigned. Additionally it should also be Into<u32>, and Into<u16>, but u32 doesn't implement Into<u16>. So you would need a custom Cast<u16> trait that does _ as u16 casting for that. I hope you understand the problem.

  16. 1 remaining item

  17. darconeous commented on Nov 26, 2025

    @darconeous

    Regarding casting, that seems like an additional constraint that could/should be added to any generics that need to do that.

    Realistically, I think you'd want to use TryInto<> instead of Into<> anyway. And u32 does implement TryInto<u16>.

  18. Dirbaio commented on Nov 26, 2025

    @Dirbaio
    Member

    @Ben-PH: ZCA is a core tenant of rust. Unless it's explicitly stated as a non goal to provide ZCA, then the goal of ZCA is implied.

    You're telling me, a maintainer of this project, what the goal of this project is?

    The goal of embedded-hal is to produce traits that allow any driver to work with any HAL. If these traits can be "zero cost" then great, but "zero cost" is secondary. It comes after the "allow any driver to work with any HAL" goal.

    @darconeous; Should I just whip up a pull request for my original version?

    No, it has an unconstrained Word associated type. This makes it very unwieldy or even impossible to write a driver that works with all HALs, if one HAL implements Word=u32 and another implements it with Word=u16. See here.

  19. Ben-PH commented on Nov 26, 2025

    @Ben-PH

    No, I'm saying that where a feature library that is intended to be core to the rust ecosystem does not explicitly and clearly state that ZCA is a non-goal, then the goal of ZCA is necessarily implied.

    If it is, as you say, a non goal, yet it is not prominently stated in a reasonable spot, i cannot help but feel that to be deceptive.

  20. bnjmn21 commented on Nov 26, 2025

    @bnjmn21

    As dirbaio stated, it is a goal. It's just not really realistic in this specific case because of unconstrained associated types. (Constraining them to be somewhat usable requires an external library like num_traits. embedded_hal is also not the only way to interact with the ADC. You still have the device crate that has ZCA).

    Unless the maintainers agree to add the dependency, this just won't work. And even then it's so difficult to use, that most drivers will probably choose to just cast to u32 anyways, so you might as well do that by default.

    Also no one ever said core libraries have to be ZCA at all costs. See strings performing utf8 validation, etc...

  21. Dirbaio commented on Nov 26, 2025

    @Dirbaio
    Member

    @Ben-PH please refrain from accusing others of being deceptive, it's not civil, nor a good way towards reaching technical agreement.

  22. darconeous commented on Dec 3, 2025

    @darconeous

    I do not understand why num_traits is a requirement. All of the required traits are in std core already. I've already described a way to make it ergonomic.

    Then again, this isn't really the hill I want to die on. u32 is fine by me.

  23. Ben-PH commented on Dec 3, 2025

    @Ben-PH
  24. adamgreig commented on Dec 3, 2025

    @adamgreig
    Member

    @Ben-PH Constructive comments only please. I appreciate your interest in making these traits as widely useful as possible, but ultimately the decisions are the HAL team's. Consider this a warning; if you continue to make unhelpful comments I may block you from engaging with the repository or organisation.

  25. bnjmn21 commented on Dec 4, 2025

    @bnjmn21

    @darconeous Can you please explain again what traits you would add to AdcValue? I'm not sure I understood you correctly. Because if you just do Into<u32> + TryInto<u16>, I don't think it's worth it, because Into / TryInto aren't zero-cost, all they do is make the cast explicit. num_traits::Unsigned is the only way to make it zero-cost, because then you could do arithmetic directly on the generic type, without any casting. (But I don't think that's a good idea, because it adds even more complexity).

  26. Ben-PH commented on Dec 4, 2025

    @Ben-PH

    embedded work, where its generic, must inherently be word size agnostic in order to be zero cost. You cannot say "all devices this will run on will have u32 ADC", because there is nothing stopping a manufacturer for building a 16/8/64/... bit value.

    Rust doesn't exactly have a clear resolution to this, such as a built in way to constrain a type to be a particular set of words (e.g. only u16 OR u32, or only unsigned words 64 bits or less), or to constrain a compile time constant to have specific arithmatic properties (e.g. a particular number range, result of arithmetic, multiple of X, etc), and for them to be used generically. There are third party crates that can do this, but bringing them in is problematic for obvious reasons.

    Given that this is intended to be a hardware abstraction layer system, as opposed to a "shim" layer (i.e. the abstractions resolve to generated code that is applicable directly to any and all compatable hardware, rather than creating a layer that "changes" what the hardware looks like), this limitation should either be resolved, or prominently documented so that users are under no illusion that they are using a zero-cost-abstraction.

    The current thinking, as I've read in this thread, is that not having a specific type (e.g. just type Word;)causes problems when there is divergence in the ecosystem, resulting in incompatibility issues. This is particularly problematic for issues like representing time, but here, we are only concerned with a primitive register value.

    @darconeous has put in some nice work trying to find a clean resolution, only to be shut down on the basis that people will use different word sizes. One possible resolution is that the type wouldn't be type Word: Sized + Copy; but rather type AdcWord: Word, or something along these lines.

    As darconeous said, this is a solvable problem. A supportive environment, where it's seen as a problem that deserves attention and constructive discussion is, I think we can all agree, something to make great efforts to cultivate.

  27. Beanow commented on Dec 4, 2025

    @Beanow

    Something to add to the topic of runtime performance costs.

    I'm sure some of you already had this in mind, but this trait may also want to consider adding however many constants as necessary describing the ADC, to make const math more ergonomic, or easy for a general crate to work with.

    Especially to avoid floating point math at runtime. But perhaps also integer divisions.

    Imagining some pseudo code macro here.

    if reading >= volt!(1.15, ConcreteAdc) && reading <= volt!(1.55, ConcreteAdc) {
      // Between 1.15 and 1.55 volt logic
    }
    
    // Expanded macro does const math, which gets optimized to a specific integer value
    if reading >= 201 && reading <= 352 {
      // Between 1.15 and 1.55 volt logic
    }
  28. darconeous commented on Dec 5, 2025

    @darconeous

    @bnjmn21: My idea was perhaps a bit half baked. Rust is great for hinting that something will be easy when instead it ends up being bonkers. But let's roll up our sleeves and see where this rabbit hole leads... Maybe it ends up working the way I wanted it to.

    The idea was that you would have a AdcChannel trait that would look like this:

    pub trait AdcChannel {
        /// The underlying word type for ADC conversions.
        ///
        /// Typically, this is `u32` or `u16`.
        type Word: AdcWord;
    }

    ...And then have a trait called AdcWord which would have all of the traits implemented for supporting operations. These are all the typical traits that u32 and u16 (and hell maybe even i16) have in common. Yes, there are A LOT, but macros can help, and once it is written you don't have to deal with it anymore (except maybe adding to it on occasion).

    I imagine it would look something kinda like this (if we don't end up defining it with a macro, which we likely should):

    use core::ops::Add;
    use core::ops::AddAssign;
    // ... snip ...
    use core::fmt::UpperHex;
    use core::fmt::LowerHex;
    
    pub trait AdcWord: Sized
        + Copy
        + TryInto<u32>
        + TryInto<u16>
        + Add
        + for<'a> Add<&'a Self>
        + AddAssign
        + for<'a> AddAssign<&'a Self>
        // ... snip ...
        + UpperHex
        + LowerHex
    {}

    Then you'd need to make sure that AdcWord gets implemented automatically for any trait implementing all of those traits. So, something like this:

    impl <T> AdcWord for T where T: Sized
        + Copy
        + TryInto<u32>
        + TryInto<u16>
        + Add
        + for<'a> Add<&'a Self>
        + AddAssign
        + for<'a> AddAssign<&'a Self>
        // ... snip ...
        + UpperHex
        + LowerHex
    {}

    This should, in theory, give you something that very nearly supports everything that you might want to do from a generic, and if you want to do something that happens to fall outside of this list you just bite the bullet and do a .try_into<u16>() or .try_into<u32>()...

    What's nice about this approach is that the long list of traits is an implementation detail that the user of the crate doesn't have to worry about. Generics that use AdcChannel types don't need to worry about that big long list, they would just bind the types using the AdcWord trait. Simple. Ergonomic.

    Now, the list of traits in AdcWord is long, but it is maintainable with macros, and once it is written you are largely done. It allows generics to directly operate on ADC values in a zero-cost way most of the time. In the weird case where that isn't possible (and there are a few), the generic can call .try_into::<u32>() at a cost that is no worse than if we had ended up forcing everyone to use u32.

    I've thrown this into Rust Playround and it seems to compile at least. It will take some effort to put together the full list of traits, but I personally feel like it is worth it. Once it is done it is done.

    As an added bonus you don't need to rely on the num_traits crate. You could add it as an optional addition if you wanted to use those traits in generics too, but eh.

    So that wasn't too bad. Phew.

    I really think this idea is worth considering. It sure seems like all upside (possibility of zero-cost generics) and no downside (when that isn't possible, it's no worse than if we had just forced everyone to use u32).

  29. darconeous commented on Dec 5, 2025

    @darconeous

    And, of course, AdcChannelOneshot would be built on AdcChannel like I described above...

    trait AdcChannelOneshot : AdcChannel + ErrorType {
        /// Returns a single raw ADC reading.
        ///
        /// Calling this method will initiate an ADC conversion,
        /// block until that conversion is complete, and then return
        /// the raw result (or an error).
        ///
        /// The units are dependent on the hardware configuration,
        /// and are outside of the scope of this trait.
        fn read_oneshot(&mut self) -> Result<<Self as AdcChannel>::Word, <Self as ErrorType>::Error>;
    }
    

    I'd be happy to try to put together a pull request on what I think this could look like.

    Note that there is nothing inherently wrong with something being complex, but I don't think this solution is complex. It has a long list of traits, but it is easy to maintain.

    If you want to go the extra mile to make sure that no one implements their own non-standard type that implements AdcWord, then you could implement it directly for the supported types instead of implementing it for every type that implements those traits:

    impl AdcWord for u16 {}
    impl AdcWord for u32 {}
    impl AdcWord for i16 {}
    impl AdcWord for i32 {}
    

    This approach has the benefit that if someone did decide to implement their own non-standard type that we wouldn't break their code if we added traits to AdcWord. Which seems like a good thing. We should probably do that instead. Then the list only needs to be in one place anyway.

  30. i509VCB commented on Jun 15, 2026

    @i509VCB
    Contributor

    I feel one aspect that hasn't been talked about here is that hardware can be run at a lower bit depth than it is capable of. For example the ADC on the MSPM0 parts is 12-bit but can be run at 10-bit or 8-bit.

    I'd propose to add a way to query the max value that a channel can produce so that a driver can then do something like convert an ADC reading to a voltage while not duplicating state and being aware of the range of values the ADC can produce.

    /// ADC channel.
    ///
    /// This does not contain any logic. It only defines the type of a sample read by the ADC.
    pub trait Channel {
        /// The size of a sample value from the ADC.
        type Word: Sized + Copy;
    }
    
    /// ADC channel capable of a one shot measurement.
    pub trait OneShotChannel: Channel + ErrorType {
        /// The maximum value that may be produced by the ADC.
        ///
        /// This is guaranteed to not change once a channel is constructed.
        ///
        /// For example, a 12-bit ADC would return 4095.
        fn max_value(&self) -> Result<Self::Word, Self::Error>;
    
        /// Sample from the ADC.
        fn sample(&mut self) -> Result<Self::Word, Self::Error>;
    }

    I have also writtten up a small set of commits in https://github.com/i509VCB/embedded-hal/tree/adc

    For async, max_value brings up an interesting question:

    /// Asynchronous ADC channel capable of a one shot measurement.
    pub trait OneShotChannel: Channel + ErrorType {
        /// The maximum value that may be produced by the ADC.
        ///
        /// This returns [`Ready`](core::task::Poll::Ready) when the max value is obtained. Some implementations such
        /// as a channel connected over I2C may return [`Pending`](core::task::Poll::Pending) while the max value is
        /// being obtained.
        ///
        /// This is guaranteed to not change once a channel is constructed.
        ///
        /// For example, a 12-bit ADC would return 4095.
        async fn max_value(&self) -> Result<Self::Word, Self::Error>;
    
        /// Sample from the ADC.
        ///
        /// This returns [`Ready`](core::task::Poll::Ready) when the sample is complete.
        async fn sample(&mut self) -> Result<Self::Word, Self::Error>;
    }

    Should max_value be queried always? Or should it be fixed at construction and therefore not async. The fact that I suggest even the blocking impl not allow max value to change dynamically means the same should apply here?

    Also some ADCs support signed values, but I feel these are special cases that embedded-hal would struggle to represent in a single trait (maybe a different one?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions