1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
//! HAL abstractions for USART/Serial
//!
//! Check the documentation of [`Usart`] for details.
use crate::prelude::*;
use core::cmp::Ordering;
use core::marker;
use crate::port;
/// Representation of a USART baudrate
///
/// Precalculated parameters for configuring a certain USART baudrate.
#[derive(Debug, Clone, Copy)]
pub struct Baudrate<CLOCK> {
/// Value of the `UBRR#` register
pub ubrr: u16,
/// Value of the `U2X#` bit
pub u2x: bool,
/// The baudrate calculation depends on the configured clock rate, thus a `CLOCK` generic
/// parameter is needed.
pub _clock: marker::PhantomData<CLOCK>,
}
impl<CLOCK: crate::clock::Clock> PartialEq for Baudrate<CLOCK> {
fn eq(&self, other: &Self) -> bool {
self.compare_value() == other.compare_value()
}
}
impl<CLOCK: crate::clock::Clock> Eq for Baudrate<CLOCK> {}
impl<CLOCK: crate::clock::Clock> PartialOrd for Baudrate<CLOCK> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.compare_value().cmp(&other.compare_value()))
}
}
impl<CLOCK: crate::clock::Clock> Ord for Baudrate<CLOCK> {
fn cmp(&self, other: &Self) -> Ordering {
other.compare_value().cmp(&self.compare_value())
}
}
impl<CLOCK: crate::clock::Clock> From<u32> for Baudrate<CLOCK> {
fn from(baud: u32) -> Self {
Baudrate::new(baud)
}
}
impl<CLOCK: crate::clock::Clock> Baudrate<CLOCK> {
/// Calculate parameters for a certain baudrate at a certain `CLOCK` speed.
pub fn new(baud: u32) -> Baudrate<CLOCK> {
let mut ubrr = (CLOCK::FREQ / 4 / baud - 1) / 2;
let mut u2x = true;
debug_assert!(ubrr <= u16::MAX as u32);
if ubrr > 4095 {
u2x = false;
ubrr = (CLOCK::FREQ / 8 / baud - 1) / 2;
}
Baudrate {
ubrr: ubrr as u16,
u2x,
_clock: marker::PhantomData,
}
}
/// Construct a `Baudrate` from given `UBRR#` and `U2X#` values.
///
/// This provides exact control over the resulting clock speed.
pub fn with_exact(u2x: bool, ubrr: u16) -> Baudrate<CLOCK> {
Baudrate {
ubrr,
u2x,
_clock: marker::PhantomData,
}
}
fn compare_value(&self) -> u32 {
if self.u2x {
8 * (self.ubrr as u32 + 1)
} else {
16 * (self.ubrr as u32 + 1)
}
}
}
/// Provide a `into_baudrate()` method for integers.
///
/// This extension trait allows conveniently initializing a baudrate by using
///
/// ```
/// let mut serial = arduino_uno::Serial::new(
/// dp.USART0,
/// pins.d0,
/// pins.d1.into_output(&mut pins.ddr),
/// 57600.into_baudrate(),
/// );
/// ```
///
/// instead of having to call [`Baudrate::new(57600)`](Baudrate::new).
pub trait BaudrateExt {
/// Calculate baudrate parameters from this number.
fn into_baudrate<CLOCK: crate::clock::Clock>(self) -> Baudrate<CLOCK>;
}
impl BaudrateExt for u32 {
fn into_baudrate<CLOCK: crate::clock::Clock>(self) -> Baudrate<CLOCK> {
Baudrate::new(self)
}
}
/// Same as [`BaudrateExt`] but accounts for an errata of certain Arduino boards:
///
/// The affected boards where this trait should be used instead are:
///
/// - Duemilanove
/// - Uno
/// - Mega 2560
pub trait BaudrateArduinoExt {
/// Calculate baudrate parameters from this number (with Arduino errata).
fn into_baudrate<CLOCK: crate::clock::Clock>(self) -> Baudrate<CLOCK>;
}
impl BaudrateArduinoExt for u32 {
fn into_baudrate<CLOCK: crate::clock::Clock>(self) -> Baudrate<CLOCK> {
let br = Baudrate::new(self);
// hardcoded exception for 57600 for compatibility with the bootloader
// shipped with the Duemilanove and previous boards and the firmware
// on the 8U2 on the Uno and Mega 2560.
//
// https://github.com/arduino/ArduinoCore-avr/blob/3055c1efa3c6980c864f661e6c8cc5d5ac773af4/cores/arduino/HardwareSerial.cpp#L123-L132
if CLOCK::FREQ == 16_000_000 && br.ubrr == 34 && br.u2x {
// (CLOCK::FREQ / 8 / 57600 - 1) / 2 == 16
Baudrate::with_exact(false, 16)
} else {
br
}
}
}
/// Events/Interrupts for USART peripherals
#[repr(u8)]
pub enum Event {
/// A complete byte was received.
///
/// Corresponds to the `USART_RX` or `USART#_RX` interrupt. Please refer to the datasheet for
/// your MCU for details.
RxComplete,
/// A compete byte was sent.
///
/// Corresponds to the `USART_TX` or `USART#_TX` interrupt. Please refer to the datasheet for
/// your MCU for details.
TxComplete,
/// All data from the USART data register was transmitted.
///
/// Corresponds to the `USART_UDRE` or `USART#_UDRE` interrupt. Please refer to the datasheet
/// for your MCU for details.
DataRegisterEmpty,
}
/// Internal trait for low-level USART peripherals.
///
/// This trait defines the common interface for all USART peripheral variants. It is used as an
/// intermediate abstraction ontop of which the [`Usart`] API is built. **Prefer using the
/// [`Usart`] API instead of this trait.**
pub trait UsartOps<H, RX, TX> {
/// Enable & initialize this USART peripheral to the given baudrate.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_init<CLOCK>(&mut self, baudrate: Baudrate<CLOCK>);
/// Disable this USART peripheral such that the pins can be used for other purposes again.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_deinit(&mut self);
/// Flush all remaining data in the TX buffer.
///
/// This operation must be non-blocking and return [`nb::Error::WouldBlock`] if not all data
/// was flushed yet.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_flush(&mut self) -> nb::Result<(), core::convert::Infallible>;
/// Write a byte to the TX buffer.
///
/// This operation must be non-blocking and return [`nb::Error::WouldBlock`] until the byte is
/// enqueued. The operation should not wait for the byte to have actually been sent.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_write(&mut self, byte: u8) -> nb::Result<(), core::convert::Infallible>;
/// Read a byte from the RX buffer.
///
/// This operation must be non-blocking and return [`nb::Error::WouldBlock`] if no incoming
/// byte is available.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_read(&mut self) -> nb::Result<u8, core::convert::Infallible>;
/// Enable/Disable a certain interrupt.
///
/// **Warning**: This is a low-level method and should not be called directly from user code.
fn raw_interrupt(&mut self, event: Event, state: bool);
}
/// USART/Serial driver
///
/// # Example
/// (This example is taken from Arduino Uno)
/// ```
/// let dp = arduino_uno::Peripherals::take().unwrap();
/// let mut pins = arduino_uno::Pins::new(dp.PORTB, dp.PORTC, dp.PORTD);
/// let mut serial = arduino_uno::Serial::new(
/// dp.USART0,
/// pins.d0,
/// pins.d1.into_output(&mut pins.ddr),
/// 57600.into_baudrate(),
/// );
///
/// ufmt::uwriteln!(&mut serial, "Hello from Arduino!\r").unwrap_infallible();
///
/// loop {
/// let b = nb::block!(serial.read()).unwrap_infallible();
/// ufmt::uwriteln!(&mut serial, "Got {}!\r", b).unwrap_infallible();
/// }
/// ```
pub struct Usart<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> {
p: USART,
rx: RX,
tx: TX,
_clock: marker::PhantomData<CLOCK>,
_h: marker::PhantomData<H>,
}
impl<H, USART, RXPIN, TXPIN, CLOCK>
Usart<
H,
USART,
port::Pin<port::mode::Input, RXPIN>,
port::Pin<port::mode::Output, TXPIN>,
CLOCK,
>
where
USART: UsartOps<H, port::Pin<port::mode::Input, RXPIN>, port::Pin<port::mode::Output, TXPIN>>,
RXPIN: port::PinOps,
TXPIN: port::PinOps,
{
/// Initialize a USART peripheral on the given pins.
///
/// Note that the RX and TX pins are hardwired for each USART peripheral and you *must* pass
/// the correct ones. This is enforced at compile time.
pub fn new<IMODE: port::mode::InputMode>(
p: USART,
rx: port::Pin<port::mode::Input<IMODE>, RXPIN>,
tx: port::Pin<port::mode::Output, TXPIN>,
baudrate: Baudrate<CLOCK>,
) -> Self {
let mut usart = Self {
p,
rx: rx.forget_imode(),
tx,
_clock: marker::PhantomData,
_h: marker::PhantomData,
};
usart.p.raw_init(baudrate);
usart
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> Usart<H, USART, RX, TX, CLOCK> {
/// Deinitialize/disable this peripheral and release the pins.
pub fn release(mut self) -> (USART, RX, TX) {
self.p.raw_deinit();
(self.p, self.rx, self.tx)
}
/// Block until all remaining data has been transmitted.
pub fn flush(&mut self) {
nb::block!(self.p.raw_flush()).unwrap_infallible()
}
/// Transmit a byte.
///
/// This method will block until the byte has been enqueued for transmission but **not** until
/// it was entirely sent.
pub fn write_byte(&mut self, byte: u8) {
nb::block!(self.p.raw_write(byte)).unwrap_infallible()
}
/// Receive a byte.
///
/// This method will block until a byte could be received.
pub fn read_byte(&mut self) -> u8 {
nb::block!(self.p.raw_read()).unwrap_infallible()
}
/// Enable the interrupt for [`Event`].
pub fn listen(&mut self, event: Event) {
self.p.raw_interrupt(event, true);
}
/// Disable the interrupt for [`Event`].
pub fn unlisten(&mut self, event: Event) {
self.p.raw_interrupt(event, false);
}
/// Split this USART into a [`UsartReader`] and a [`UsartWriter`].
///
/// This allows concurrently receiving and transmitting data from different contexts.
pub fn split(
self,
) -> (
UsartReader<H, USART, RX, TX, CLOCK>,
UsartWriter<H, USART, RX, TX, CLOCK>,
) {
(
UsartReader {
p: unsafe { core::ptr::read(&self.p) },
rx: self.rx,
_tx: marker::PhantomData,
_clock: marker::PhantomData,
_h: marker::PhantomData,
},
UsartWriter {
p: self.p,
tx: self.tx,
_rx: marker::PhantomData,
_clock: marker::PhantomData,
_h: marker::PhantomData,
},
)
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> ufmt::uWrite for Usart<H, USART, RX, TX, CLOCK> {
type Error = core::convert::Infallible;
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
for b in s.as_bytes().iter() {
self.write_byte(*b);
}
Ok(())
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> embedded_hal_v0::serial::Write<u8>
for Usart<H, USART, RX, TX, CLOCK>
{
type Error = core::convert::Infallible;
fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
self.p.raw_write(byte)
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
self.p.raw_flush()
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> embedded_hal_v0::serial::Read<u8>
for Usart<H, USART, RX, TX, CLOCK>
{
type Error = core::convert::Infallible;
fn read(&mut self) -> nb::Result<u8, Self::Error> {
self.p.raw_read()
}
}
/// Writer half of a [`Usart`] peripheral.
///
/// Created by calling [`Usart::split`]. Splitting a peripheral into reader and writer allows
/// concurrently receiving and transmitting data from different contexts.
///
/// The writer half most notably implements [`embedded_hal_v0::serial::Write`] and [`ufmt::uWrite`]
/// for transmitting data.
pub struct UsartWriter<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> {
p: USART,
tx: TX,
_rx: marker::PhantomData<RX>,
_clock: marker::PhantomData<CLOCK>,
_h: marker::PhantomData<H>,
}
/// Reader half of a [`Usart`] peripheral.
///
/// Created by calling [`Usart::split`]. Splitting a peripheral into reader and writer allows
/// concurrently receiving and transmitting data from different contexts.
///
/// The reader half most notably implements [`embedded_hal_v0::serial::Read`] for receiving data.
pub struct UsartReader<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> {
p: USART,
rx: RX,
_tx: marker::PhantomData<TX>,
_clock: marker::PhantomData<CLOCK>,
_h: marker::PhantomData<H>,
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> UsartWriter<H, USART, RX, TX, CLOCK> {
/// Merge this `UsartWriter` with a [`UsartReader`] back into a single [`Usart`] peripheral.
pub fn reunite(
self,
other: UsartReader<H, USART, RX, TX, CLOCK>,
) -> Usart<H, USART, RX, TX, CLOCK> {
Usart {
p: self.p,
rx: other.rx,
tx: self.tx,
_clock: marker::PhantomData,
_h: marker::PhantomData,
}
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> UsartReader<H, USART, RX, TX, CLOCK> {
/// Merge this `UsartReader` with a [`UsartWriter`] back into a single [`Usart`] peripheral.
pub fn reunite(
self,
other: UsartWriter<H, USART, RX, TX, CLOCK>,
) -> Usart<H, USART, RX, TX, CLOCK> {
Usart {
p: self.p,
rx: self.rx,
tx: other.tx,
_clock: marker::PhantomData,
_h: marker::PhantomData,
}
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> ufmt::uWrite
for UsartWriter<H, USART, RX, TX, CLOCK>
{
type Error = core::convert::Infallible;
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
for b in s.as_bytes().iter() {
nb::block!(self.p.raw_write(*b)).unwrap_infallible()
}
Ok(())
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> embedded_hal_v0::serial::Write<u8>
for UsartWriter<H, USART, RX, TX, CLOCK>
{
type Error = core::convert::Infallible;
fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
self.p.raw_write(byte)
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
self.p.raw_flush()
}
}
impl<H, USART: UsartOps<H, RX, TX>, RX, TX, CLOCK> embedded_hal_v0::serial::Read<u8>
for UsartReader<H, USART, RX, TX, CLOCK>
{
type Error = core::convert::Infallible;
fn read(&mut self) -> nb::Result<u8, Self::Error> {
self.p.raw_read()
}
}
#[macro_export]
macro_rules! impl_usart_traditional {
(
hal: $HAL:ty,
peripheral: $USART:ty,
register_suffix: $n:expr,
rx: $rxpin:ty,
tx: $txpin:ty,
) => {
$crate::paste::paste! {
impl $crate::usart::UsartOps<
$HAL,
$crate::port::Pin<$crate::port::mode::Input, $rxpin>,
$crate::port::Pin<$crate::port::mode::Output, $txpin>,
> for $USART {
fn raw_init<CLOCK>(&mut self, baudrate: $crate::usart::Baudrate<CLOCK>) {
self.[<ubrr $n>].write(|w| unsafe { w.bits(baudrate.ubrr) });
self.[<ucsr $n a>].write(|w| w.[<u2x $n>]().bit(baudrate.u2x));
// Enable receiver and transmitter but leave interrupts disabled.
self.[<ucsr $n b>].write(|w| w
.[<txen $n>]().set_bit()
.[<rxen $n>]().set_bit()
);
// Set frame format to 8n1 for now. At some point, this should be made
// configurable, similar to what is done in other HALs.
self.[<ucsr $n c>].write(|w| w
.[<umsel $n>]().usart_async()
.[<ucsz $n>]().chr8()
.[<usbs $n>]().stop1()
.[<upm $n>]().disabled()
);
}
fn raw_deinit(&mut self) {
// Wait for any ongoing transfer to finish.
$crate::nb::block!(self.raw_flush()).ok();
self.[<ucsr $n b>].reset();
}
fn raw_flush(&mut self) -> $crate::nb::Result<(), core::convert::Infallible> {
if self.[<ucsr $n a>].read().[<udre $n>]().bit_is_clear() {
Err($crate::nb::Error::WouldBlock)
} else {
Ok(())
}
}
fn raw_write(&mut self, byte: u8) -> $crate::nb::Result<(), core::convert::Infallible> {
// Call flush to make sure the data-register is empty
self.raw_flush()?;
self.[<udr $n>].write(|w| unsafe { w.bits(byte) });
Ok(())
}
fn raw_read(&mut self) -> $crate::nb::Result<u8, core::convert::Infallible> {
if self.[<ucsr $n a>].read().[<rxc $n>]().bit_is_clear() {
return Err($crate::nb::Error::WouldBlock);
}
Ok(self.[<udr $n>].read().bits())
}
fn raw_interrupt(&mut self, event: $crate::usart::Event, state: bool) {
match event {
$crate::usart::Event::RxComplete =>
self.[<ucsr $n b>].modify(|_, w| w.[<rxcie $n>]().bit(state)),
$crate::usart::Event::TxComplete =>
self.[<ucsr $n b>].modify(|_, w| w.[<txcie $n>]().bit(state)),
$crate::usart::Event::DataRegisterEmpty =>
self.[<ucsr $n b>].modify(|_, w| w.[<udrie $n>]().bit(state)),
}
}
}
}
};
}