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
{{ message }}
Repository navigation
Should setting baud rate for serial communication be part of this hal? #79
I believe some way to set baud rate for the serial traits is needed.
Relevant problem
Dynamixel servos comes with two different RS-485 protocols that have some difference in support of baud rate. And even if every servo on your RS-485 bus uses the same protocol there should be nothing stopping you from configuring them with different baud rates. This require setting baud rate before communicating with a servo.
This is currently the biggest blocker for having the dynamixel library work for every embedded-hal implementation out of the box (as it currently does with adapters supporing serialport)
Reacted by Matti Virkkunen, Rafael Bachmann and ryan
Hm, so you're using the Serial trait for RS-485 communication? Interesting. Is this application relying on the fact that a RS-232 to RS-485 adapter is available?
I do agree that there're some uses for on-the-fly configuration changes, so I'd be very much in favour for adding this; however we'd need to check for implementation feasibility. There might be chips which only allow such changes through full re-initialisation which may require resources which are not owned but only borrowed.
Hm, so you're using the Serial trait for RS-485 communication? Interesting. Is this application relying on the fact that a RS-232 to RS-485 adapter is available?
You could use a RS-485 transceiver directly connected to some uart, meaning it's no need for converting to RS-232. Since this is SW and we don't really care about things as differential-lines and voltage levels the only real difference is that with RS-485 you cannot read and write at the same time.
@kjetilkjeka That only works with dedicated hardware. When using a MCU and a RS485 transceiver you will need a "Driver Enable" signal. Expecting the user to manage that manually is not very user friendly and some chips, e.g. STM32 MCUs have hardware support for it which is especially handy if one wants to use async IO.
The simple way is to connect tx together with the enable line. Then you will get dominant 1s and recessive 0s. That is if the mcu doesn't drive the enable line for you.
I would expect the write/read implementation to handle this. If they don't they're pretty much useless. I'm not suggesting such a thing.
Edit: i dont expect the hal to assume what kind of hw you've connected to the uart. This mist be handled in hw or at the initialization.
My point is that you'll need specific setup for that case. You can't just use the regular serial impl and it'll work out automagically for RS-485 as well.
Is this simply an observation, an argument against adding the set baud method or an argument against using the serial traits for RS485?
Perhaps I'm wrong, but i see the serial traits as a generic serial protocol. Much like the stdlib Read/Write traits can be used on network sockets, files, rs485, etc. I expect the serial traits to work on uart, usart, RS232, RS485, etc. Even for the simple uart case you will need "specific setup" as voltage levels might not be the same for the commuinicating units.
It's a somewhat unrelated observation that the serial trait may be lacking more details than just the baudrate selection to be useful for various serial protocols.
I'm in favor of keeping the base Read and Write traits as simple as possible -- they should have to do with transmitting and receiving bytes on the bus, and basically nothing else.
However, I can also see the need for changing the baud rate (and possibly other parameters) at runtime. I'm going to make the same suggestion we've talked about elsewhere: Add a separate, but composable trait (maybe serial::Configure). Something like:
In favor of what @austinglaser suggests with the following additions.
To make the trait useable we must create a way to construct it. What about requiring a fallible conversion from u32 to Freq.
I'm generally in favor of making functions infallible by only allowing legal arguments to be allowed. I think if we want to support weird baudrates (which we do) we must allow the set_baud_rate to fail.
This is a rather messy topic and I don't have good solutions in my head at this time. Your "standard" baud rates are ending far too low, 115200 is rather pedestrian nowadays. Also even "standard" baud rates can very often not be represented exactly and also often this depends on the clock the UART or even the whole system is running at.
For me this means it either should be fallible or there must be a way to determine whether a baud rate can be supported or what the next closest supported value would be.
This is a rather messy topic and I don't have good solutions in my head at this time. Your "standard" baud rates are ending far too low, 115200 is rather pedestrian nowadays.
These are BaudRates that every unit conforming to the embedded-hal needs to support. And it looks like Rust is going to work on 8-bit avr in the future. Perhaps this is a good argument for dropping the infallible set_baud.
Also even "standard" baud rates can very often not be represented exactly
How big of a problem is this? I would be happy with the "best effort" and "you should probably have your impl fail if it's to far away (2-3% or something)"
and also often this depends on the clock the UART or even the whole system is running at.
I guess the solution here is, If the implementation don't know what kind of freq the uart clock runs at this Trait should (read: can) not be implemented.
This alternative would supporting getting an indication of how much off the BaudRate is. But would allow scary things like. interface.set_baud_rate(BaudRate.closest(9999999999)) (the naming is ad-hoc)
#[derive(Debug)]pubstructUnrepresentableBaud;pubtraitBaudRate:Into<f32>{//// Try to crate a `BaudRate` with less than 2% error.fncreate_approximately(baud_rate:u32) -> Reult<(),UnrepresentableBaud>;//// Create the closest `BaudRate` possible to `baud_rate`.fnclosest(baud_rate:u32) -> Self;}pubtraitConfigureBaud{typeBaudRate:BaudRate;fnset_baud_rate(&mutself,baud_rate:Self::BaudRate);}
These are BaudRates that every unit conforming to the embedded-hal needs to support.
Huh?
And it looks like Rust is going to work on 8-bit avr in the future.
Even the ominous ATMega328 officially supports 2 MBaud...
How big of a problem is this? I would be happy with the "best effort" and "you should probably have your impl fail if it's to far away (2-3% or something)"
It's a big problem. I've seen people clock their MCUs specifically for proper serial communication and if this is all automagic then it will cause all sorts of surprises.
I guess the solution here is, If the implementation don't know what kind of freq the uart clock runs at this Trait should (read: can) not be implemented.
Well, often you pass in the relevant clocks when initialising the UART, e.g. from the stm32f103xx-hal:
So the application sets up the clocks and passes it in so there's no way of knowing whether the baud rate is compatible with the current clocks and now coming back to this topic and my previous concern: If you reconfigure the baud rate on the fly you will most likely have to pass in the very same information again that was used during construction to make the proper calculation (and some chips actually require that you turn the peripheral off again to make such a change) but this is all implementation dependant...
So it looks like the temporary spec sheet currently looks:
Cannot be mandatory to implement just to use Write/Read. (must live in its own trait)
Support weird baud rates.
Give an indication of how far away from the desired baud the actual baud is.
Be explicit whether you need an "exact" baud or approximate baud.
Be explicit of when the baud rate change occurs (can this affect bytes already called transmit on?)
Must not require passing any "init" information like uart clock frequency etc.
Of course, be easy to use correctly and hard to use wrongly.
and some chips actually require that you turn the peripheral off again to make such a change
If this is the case, the reconfigurable baud rate should probably not be implemented (or handle these special concerns in software)
So the application sets up the clocks and passes it in so there's no way of knowing whether the baud rate is compatible with the current clocks and now coming back to this topic and my previous concern: If you reconfigure the baud rate on the fly you will most likely have to pass in the very same information again that was used during construction to make the proper calculation
I guess what you mean is "no way of knowing statically"? As the interface could remember its clock frequency. Then you could simply ask the interface whether the new clock freuquency is compatible or not. For instance with:
@little-arhat How would you do this safely? A method on an embedded-hal trait can not contain any of the information usually required to do such a change and for most MCUs it can also not be stored in the implementation since it might require access to shared registers.
@little-arhatunsafe does not necessarily mean that something is not safe but that the compiler can not reason about the safety by itself so it's up to the software author to do that.
Anyway my point is that for a "safe" implementation you actually need to have exclusive access to the resources you're changing to not stomp on someone elses feet. Usually that means that you have to provide mutable references to every resource required to set up the peripheral in the first place which is typically very unwieldy and thus not expected to happen in the middle of a running application but during initialisation. Also due to the very different nature of the vendor peripherals this is not something that can be easily abstracted over in the vendor independent way which makes it highly unsuitable for embedded-hal.
If someone can show a convincing demonstration that this can be generically defined in a trait and usefully implemented for any real hardware I'd be more than happy to help turn it into an extension trait.
I have a device that does auto baudrate detection, but only up to 115200 bps, so in order to run it with a higher baud rate, one would have to:
Auto baud @ < 115200 bps
Set device baud rate to > 115200 bps
Reconfigure UART peripheral to baudrate from point 2
I would like this logic to be contained within the drive crate, thus i need a way to reconfigure the baud rate after initial initialization of the UART.
Many of the current hal's have their own type for baudrates, so giving them the opportunity to use them makes sense and gives them the responsibility of supporting 'weird' rates.
Having the option of returning an error you can limit the available bauds to the ones compatible with a given clock setup or else return an error.
As a response to an earlier issue, if a given clock setup changes and there are not made a way of updating the copy held by the Serial interface. The Serial interface baud is lost anyhow.
Another case in point is using a USART as 1-wire Bus "master". There you need to frequently change the baud rate in order to generate the correct bit patterns.
I think the trait proposal by @unizippro looks good -- note that the BaudRate type used by the implementation could encode information about the clocks if needed, which allows to erase that dependency from the general trait interface.
In addition, I suggest to make the function return nb::Result, in order to allow the impl to wait for an ongoing transmission to complete or any other precondition necessary to change the baud rate.
from a consumer perspective imo it's better to use an u32 value for baud rate, otherwise you have to add a bunch of complexity to abstract over the BaudRate type
i'd be inclined to return the actual baud instead of () on success to let users know what was achievable with the oscillators available (it's normal for there to be a slight difference between requested and actual bauds due to clocking).
if you would like to contribute this i would suggest going forward with an e-h and demonstration PR, any further trait-specific discussion can occur there ^_^
I'd just make baudrate an u32 (or maybe some Hertz concrete type that is in embedded-hal that wraps an u32 or something)
Having an unconstrained type BaudRate seems like the same mistake in #324, #201, #177 (comment) . Different HALs will use different types among u32, whatever Hertz they have, or stuff from embedded-time or similar, making the trait impossible to use from HAL-independent drivers.
I have to agree with @ryankurte that this should be fleshed out in a demonstrator PR. I still have strong doubts this is generally implementable without gnarly hacks but would love to be proven wrong.
I implemented a similar trait as PoC based on the stm32f1xx-hal. I had to use the unconstrained (custom) BaudRate type to force the user to go through a function which calculates the correct register value from the current clocks. The Serial in stm32f1xx-hal is mostly a zero-sized type and does not hold a reference to the (frozen) clocks.
It looks roughly like this:
pubtraitAsyncSetBaudRate{typeError:Debug;typeBaudRate;fnpoll_set_baud_rate(&'_mutself,rate:&Self::BaudRate,cx:&mutContext<'_>,) -> Poll<Result<(),Self::Error>>;}pubtraitBaudRateGenerator<T>{fncalc_baud_rate(&self,bps:u32) -> T;}#[derive(Clone,Copy)]pubstructBaudRateConfig{config: serial::Config,// serial from stm32f1xx_halclocks: rcc::Clocks,// rcc from stm32f1xx_hal}pubstructBaudRateFromClocks<'x>(pub&'x rcc::Clocks);impl<'x> usart::BaudRateGenerator<BaudRateConfig>forBaudRateFromClocks<'x>{fncalc_baud_rate(&self,bps:u32) -> BaudRateConfig{BaudRateConfig{config: serial::Config::default().baudrate(bps.bps()),clocks:*self.0,}}}
(sorry, I'm a bit in a hurry right now so no proper minimal test code)
I'm not convinced this is the best design (for instance, this is not actually calculating the BRR register value and storing it in BaudRate, but instead only putting the necessary values to call reconfigure on the Serial), but it was possible to implement this without modifying stm32f1xx_hal.
To improve the implementation, I would've had to modify stm32f1xx_hal to support setting only the baud rate and to provide a wrapper type around the register's integer type in order to allow precalculating that value from frozen clocks.
Without that, the trait would indeed force the Serial implementations to know about the current clock rates, which sounds painful at least.
I had to use the unconstrained (custom) BaudRate type to force the user to go through a function which calculates the correct register value from the current clocks
If calling the trait needs calling HAL-specific methods/types, it can't be used from HAL-independent drivers. With this design, set_baud_rate might as well be an inherent method in Uart instead of a trait method, since the advantage of having traits is writing HAL-independent drivers, and this trait is not fulfilling that.
the trait would indeed force the Serial implementations to know about the current clock rates, which sounds painful at least.
embassy-stm32 stores the current clocks in a global, so Uart/Spi/I2c/etc have access to it at all times. WIth that design it's possible (and not painful at all) to implement a trait like fn set_baudrate(&mut self, baud_rate: u32), which would be useful for HAL-independent drivers (no unconstrained BaudRate type)
Activity
kjetilkjeka commentedon Apr 22, 2018
One possible solution could be to introduce a
serial::Serialtrait that implements theset_baud_rate(&mut self) -> Result<(), Self::Error>.Then i could auto implement the dynamixel interface for
Serial + Write + Readtypestherealprof commentedon Apr 22, 2018
Hm, so you're using the
Serialtrait for RS-485 communication? Interesting. Is this application relying on the fact that a RS-232 to RS-485 adapter is available?I do agree that there're some uses for on-the-fly configuration changes, so I'd be very much in favour for adding this; however we'd need to check for implementation feasibility. There might be chips which only allow such changes through full re-initialisation which may require resources which are not owned but only borrowed.
kjetilkjeka commentedon Apr 22, 2018
currently I've only implemented it for this serial trait. I've tested it with an ftdi like rs485 usb dongle.
You could use a RS-485 transceiver directly connected to some uart, meaning it's no need for converting to RS-232. Since this is SW and we don't really care about things as differential-lines and voltage levels the only real difference is that with RS-485 you cannot read and write at the same time.
therealprof commentedon Apr 24, 2018
@kjetilkjeka That only works with dedicated hardware. When using a MCU and a RS485 transceiver you will need a "Driver Enable" signal. Expecting the user to manage that manually is not very user friendly and some chips, e.g. STM32 MCUs have hardware support for it which is especially handy if one wants to use async IO.
kjetilkjeka commentedon Apr 24, 2018
The simple way is to connect tx together with the enable line. Then you will get dominant 1s and recessive 0s. That is if the mcu doesn't drive the enable line for you.
I would expect the write/read implementation to handle this. If they don't they're pretty much useless. I'm not suggesting such a thing.
Edit: i dont expect the hal to assume what kind of hw you've connected to the uart. This mist be handled in hw or at the initialization.
therealprof commentedon Apr 24, 2018
My point is that you'll need specific setup for that case. You can't just use the regular serial impl and it'll work out automagically for RS-485 as well.
kjetilkjeka commentedon Apr 24, 2018
Is this simply an observation, an argument against adding the set baud method or an argument against using the serial traits for RS485?
Perhaps I'm wrong, but i see the serial traits as a generic serial protocol. Much like the stdlib Read/Write traits can be used on network sockets, files, rs485, etc. I expect the serial traits to work on uart, usart, RS232, RS485, etc. Even for the simple uart case you will need "specific setup" as voltage levels might not be the same for the commuinicating units.
therealprof commentedon Apr 24, 2018
It's a somewhat unrelated observation that the serial trait may be lacking more details than just the baudrate selection to be useful for various serial protocols.
austinglaser commentedon Apr 24, 2018
I'm in favor of keeping the base
ReadandWritetraits as simple as possible -- they should have to do with transmitting and receiving bytes on the bus, and basically nothing else.However, I can also see the need for changing the baud rate (and possibly other parameters) at runtime. I'm going to make the same suggestion we've talked about elsewhere: Add a separate, but composable trait (maybe
serial::Configure). Something like:This doesn't break existing implementations, and leaves it to implementers to decide whether such configuration makes sense for their use-case.
kjetilkjeka commentedon Apr 25, 2018
In favor of what @austinglaser suggests with the following additions.
set_baud_rateto fail.Another alternative could be to distinguish between interfaces supporting weird and non-weird bauds:
therealprof commentedon Apr 25, 2018
This is a rather messy topic and I don't have good solutions in my head at this time. Your "standard" baud rates are ending far too low, 115200 is rather pedestrian nowadays. Also even "standard" baud rates can very often not be represented exactly and also often this depends on the clock the UART or even the whole system is running at.
For me this means it either should be fallible or there must be a way to determine whether a baud rate can be supported or what the next closest supported value would be.
kjetilkjeka commentedon Apr 25, 2018
These are
BaudRatesthat every unit conforming to the embedded-hal needs to support. And it looks like Rust is going to work on 8-bit avr in the future. Perhaps this is a good argument for dropping the infallibleset_baud.How big of a problem is this? I would be happy with the "best effort" and "you should probably have your impl fail if it's to far away (2-3% or something)"
I guess the solution here is, If the implementation don't know what kind of freq the uart clock runs at this Trait should (read: can) not be implemented.
This alternative would supporting getting an indication of how much off the
BaudRateis. But would allow scary things like.interface.set_baud_rate(BaudRate.closest(9999999999))(the naming is ad-hoc)therealprof commentedon Apr 25, 2018
Huh?
Even the ominous ATMega328 officially supports 2 MBaud...
It's a big problem. I've seen people clock their MCUs specifically for proper serial communication and if this is all automagic then it will cause all sorts of surprises.
Well, often you pass in the relevant clocks when initialising the UART, e.g. from the
stm32f103xx-hal:So the application sets up the clocks and passes it in so there's no way of knowing whether the baud rate is compatible with the current clocks and now coming back to this topic and my previous concern: If you reconfigure the baud rate on the fly you will most likely have to pass in the very same information again that was used during construction to make the proper calculation (and some chips actually require that you turn the peripheral off again to make such a change) but this is all implementation dependant...
kjetilkjeka commentedon Apr 25, 2018
So it looks like the temporary spec sheet currently looks:
If this is the case, the reconfigurable baud rate should probably not be implemented (or handle these special concerns in software)
I guess what you mean is "no way of knowing statically"? As the interface could remember its clock frequency. Then you could simply ask the interface whether the new clock freuquency is compatible or not. For instance with:
therealprof commentedon Apr 25, 2018
The problem with "remembering" is, that the clock might actually change...
At the moment, the most compatible and safest way to change the baud rate would be to drop and reinitialise the serial interface.
4 remaining items
therealprof commentedon May 13, 2019
@little-arhat How would you do this safely? A method on an
embedded-haltrait can not contain any of the information usually required to do such a change and for most MCUs it can also not be stored in the implementation since it might require access to shared registers.little-arhat commentedon May 13, 2019
@therealprof that what this issue is about, I guess: should embedded-hal include methods like
set_speed(bps)orset_bus_frequency(hz).therealprof commentedon May 13, 2019
@little-arhat And my question was: Are those methods even (safely) implementable? I have strong doubts that they are (in general at least)...
little-arhat commentedon May 13, 2019
@therealprof I don't know, but do they have to be safe?
For example, this hal implementation has buncf of
unsafecalls inWatchdog,OutputPin,InputPin, and maybe others.On the other hand, stm32 HAL doesn't provide such functions.
therealprof commentedon May 13, 2019
@little-arhat
unsafedoes not necessarily mean that something is not safe but that the compiler can not reason about the safety by itself so it's up to the software author to do that.Anyway my point is that for a "safe" implementation you actually need to have exclusive access to the resources you're changing to not stomp on someone elses feet. Usually that means that you have to provide mutable references to every resource required to set up the peripheral in the first place which is typically very unwieldy and thus not expected to happen in the middle of a running application but during initialisation. Also due to the very different nature of the vendor peripherals this is not something that can be easily abstracted over in the vendor independent way which makes it highly unsuitable for
embedded-hal.If someone can show a convincing demonstration that this can be generically defined in a trait and usefully implemented for any real hardware I'd be more than happy to help turn it into an extension trait.
MathiasKoch commentedon Apr 15, 2020
I'd like to bring this back up.
I have a device that does auto baudrate detection, but only up to 115200 bps, so in order to run it with a higher baud rate, one would have to:
I would like this logic to be contained within the drive crate, thus i need a way to reconfigure the baud rate after initial initialization of the UART.
unizippro commentedon May 5, 2020
How does a trait like this look?
Many of the current hal's have their own type for baudrates, so giving them the opportunity to use them makes sense and gives them the responsibility of supporting 'weird' rates.
Having the option of returning an error you can limit the available bauds to the ones compatible with a given clock setup or else return an error.
As a response to an earlier issue, if a given clock setup changes and there are not made a way of updating the copy held by the Serial interface. The Serial interface baud is lost anyhow.
barafael commentedon Feb 16, 2021
For e.g. HC-12 serial transceiver module, this would make it possible to change the baud rate (which the module requires for supporting all modes).
horazont commentedon Jan 8, 2022
Another case in point is using a USART as 1-wire Bus "master". There you need to frequently change the baud rate in order to generate the correct bit patterns.
I think the trait proposal by @unizippro looks good -- note that the
BaudRatetype used by the implementation could encode information about the clocks if needed, which allows to erase that dependency from the general trait interface.In addition, I suggest to make the function return
nb::Result, in order to allow the impl to wait for an ongoing transmission to complete or any other precondition necessary to change the baud rate.ryankurte commentedon Jan 9, 2022
seems broadly good to me.
u32value for baud rate, otherwise you have to add a bunch of complexity to abstract over theBaudRatetype()on success to let users know what was achievable with the oscillators available (it's normal for there to be a slight difference between requested and actual bauds due to clocking).if you would like to contribute this i would suggest going forward with an
e-hand demonstration PR, any further trait-specific discussion can occur there ^_^Dirbaio commentedon Jan 9, 2022
I'd just make baudrate an
u32(or maybe someHertzconcrete type that is inembedded-halthat wraps an u32 or something)Having an unconstrained
type BaudRateseems like the same mistake in #324, #201, #177 (comment) . Different HALs will use different types amongu32, whateverHertzthey have, or stuff fromembedded-timeor similar, making the trait impossible to use from HAL-independent drivers.therealprof commentedon Jan 9, 2022
I have to agree with @ryankurte that this should be fleshed out in a demonstrator PR. I still have strong doubts this is generally implementable without gnarly hacks but would love to be proven wrong.
horazont commentedon Jan 10, 2022
I implemented a similar trait as PoC based on the stm32f1xx-hal. I had to use the unconstrained (custom) BaudRate type to force the user to go through a function which calculates the correct register value from the current clocks. The Serial in stm32f1xx-hal is mostly a zero-sized type and does not hold a reference to the (frozen) clocks.
It looks roughly like this:
(sorry, I'm a bit in a hurry right now so no proper minimal test code)
I'm not convinced this is the best design (for instance, this is not actually calculating the BRR register value and storing it in BaudRate, but instead only putting the necessary values to call
reconfigureon the Serial), but it was possible to implement this without modifying stm32f1xx_hal.To improve the implementation, I would've had to modify stm32f1xx_hal to support setting only the baud rate and to provide a wrapper type around the register's integer type in order to allow precalculating that value from frozen clocks.
Without that, the trait would indeed force the Serial implementations to know about the current clock rates, which sounds painful at least.
Dirbaio commentedon Jan 10, 2022
If calling the trait needs calling HAL-specific methods/types, it can't be used from HAL-independent drivers. With this design,
set_baud_ratemight as well be an inherent method in Uart instead of a trait method, since the advantage of having traits is writing HAL-independent drivers, and this trait is not fulfilling that.embassy-stm32 stores the current clocks in a global, so Uart/Spi/I2c/etc have access to it at all times. WIth that design it's possible (and not painful at all) to implement a trait like
fn set_baudrate(&mut self, baud_rate: u32), which would be useful for HAL-independent drivers (no unconstrainedBaudRatetype)Merge rust-embedded#79