You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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)
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...
Reacted by Christoph, Ben, Robert Quattlebaum and Fabian
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.
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.
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.
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?
traitAdcChannel{/// The underlying word type for ADC conversions.////// Typically, this is `u32` or `u16`.typeWord:Sized + Copy;}traitAdcChannelOneshot: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.fnread_oneshot(&mutself) -> Result<<SelfasAdcChannel>::Word, <SelfasErrorType>::Error>;}traitAdcChannelOneshotMv: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).fnread_oneshot_mv(&mutself) -> Result<<SelfasAdcChannel>::Word, <SelfasErrorType>::Error>;}
And maybe some async versions:
traitAdcChannelOneshotAsync:AdcChannel + ErrorType{fnpoll_read_oneshot(&mutself,cx:&mutContext<'_>)
-> Poll<Result<<SelfasAdcChannel>::Word, <SelfasErrorType>::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.
Reacted by Mariano Francisco Rodriguez, Sematre and Ben
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.
traitAdcChannelOneshot:ErrorType{constONE_VOLT:u32;fnto_mv(raw_value:u32) -> u32{// may be overridden by more optimal impl(raw_value *1000) / Self::ONE_VOLT}fnread_raw(&mutself) -> Result<u32, <SelfasErrorType>::Error>;fnread_mv(&mutself) -> Result<u32, <SelfasErrorType>::Error>{// may be overridden by hardware functionself.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:
constTHRESHOLD:u32 = 3*Adc::ONE_VOLT;if adc.read_raw() > THRESHOLD{do_stuff();}// no runtime conversion = very fast
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.
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.
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.
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.
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.
@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.
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.
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...
I do not understand why num_traits is a requirement. All of the required traits are in stdcore 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.
@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.
@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).
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.
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 valueif reading >= 201 && reading <= 352{// Between 1.15 and 1.55 volt logic}
@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:
pubtraitAdcChannel{/// The underlying word type for ADC conversions.////// Typically, this is `u32` or `u16`.typeWord: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):
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).
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.
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.pubtraitChannel{/// The size of a sample value from the ADC.typeWord:Sized + Copy;}/// ADC channel capable of a one shot measurement.pubtraitOneShotChannel: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.fnmax_value(&self) -> Result<Self::Word,Self::Error>;/// Sample from the ADC.fnsample(&mutself) -> Result<Self::Word,Self::Error>;}
For async, max_value brings up an interesting question:
/// Asynchronous ADC channel capable of a one shot measurement.pubtraitOneShotChannel: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.asyncfnmax_value(&self) -> Result<Self::Word,Self::Error>;/// Sample from the ADC.////// This returns [`Ready`](core::task::Poll::Ready) when the sample is complete.asyncfnsample(&mutself) -> 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?)
Activity
ryankurte commentedon Apr 28, 2022
the updated
spitraits have me wondering if a similar approach would suit for ADCs... something like a sharedAdcDevicethat is split into separate channels implementingAdcChannelwhich 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)
Dirbaio commentedon Apr 28, 2022
Maybe having a trait for an "ADC device" is not really needed? We could just have this
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!Sendso that the user can't hit the ADC concurrently from multiple threads (irq priority levels).I don't think making traits for these is feasible, they're incredibly hardware dependent...
ryankurte commentedon Apr 29, 2022
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
AdcChannelcould be a good start.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.
eldruin commentedon May 11, 2022
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.
crjeder commentedon Jul 14, 2022
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.
Ben-PH commentedon May 28, 2024
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.
darconeous commentedon Mar 28, 2025
So something like this, perhaps?
And maybe some async versions:
Having the ability to at least have reads be abstracted away helps make my code portable, so something like this would be very useful.
bnjmn21 commentedon Nov 25, 2025
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.
Async versions accordingly.
Changes:
readis renamed toread_raw. Havingoneshotin every function name is redundant imo.read_rawfn. In this caseONE_VOLTandto_mvhelps for doing manual computations, See this example:Ben-PH commentedon Nov 25, 2025
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.
Dirbaio commentedon Nov 25, 2025
The goal of embedded-hal never has been to provide zero cost abstractions.
Ben-PH commentedon Nov 25, 2025
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.
bnjmn21 commentedon Nov 25, 2025
You're right. The design goals of embedded-hal do state that ZCA should be used:
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 u32cast costs 0 or 1 instructions on 32 bit platforms.Ben-PH commentedon Nov 25, 2025
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.
darconeous commentedon Nov 25, 2025
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_VOLTconstant 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.bnjmn21 commentedon Nov 25, 2025
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 elseor use a solution likenum_traits::sign::Unsigned. Additionally it should also beInto<u32>, andInto<u16>, but u32 doesn't implementInto<u16>. So you would need a customCast<u16>trait that does_ as u16casting for that. I hope you understand the problem.1 remaining item
darconeous commentedon Nov 26, 2025
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 ofInto<>anyway. Andu32does implementTryInto<u16>.Dirbaio commentedon Nov 26, 2025
You're telling me, a maintainer of this project, what the goal of this project is?
The goal of
embedded-halis 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.No, it has an unconstrained
Wordassociated 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.Ben-PH commentedon Nov 26, 2025
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.
bnjmn21 commentedon Nov 26, 2025
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...
Dirbaio commentedon Nov 26, 2025
@Ben-PH please refrain from accusing others of being deceptive, it's not civil, nor a good way towards reaching technical agreement.
darconeous commentedon Dec 3, 2025
I do not understand why
num_traitsis a requirement. All of the required traits are instdcorealready. I've already described a way to make it ergonomic.Then again, this isn't really the hill I want to die on.
u32is fine by me.Ben-PH commentedon Dec 3, 2025
adamgreig commentedon Dec 3, 2025
@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.
bnjmn21 commentedon Dec 4, 2025
@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 doInto<u32> + TryInto<u16>, I don't think it's worth it, becauseInto/TryIntoaren't zero-cost, all they do is make the cast explicit.num_traits::Unsignedis 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).Ben-PH commentedon Dec 4, 2025
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 rathertype 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.
Beanow commentedon Dec 4, 2025
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
constmath 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.
darconeous commentedon Dec 5, 2025
@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
AdcChanneltrait that would look like this:...And then have a trait called
AdcWordwhich would have all of the traits implemented for supporting operations. These are all the typical traits thatu32andu16(and hell maybe eveni16) 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):
Then you'd need to make sure that
AdcWordgets implemented automatically for any trait implementing all of those traits. So, something like this: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
AdcChanneltypes don't need to worry about that big long list, they would just bind the types using theAdcWordtrait. Simple. Ergonomic.Now, the list of traits in
AdcWordis 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 useu32.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_traitscrate. 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).darconeous commentedon Dec 5, 2025
And, of course,
AdcChannelOneshotwould be built onAdcChannellike I described above...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: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.i509VCB commentedon Jun 15, 2026
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.
I have also writtten up a small set of commits in https://github.com/i509VCB/embedded-hal/tree/adc
For async,
max_valuebrings up an interesting question: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?)