API referencestd/embedded

std/embedded/hal

Public declarations, types, methods, and source contracts for std/embedded/hal.

On this page

Library guide · API index and notation

This page is generated from the bundled library in this checkout. Signatures and adjacent source comments are reproduced below; the linked guide explains usage, storage, failures, and platform support.

import "std/embedded/hal"

Names used in signatures

Unqualified names denote this package’s types (including other source files in the same package), language built-ins, or generic parameters such as T. Qualified names use the import aliases below. These aliases belong to the library source; import a dependency yourself to use its alias in your program.

Alias Package Source file
cpu core/cpu hal.dodo
ptr core/ptr hal.dodo
time std/time hal.dodo

Error

Enum · Source

Bus and device failures shared by every driver and chip implementation. A single payload-free enum keeps drivers composable and comparable with ==.

pub enum Error {
    // The device did not respond or a flag did not change in time.
    Timeout,
    // No device acknowledged its address or a data byte.
    NoAcknowledge,
    // Electrical or protocol fault, including lost bus arbitration.
    Bus,
    // Data arrived faster than it was consumed.
    Overrun,
    // The peripheral is in use or not ready for this request.
    Busy,
    // An argument is outside what the device or bus accepts.
    InvalidInput,
    // The implementation does not support this operation.
    Unsupported
}

error_name

Function · Source

pub fn error_name(error: Error) -> &str from(static)

OutputPin

Interface · Source

A digital output, such as a pin driving an LED or a chip select.

pub interface OutputPin {
    fn set_high(&mut self)
    fn set_low(&mut self)
}

InputPin

Interface · Source

A digital input.

pub interface InputPin {
    fn is_high(&self) -> bool
}

Delay

Interface · Source

A busy-waiting delay source, such as a timer.

pub interface Delay {
    fn delay_us(&mut self, microseconds: u32)
}

Counter

Interface · Source

A free-running counter that keeps time, such as a chip’s microsecond timer. Drivers measure intervals and give up on stuck devices with it, through Deadline and Ticker below, without naming a chip.

pub interface Counter {
    // Microseconds since some fixed start, such as the chip's start; never
    // decreases.
    fn now_us(&self) -> u64
}

Alarm

Interface · Source

A one-shot alarm on a counter: it fires once when now_us() reaches the time it was given. Code polls fired, or a chip’s interrupt for the alarm runs a handler, which calls clear. Raising that interrupt is chip-specific, as for the RP2040’s and RP2350’s listen and irq; the protocol only sets times and reports them. An alarm is also a Counter.

pub interface Alarm {
    // Microseconds on the counter the alarm compares with.
    fn now_us(&self) -> u64
    // Fire once when now_us() reaches `time_us`, replacing any earlier time
    // and clearing an earlier firing. A time already reached fires at once.
    // InvalidInput if the time lies further ahead than the alarm reaches,
    // which each implementation states.
    fn schedule_at_us(&mut self, time_us: u64) -> void!Error
    // Disarm: a scheduled time no longer fires. An earlier firing stays
    // reported until `clear`.
    fn cancel(&mut self)
    // True once the scheduled time was reached, until `clear` or the next
    // schedule.
    fn fired(&self) -> bool
    // Acknowledge a firing. An interrupt handler has to, or the interrupt
    // stays raised.
    fn clear(&mut self)
}

TickCounter

Interface · Source

A free-running counter at a rate of its own, such as a timer that counts the system clock.

pub interface TickCounter {
    // Ticks per second.
    fn tick_hz(&self) -> u32
    // Ticks since some fixed start; never decreases.
    fn now_ticks(&self) -> u64
}

Compare

Interface · Source

A compare channel on a TickCounter: it fires once when the counter reaches the tick count it was given, as an Alarm does with microseconds, and is a TickCounter itself. Code polls fired, or with listen the channel raises its interrupt, whose handler calls clear.

pub interface Compare {
    fn tick_hz(&self) -> u32
    fn now_ticks(&self) -> u64
    // Fire once when now_ticks() reaches `ticks`, replacing any earlier
    // count and clearing an earlier firing. A count already reached fires
    // at once. InvalidInput if the count lies further ahead than the
    // channel reaches, which each implementation states.
    fn schedule_at_ticks(&mut self, ticks: u64) -> void!Error
    // Disarm: a scheduled count no longer fires. An earlier firing stays
    // reported until `clear`.
    fn cancel(&mut self)
    // True once the scheduled count was reached, until `clear` or the next
    // schedule.
    fn fired(&self) -> bool
    // Acknowledge a firing. An interrupt handler has to, or the interrupt
    // stays raised.
    fn clear(&mut self)
    // Raise the channel's interrupt while it has fired.
    fn listen(&mut self)
    // Stop raising it; `fired` still reports.
    fn ignore(&mut self)
}

PeriodicTimer

Interface · Source

A timer that elapses again and again at a fixed period: a hardware counter that wraps, or an alarm that re-arms itself. Each period ends a whole number of periods after the start, so periods do not drift however late a program looks at them, and a program that looks late learns how many ended meanwhile instead of losing them.

pub interface PeriodicTimer {
    fn tick_hz(&self) -> u32
    // Elapse every `period_ticks` ticks, the first time one period from
    // now, replacing a running period and forgetting periods not yet
    // polled. InvalidInput for 0 or a period the timer cannot make, which
    // each implementation states.
    fn start(&mut self, period_ticks: u64) -> void!Error
    // Stop: no more periods end, and those not yet polled are forgotten.
    fn cancel(&mut self)
    // Without waiting: how many periods ended since `start` or the last
    // call, 0 while none has. More than 1 means the program missed
    // periods: they ended while it was busy. Acknowledges the interrupt,
    // so a handler calls it; a handler may then see 0 for a period an
    // earlier call already counted.
    fn poll_periods(&mut self) -> u32
    // Raise the timer's interrupt when a period ends.
    fn listen(&mut self)
    fn ignore(&mut self)
}

InputCapture

Interface · Source

A capture channel: on each event at its input, such as an edge on a pin, the hardware latches the time on a counter, so the time is exact however late the program reads it.

pub interface InputCapture {
    fn tick_hz(&self) -> u32
    // Without waiting: true with `ticks` set to the time of the earliest
    // event not yet reported, a tick count at tick_hz, and false while
    // none waits. Overrun if events came faster than the channel holds
    // them, so some were lost; events that still wait are reported by the
    // next calls.
    fn poll_event(&mut self, ticks: &mut u64) -> bool!Error
    // Raise the channel's interrupt while an event waits.
    fn listen(&mut self)
    fn ignore(&mut self)
}

I2c

Interface · Source

An I2C bus controller. Addresses are 7-bit device addresses.

pub interface I2c {
    fn write(&mut self, address: u8, bytes: &[u8]) -> void!Error
    fn read(&mut self, address: u8, buffer: &mut[u8]) -> void!Error
    // Write `bytes`, then read `buffer.len` bytes without releasing the bus.
    fn write_read(&mut self, address: u8, bytes: &[u8], buffer: &mut[u8]) -> void!Error
}

Spi

Interface · Source

An SPI bus controller. Chip select is a separate output pin; see SpiDevice.

pub interface Spi {
    // Full-duplex exchange in place: each byte sent is replaced by the byte read.
    fn transfer(&mut self, bytes: &mut[u8]) -> void!Error
    fn write(&mut self, bytes: &[u8]) -> void!Error
}

PwmOutput

Interface · Source

A pulse-width modulated output: a square wave that is high for duty / max_duty() of each period, which dims an LED, sets a motor’s speed, or positions a servo. Its frequency is set when the output is created. A duty of 0 holds it low and max_duty() high.

pub interface PwmOutput {
    // The duty that holds the output high, at least 1.
    fn max_duty(&self) -> u16
    // InvalidInput if `duty` is above max_duty().
    fn set_duty(&mut self, duty: u16) -> void!Error
}

AnalogInput

Interface · Source

An input of an analog-to-digital converter. Each read converts the voltage once: 0 at ground, max_value() at the converter’s reference voltage, and proportionally in between.

pub interface AnalogInput {
    // The value read at the reference voltage, such as 4095 for a 12-bit
    // converter.
    fn max_value(&self) -> u16
    fn read(&mut self) -> u16!Error
}

FLASH_ERASED

Constant · Source

The value every byte of erased flash reads as.

pub const FLASH_ERASED: u8 = 0xFF

Flash

Interface · Source

Persistent memory that behaves like NOR flash: the program flash of a microcontroller, an external SPI flash chip, or a region of either. Erasing sets whole blocks to FLASH_ERASED; writing then programs bytes once, and a byte is only written again after its block is erased. Offsets count bytes from the device’s start. std/embedded/storage builds regions and a key-value store on any value with these methods, and std/embedded/hal/fake has one in memory for tests.

Every method reports InvalidInput for a range outside the device, or not aligned as below, and leaves the device unchanged. A device may refuse a range it protects, such as the flash holding the running program, with InvalidInput too.

pub interface Flash {
    // The device's size in bytes, a multiple of erase_size().
    fn capacity(&self) -> u32
    // The bytes one erase covers, a power of two such as 4096. Erases start
    // and end on multiples of it.
    fn erase_size(&self) -> u32
    // The bytes one write covers, a power of two up to 256: 1 when single
    // bytes can be written, more for devices that program whole words.
    // Writes start and end on multiples of it.
    fn write_size(&self) -> u32
    // Copy `buffer.len` bytes from `offset` into `buffer`; any offset and
    // length inside the device.
    fn read(&mut self, offset: u32, buffer: &mut[u8]) -> void!Error
    // Set the `length` bytes from `offset` to FLASH_ERASED.
    fn erase(&mut self, offset: u32, length: u32) -> void!Error
    // Program `bytes` at `offset`. Write only to erased bytes: what writing
    // over written ones does depends on the device, and some refuse or
    // corrupt it. An interrupted write or erase, as by a power cut, may leave
    // any content in the range it covered.
    fn write(&mut self, offset: u32, bytes: &[u8]) -> void!Error
}

Rtc

Interface · Source

A real-time clock: the time of day, kept by a counter that runs on while the processor sleeps, such as the RP2040’s RTC, the RP2350’s always-on timer, which also keeps counting through resets, or a clock chip on I2C with a backup battery.

Times are milliseconds since the Unix epoch, 1970-01-01 00:00:00 UTC, the count std/time’s Timestamp holds; rtc_now and rtc_set below convert them to and from a time.DateTime. A clock that counts whole seconds reports whole seconds, and resolution_ms says how long its steps are. A clock runs only once its time is set: until then, and again after it lost power, is_set is false and reading it reports Busy.

pub interface Rtc {
    // True while the clock runs from a time it was given.
    fn is_set(&mut self) -> bool!Error
    // The time, a multiple of resolution_ms(). Busy if it is not set.
    fn now_ms(&mut self) -> u64!Error
    // Set the time and start the clock; times between its steps round
    // down. InvalidInput if the clock cannot count that far.
    fn set_ms(&mut self, time_ms: u64) -> void!Error
    // How long one step of the clock is: 1 for a clock that counts
    // milliseconds, 1000 for one that counts seconds.
    fn resolution_ms(&self) -> u32
}

RtcAlarm

Interface · Source

A real-time clock’s alarm: it fires once, when the clock reaches the time it was given, like a counter’s Alarm. Chips raise an interrupt when it fires, and some wake from sleep for it; their clock types say how.

pub interface RtcAlarm {
    // Fire when now_ms() reaches `time_ms`, replacing an earlier alarm and
    // clearing an earlier firing. A time already reached fires at once.
    // Busy if the clock is not set; InvalidInput if the alarm cannot reach
    // that far ahead.
    fn set_alarm_ms(&mut self, time_ms: u64) -> void!Error
    // True once the alarm has fired, until clear_alarm.
    fn alarm_fired(&mut self) -> bool!Error
    // Disarm the alarm and acknowledge it if it fired. An interrupt handler
    // has to, or the interrupt stays raised.
    fn clear_alarm(&mut self) -> void!Error
}

I2cPoll

Interface · Source

An I2C bus controller whose transactions run while the program does other work. A transaction may be any length: an implementation moves as many bytes as its FIFO holds per poll and holds the bus, with SCL low, until the next poll continues it, which every I2C device accepts as clock stretching. Addresses are 7-bit device addresses, as for I2c.

pub interface I2cPoll {
    // Advance a write of `bytes` to the device at `address`, without
    // waiting: false while it runs, true once it has ended with a STOP. The
    // first call starts the transaction; later calls pass the same address
    // and bytes until it finishes. Errors as for I2c.write, after which the
    // transaction is over. InvalidInput for a call whose address or lengths
    // differ from the running transaction's, which keeps running.
    fn poll_write(&mut self, address: u8, bytes: &[u8]) -> bool!Error
    // Advance a read of `buffer.len` bytes, as for poll_write. The bytes
    // are all in `buffer` once it returns true; before that its contents
    // are unspecified.
    fn poll_read(&mut self, address: u8, buffer: &mut[u8]) -> bool!Error
    // Advance a write of `bytes`, a repeated START, and a read into
    // `buffer`, as one transaction, as I2c.write_read does.
    fn poll_write_read(&mut self, address: u8, bytes: &[u8], buffer: &mut[u8]) -> bool!Error
    // Abandon the running transaction, if any, ending it on the bus as
    // soon as the controller can, so the next poll starts a new one.
    fn cancel(&mut self)
}

SpiPoll

Interface · Source

An SPI bus controller whose transfers run while the program does other work. Chip select stays a separate pin; SpiDevice drives it around polled transfers too.

pub interface SpiPoll {
    // Advance a full-duplex exchange of `bytes` in place, without waiting:
    // false while frames remain, true once every byte sent has been replaced
    // by the byte read. Later calls pass the same slice until it finishes;
    // InvalidInput for one of another length. The slice's bytes past the
    // ones exchanged so far are still to be sent, so the caller must not
    // change them meanwhile.
    fn poll_transfer(&mut self, bytes: &mut[u8]) -> bool!Error
    // Advance a write of `bytes`, discarding what arrives, as for
    // poll_transfer.
    fn poll_write(&mut self, bytes: &[u8]) -> bool!Error
    // Abandon the running transfer, if any, once the frame on the wire is
    // complete, and discard what was received.
    fn cancel(&mut self)
}

I2cTargetEvent

Enum · Source

What happened on an I2C bus, from I2cTarget.poll.

pub enum I2cTargetEvent {
    // Nothing since the last poll.
    Idle,
    // The master wrote `count` bytes, now at the start of the buffer given
    // to `poll`. `start` is true when the first of them is the first byte
    // after the target's address, so it begins a new write, for example a
    // register number; the bytes of one poll never span two writes.
    Write(count: usize, start: bool),
    // The master reads and waits, with SCL held low, until `respond`
    // queues the bytes for it.
    Read,
    // A transaction addressed to the target ended with a STOP condition.
    Stop
}

I2cTarget

Interface · Source

An I2C target (slave): a device on a bus that another master addresses. The address is set when the target is created. The program polls for what the master did, in order: written bytes, a STOP, and reads, which wait, with SCL held low, until respond answers them, so a slow program delays the master but loses nothing.

match target.poll(&mut buffer)? { hal.I2cTargetEvent.Write(count, start) => { … } hal.I2cTargetEvent.Read => { target.respond(&reply)? } hal.I2cTargetEvent.Stop => {} hal.I2cTargetEvent.Idle => {} }

pub interface I2cTarget {
    // What the master did since the last poll, without waiting: first the
    // bytes it wrote, as many as fit `buffer`, then a STOP, then a read
    // waiting for `respond`. Bus for an electrical or protocol fault, and
    // Overrun if written bytes were lost.
    fn poll(&mut self, buffer: &mut[u8]) -> I2cTargetEvent!Error
    // Answer a Read with `bytes`, as many as the controller holds; returns
    // how many. The master reads them one by one and may stop early; if it
    // reads on, the next poll reports another Read. An empty `bytes`
    // answers one 0xFF, what the master would read from an idle bus, so it
    // is never left waiting.
    fn respond(&mut self, bytes: &[u8]) -> usize!Error
}

SpiTarget

Interface · Source

An SPI target (slave): another master drives the clock and the chip select, and the target shifts out what it queued while it shifts in what the master sends. Mode and frame size are set when it is created.

pub interface SpiTarget {
    // Queue `bytes` to send as the master clocks them, as many as there is
    // room for, without waiting; returns how many.
    fn queue(&mut self, bytes: &[u8]) -> usize!Error
    // The bytes the master sent since the last call, up to `buffer.len`,
    // without waiting; returns how many. Overrun if some were lost.
    fn read(&mut self, buffer: &mut[u8]) -> usize!Error
}

PulseCapture

Struct · Source

One measurement of a pulse train from a PwmInput: how long a period lasts and how long the signal is high in it, in nanoseconds, averaged over cycles whole periods. Hardware that timestamps edges measures single periods (cycles 1); hardware that counts edges over a window averages many. A measurement that saw no whole period, such as a line that did not change, has cycles 0: period_ns is then how long the line was watched and high_ns how long of that it was high, so duty still reads the share of time it was high (100% or 0% for a steady line).

pub struct PulseCapture {
    pub period_ns: u64
    pub high_ns: u64
    pub cycles: u32
}

PulseCapture.new

Function · Source

An empty measurement, for poll_capture to fill.

pub fn new() -> PulseCapture

PulseCapture.frequency_millihz

Function · Source

The signal’s frequency in millihertz, rounded; 0 for a steady line.

pub fn frequency_millihz(&self) -> u64

PulseCapture.frequency_hz

Function · Source

The signal’s frequency in hertz, rounded; 0 for a steady line.

pub fn frequency_hz(&self) -> u32

PulseCapture.duty

Function · Source

The high time as a share of the period, scaled to 0..max and rounded: duty(100) is a percentage, and a PwmOutput’s max_duty() reproduces the signal on an output.

pub fn duty(&self, max: u32) -> u32

PulseCapture.high_us

Function · Source

The high time in microseconds, rounded, as a servo or RC receiver’s pulse length is usually given. Saturates at the largest u32 (about 71 minutes).

pub fn high_us(&self) -> u32

PulseCapture.period_us

Function · Source

The period in microseconds, rounded, saturating as high_us does.

pub fn period_us(&self) -> u32

PwmInput

Interface · Source

An input that measures the pulses on a pin: the frequency and duty cycle of a PWM signal, a fan’s tachometer, or the pulse length of a servo signal. Like a PWM output it is configured when it is created, with how long one measurement may take. Measurements follow one another continuously.

pub interface PwmInput {
    // Without waiting: true with `capture` set to a measurement that
    // finished since the last call, false while none has. A program that
    // polls more slowly than measurements finish gets the latest. Overrun
    // if a measurement was lost, as when a counter overflowed; the next
    // measurement has then already begun.
    fn poll_capture(&mut self, capture: &mut PulseCapture) -> bool!Error
}

CAN_MAX_STANDARD_ID

Constant · Source

The largest identifiers: 11-bit standard and 29-bit extended.

pub const CAN_MAX_STANDARD_ID: u32 = 0x7FF

CAN_MAX_EXTENDED_ID

Constant · Source

pub const CAN_MAX_EXTENDED_ID: u32 = 0x1FFF_FFFF

CAN_MAX_DATA

Constant · Source

The most data bytes of a classic CAN frame and of a CAN FD frame.

pub const CAN_MAX_DATA: usize = 8

CAN_FD_MAX_DATA

Constant · Source

pub const CAN_FD_MAX_DATA: usize = 64

can_dlc_length

Function · Source

The data length of a CAN frame with data length code dlc, 0 to 15: codes up to 8 are lengths, and on CAN FD 9 to 15 mean 12, 16, 20, 24, 32, 48, and 64 bytes. A classic frame with a code above 8 carries 8.

pub fn can_dlc_length(dlc: u8, fd: bool) -> usize

can_length_dlc

Function · Source

The data length code for length bytes: InvalidInput above 64, or for a length CAN FD cannot carry exactly (it pads to 12, 16, 20, 24, 32, 48, or 64 bytes).

pub fn can_length_dlc(length: usize) -> u8!Error

CanFrame

Struct · Source

One CAN frame: an identifier, standard or extended, and up to 8 data bytes, or 64 on CAN FD, or a remote request for that many. The fields are checked as they are set, so every frame is one a controller can send. Frames are values a program keeps and reuses:

frame := hal.CanFrame.new() frame.set_data(0x123, false, &payload)? can.poll_send(&frame)? if can.poll_receive(&mut frame)? { … frame.id(), frame.bytes() … }

pub struct CanFrame {
    // Private implementation fields omitted.
}

CanFrame.new

Function · Source

A data frame with standard identifier 0 and no data, for a receive to fill or a set_* call to change.

pub fn new() -> CanFrame

CanFrame.standard

Function · Source

A classic data frame with standard identifier id and bytes as its data; see set_data.

pub fn standard(id: u32, bytes: &[u8]) -> CanFrame!Error

CanFrame.extended

Function · Source

A classic data frame with extended identifier id; see set_data.

pub fn extended(id: u32, bytes: &[u8]) -> CanFrame!Error

CanFrame.set_data

Function · Source

Make this a classic data frame: identifier id, extended or standard, with bytes as its data. InvalidInput for an identifier too large for its kind or more than CAN_MAX_DATA bytes; the frame is then unchanged.

pub fn set_data(&mut self, id: u32, extended: bool, bytes: &[u8]) -> void!Error

CanFrame.set_remote

Function · Source

Make this a remote frame, a request for length bytes of data frame id, 0 to CAN_MAX_DATA. Errors as for set_data.

pub fn set_remote(&mut self, id: u32, extended: bool, length: usize) -> void!Error

CanFrame.set_fd

Function · Source

Make this a CAN FD data frame with bytes as its data, sent with the faster data bit rate if bit_rate_switch. InvalidInput for a length can_length_dlc rejects, or as for set_data.

pub fn set_fd(&mut self, id: u32, extended: bool, bytes: &[u8], bit_rate_switch: bool) -> void!Error

CanFrame.id

Function · Source

pub fn id(&self) -> u32

CanFrame.is_extended

Function · Source

pub fn is_extended(&self) -> bool

CanFrame.is_remote

Function · Source

pub fn is_remote(&self) -> bool

CanFrame.is_fd

Function · Source

pub fn is_fd(&self) -> bool

CanFrame.bit_rate_switch

Function · Source

pub fn bit_rate_switch(&self) -> bool

CanFrame.len

Function · Source

The data length: of the data, or for a remote frame the length it requests.

pub fn len(&self) -> usize

CanFrame.dlc

Function · Source

The frame’s data length code.

pub fn dlc(&self) -> u8

CanFrame.bytes

Function · Source

The data bytes; empty for a remote frame.

pub fn bytes(&self) -> &[u8]

CanFrame.same

Function · Source

Whether this frame equals other: identifier and its kind, remote, FD, bit rate switch, length, and data.

pub fn same(&self, other: &CanFrame) -> bool

CanFrame.copy_from

Function · Source

Make this frame a copy of other.

pub fn copy_from(&mut self, other: &CanFrame)

CanFilter

Struct · Source

An acceptance filter: frames whose identifier bits under mask equal those of id, of the same kind (standard or extended), pass. A mask of 0 passes every frame of that kind. Controllers configure their hardware filters from these when they are created.

pub struct CanFilter {
    pub id: u32
    pub mask: u32
    pub extended: bool
}

CanFilter.exact

Function · Source

A filter that passes exactly identifier id.

pub fn exact(id: u32, extended: bool) -> CanFilter

CanFilter.all

Function · Source

A filter that passes every frame of one kind.

pub fn all(extended: bool) -> CanFilter

CanFilter.accepts

Function · Source

pub fn accepts(&self, frame: &CanFrame) -> bool

CanErrorState

Enum · Source

Where a CAN controller stands in the bus’s fault confinement, from its transmit and receive error counters. An error-active node signals the errors it sees; an error-passive one, after many errors, only listens for them; a bus-off node, after very many, takes no part until it recovers by seeing 128 runs of 11 recessive bits.

pub enum CanErrorState {
    Active,
    Passive,
    BusOff
}

Can

Interface · Source

A CAN controller on a bus. Bit rate, filters, and modes are set when it is created. Frames queue in the controller’s buffers in both directions, so both methods return at once.

pub interface Can {
    // Queue `frame` to send, without waiting: true once queued, false while
    // every transmit buffer is full. Unsupported for an FD frame on a
    // classic controller, Bus while the controller is bus-off.
    fn poll_send(&mut self, frame: &CanFrame) -> bool!Error
    // Without waiting: true with the oldest received frame in `frame`,
    // false while none waits. Overrun once if frames were lost since the
    // last call, before the frames that followed them.
    fn poll_receive(&mut self, frame: &mut CanFrame) -> bool!Error
    // Where the controller stands in fault confinement. Errors if the
    // controller cannot be asked, as one on a failing SPI bus.
    fn error_state(&mut self) -> CanErrorState!Error
}

CanBitTiming

Struct · Source

One bit time of a CAN controller in time quanta of prescaler input clock cycles: a sync segment of one quantum, segment1 (propagation plus phase segment 1) before the sample point, and segment2 after it. sync_jump is how far the controller may move the sample point to follow the transmitter. Controllers program their timing registers from it, each with its own encoding.

pub struct CanBitTiming {
    pub prescaler: u32
    pub segment1: u32
    pub segment2: u32
    pub sync_jump: u32
}

CanBitTiming.quanta

Function · Source

Time quanta per bit.

pub fn quanta(&self) -> u32

CanBitTiming.bitrate

Function · Source

The resulting bit rate from an input clock of clock_hz, rounded.

pub fn bitrate(&self, clock_hz: u32) -> u32

CanBitTiming.sample_point_permille

Function · Source

Where the sample point falls, in thousandths of the bit.

pub fn sample_point_permille(&self) -> u32

CanTimingLimits

Struct · Source

The ranges a controller’s timing registers accept, for can_timing.

pub struct CanTimingLimits {
    pub prescaler_min: u32
    pub prescaler_max: u32
    // Prescalers must be a multiple of this, such as 2 for controllers that
    // count the clock in pairs.
    pub prescaler_step: u32
    pub segment1_min: u32
    pub segment1_max: u32
    pub segment2_min: u32
    pub segment2_max: u32
    pub sync_jump_max: u32
}

can_timing

Function · Source

The bit timing for bitrate from an input clock of clock_hz, within limits, with the sample point closest to sample_point_permille (875, 87.5%, is CiA’s recommendation up to 800 kbit/s, 750 at 1 Mbit/s). The exact bit rate is preferred; among timings as exact, the sample point closest to the request, then the most quanta, which follow the bus most finely. The synchronization jump width is as wide as segment2 and the limits allow. InvalidInput if no timing reaches the bit rate within 0.5%.

pub fn can_timing(clock_hz: u32, bitrate: u32, sample_point_permille: u32, limits: &CanTimingLimits) -> CanBitTiming!Error

I2sFormat

Enum · Source

How an I2S stream frames its samples. The word select (LRCLK) line marks which channel a sample belongs to: low for the left channel in Philips framing, high for it in both justified framings.

pub enum I2sFormat {
    // The Philips I2S standard: word select low for the left channel, and
    // each sample starts, most significant bit first, one bit clock after
    // word select changes.
    Philips,
    // Word select high for the left channel, and each sample starts on the
    // bit clock where word select changes.
    LeftJustified,
    // Word select high for the left channel, and each sample ends on the
    // bit clock before word select changes, sign-extended above in a wider
    // slot.
    RightJustified
}

I2sOutput

Interface · Source

An I2S output: samples that a DAC or amplifier plays at the stream’s sample rate. The implementation keeps a queue and plays silence when it runs dry, so a program keeps the queue topped up from its poll.

pub interface I2sOutput {
    // Frames per second.
    fn sample_rate(&self) -> u32
    // Samples per frame: 1 or 2.
    fn channels(&self) -> u32
    // Queue samples to play, without waiting: as many whole frames as there
    // is room for; returns how many samples. InvalidInput for a slice that
    // is not whole frames.
    fn poll_write(&mut self, samples: &[i32]) -> usize!Error
}

I2sInput

Interface · Source

An I2S input: samples a microphone or ADC sends at the stream’s sample rate.

pub interface I2sInput {
    fn sample_rate(&self) -> u32
    fn channels(&self) -> u32
    // The samples received since the last call, as many whole frames as
    // fit `samples`, without waiting; returns how many samples. Overrun
    // once if samples were lost because they were not read in time.
    fn poll_read(&mut self, samples: &mut[i32]) -> usize!Error
}

Rng

Interface · Source

A source of random bytes: a chip’s hardware generator, which gathers entropy from physical noise such as an oscillator’s jitter, or a SoftRng seeded from one. random_u32, random_u64, and random_below build numbers from the bytes. Hardware generators differ in quality and speed: each chip package says whether its generator is fit for cryptographic keys. Where it is slow, seed a SoftRng from it once and draw from that.

pub interface Rng {
    // Fill `bytes` completely. Timeout if a hardware source stops
    // producing entropy, Bus if its health tests fail; on error the
    // contents of `bytes` are unspecified and must not be used.
    fn fill(&mut self, bytes: &mut[u8]) -> void!Error
}

Watchdog

Interface · Source

A watchdog: once started, it resets the chip unless the program feeds it again within its timeout, so firmware that hangs restarts instead of staying stuck. Its timeout is set when it is started; drivers and tasks that run long loops only feed it.

pub interface Watchdog {
    // Count down from the timeout again.
    fn feed(&mut self)
}

ResetReason

Enum · Source

Why the chip last started, as its watchdog reports it.

pub enum ResetReason {
    // Not the watchdog: power-up, the reset pin, a debugger, or the boot
    // ROM, for example after flashing.
    Other,
    // The watchdog was not fed before its timeout, or a panic halted the
    // program while the watchdog ran.
    Timeout,
    // The program reset the chip through the watchdog on purpose.
    Restart
}

reset_reason_name

Function · Source

pub fn reset_reason_name(reason: ResetReason) -> &str from(static)

Registers

Interface · Source

A peripheral’s 32-bit registers at byte offsets, for peripheral drivers.

pub interface Registers {
    fn read(&mut self, offset: usize) -> u32
    fn write(&mut self, offset: usize, value: u32)
}

DmaWidth

Enum · Source

The size of each element a DMA transfer moves.

pub enum DmaWidth {
    Byte,
    HalfWord,
    Word
}

DmaPace

Enum · Source

What paces a DMA transfer.

pub enum DmaPace {
    // Nothing: the channel moves elements as fast as the bus allows, as
    // for a copy between two buffers.
    Unpaced,
    // The peripheral register the transfer writes to: an element moves
    // whenever the peripheral has room, such as a UART's transmit FIFO.
    Destination,
    // The peripheral register the transfer reads from: an element moves
    // whenever the peripheral has one, such as a UART's receive FIFO.
    Source
}

DmaRing

Enum · Source

An address that wraps around a ring of 1 << bits bytes, aligned to its size, instead of running on: a receiver keeps writing into the same buffer, or a transmitter keeps reading from it.

pub enum DmaRing {
    None,
    Source(u32),
    Destination(u32)
}

DmaTransfer

Struct · Source

One DMA transfer: count elements of width from source to destination. An address that increments advances by one element after each; one that does not stays on a peripheral register.

pub struct DmaTransfer {
    pub source: usize
    pub destination: usize
    pub count: u32
    pub width: DmaWidth
    pub increment_source: bool
    pub increment_destination: bool
    pub pace: DmaPace
    pub ring: DmaRing
}

address_of

Function · Source

The address of bytes’ first byte, for a DMA transfer’s source or destination. Taking it is safe; the channel’s start is the unsafe step.

pub fn address_of(bytes: &[u8]) -> usize

DmaChannel

Interface · Source

A DMA channel: moves data between memory and peripherals while the processor does other work. Peripheral drivers start transfers through it and chip packages implement it, so drivers that use DMA name no chip. Drivers keep their buffers borrowed until the transfer is done or aborted, as starting one is unsafe; applications use their safe methods.

pub interface DmaChannel {
    // Start `transfer`. InvalidInput if the channel cannot pace by the
    // peripheral named, wrap a ring of that size, or move that many
    // elements; Busy if a transfer is still running.
    // SAFETY: the memory the transfer reads and writes must stay valid,
    // and nothing else may access the memory it writes, until it is done or
    // aborted.
    unsafe fn start(&mut self, transfer: DmaTransfer) -> void!Error
    // True while a transfer is running.
    fn is_busy(&mut self) -> bool
    // The elements the running transfer has yet to move: 0 once it is done.
    fn remaining(&mut self) -> u32
    // The largest count a transfer may have.
    fn max_count(&mut self) -> u32
    // Stop the running transfer, if any, and wait until the channel no
    // longer touches memory.
    fn abort(&mut self)
    // Bus if a transfer since the last call hit a bus error, such as an
    // address with nothing behind it, which stops it.
    fn take_error(&mut self) -> void!Error
}

DmaBuffer

Interface · Source

A transfer between a buffer and a peripheral that runs while the program does other work, usually by DMA, in one direction fixed when the session is created. The session holds the buffer and lends it out only between transfers, so the program never touches memory a transfer is moving:

transfer.buffer()?[0] = command // fill it, then: transfer.start(count)? … other work, or return Pending from a task … if transfer.poll_finish()? { … read transfer.buffer()? … }

DmaStream implements it over any DmaChannel; peripheral drivers build their DMA sessions on it, and fake.DmaBuffer stands in for one in tests.

pub interface DmaBuffer {
    // The buffer, to fill before a transfer or read after one. Busy while
    // a transfer runs.
    fn buffer(&mut self) -> &mut[u8]!Error
    // The buffer's length in bytes, the most a transfer moves.
    fn capacity(&self) -> usize
    // Start moving buffer[..count], and return at once. InvalidInput for
    // 0, more than the capacity, or a count the session cannot move (not a
    // whole number of its elements); Busy while a transfer runs.
    fn start(&mut self, count: usize) -> void!Error
    // Without waiting: true once no transfer runs, false while one does.
    // Bus if the transfer hit a bus error, Overrun if the peripheral lost
    // data; either way it is over.
    fn poll_finish(&mut self) -> bool!Error
    // Stop the running transfer, if any; the peripheral saw only part of
    // it.
    fn abort(&mut self)
}

SpiDma

Interface · Source

An SPI bus whose transfers run by DMA over a buffer the session holds, as DmaBuffer does, in both directions at once. A display driver streams a frame with start_write; a flash driver reads a page with start_transfer.

pub interface SpiDma {
    fn buffer(&mut self) -> &mut[u8]!Error
    fn capacity(&self) -> usize
    // Start sending buffer[..count] and replacing each byte with the one
    // received meanwhile. Errors as for DmaBuffer.start.
    fn start_transfer(&mut self, count: usize) -> void!Error
    // Start sending buffer[..count], discarding what arrives; the buffer
    // stays as it is.
    fn start_write(&mut self, count: usize) -> void!Error
    fn poll_finish(&mut self) -> bool!Error
    fn abort(&mut self)
}

dma_width_bytes

Function · Source

The number of bytes in one element of width.

pub fn dma_width_bytes(width: &DmaWidth) -> usize

DmaStream

Struct · Source

A buffer moved to or from one peripheral data register by a DMA channel: the part every DMA-backed peripheral driver shares, written once against DmaChannel so it works with any chip’s channels. It holds the channel and the buffer until it is dropped and implements DmaBuffer. Each transfer moves elements of the stream’s width between the buffer, advancing, and the register, staying, paced by the peripheral’s data request.

The peripheral driver around it turns the peripheral’s DMA request on before start and off after the transfer, and adds its own errors, as pl022.DmaBus does for SPI. Dropping a stream aborts a running transfer.

pub struct DmaStream: DmaBuffer {
    // Private implementation fields omitted.
}

DmaStream.transmit

Function · Source

A stream that sends buffer to the peripheral register at register, its address as the channel sees it, width at a time, whenever the peripheral asks for data. InvalidInput for an empty buffer or one not aligned to the width; Busy if the channel is running.

pub fn transmit(channel: &mut dyn DmaChannel, buffer: &mut[u8], register: usize, width: DmaWidth) -> DmaStream!Error from(channel, buffer)

DmaStream.receive

Function · Source

A stream that fills buffer from the peripheral register at register whenever the peripheral has data; errors as for transmit.

pub fn receive(channel: &mut dyn DmaChannel, buffer: &mut[u8], register: usize, width: DmaWidth) -> DmaStream!Error from(channel, buffer)

DmaStream.buffer

Function · Source

The buffer, between transfers; Busy while one runs.

pub fn buffer(&mut self) -> &mut[u8]!Error from(self)

DmaStream.capacity

Function · Source

pub fn capacity(&self) -> usize

DmaStream.is_receive

Function · Source

True for a stream that fills its buffer from the peripheral.

pub fn is_receive(&self) -> bool

DmaStream.register

Function · Source

The peripheral register the stream moves data to or from.

pub fn register(&self) -> usize

DmaStream.start

Function · Source

Start moving buffer[..count]; see DmaBuffer.start. InvalidInput also for a count that is not a whole number of elements or more elements than the channel moves at once.

pub fn start(&mut self, count: usize) -> void!Error

DmaStream.is_busy

Function · Source

True while a transfer runs.

pub fn is_busy(&mut self) -> bool

DmaStream.remaining

Function · Source

The bytes the running transfer has yet to move: 0 once it is done.

pub fn remaining(&mut self) -> usize

DmaStream.poll_finish

Function · Source

See DmaBuffer.poll_finish.

pub fn poll_finish(&mut self) -> bool!Error

DmaStream.finish

Function · Source

Wait until the running transfer, if any, is done; errors as for poll_finish.

pub fn finish(&mut self) -> void!Error

DmaStream.abort

Function · Source

Stop the running transfer, if any.

pub fn abort(&mut self)

dma_copy

Function · Source

Copy source into destination with a DMA channel and wait until it is done: unpaced, in words where both addresses and the length allow. InvalidInput if the lengths differ or are too many elements for the channel, Busy if it is running, Bus for a bus error.

pub fn dma_copy<C: DmaChannel>(channel: &mut C, destination: &mut[u8], source: &[u8]) -> void!Error

I2C_STANDARD_HZ

Constant · Source

Common I2C bus frequencies: standard mode, fast mode, and fast mode plus. Every device supports standard mode; most sensors also fast mode.

pub const I2C_STANDARD_HZ: u32 = 100_000

I2C_FAST_HZ

Constant · Source

pub const I2C_FAST_HZ: u32 = 400_000

I2C_FAST_PLUS_HZ

Constant · Source

pub const I2C_FAST_PLUS_HZ: u32 = 1_000_000

SpiMode

Enum · Source

SPI clock polarity and phase, as numbered in device datasheets. Mode 0, clock idle low and data sampled on the rising edge, is the most common.

pub enum SpiMode {
    // Clock idles low; data is sampled on the rising (first) edge.
    Mode0,
    // Clock idles low; data is sampled on the falling (second) edge.
    Mode1,
    // Clock idles high; data is sampled on the falling (first) edge.
    Mode2,
    // Clock idles high; data is sampled on the rising (second) edge.
    Mode3
}

encode

Function · Source

value moved into the position of mask. Traps if it does not fit, so a wrong value never silently changes a neighbouring field.

pub fn encode<T>(mask: T, value: T) -> T

decode

Function · Source

The field mask extracted from a whole register value.

pub fn decode<T>(mask: T, register: T) -> T

Reg

Struct · Source

One memory-mapped register holding T (u8, u16, u32, or u64 up to the target pointer width). Every access is a single volatile load or store of T; the compiler never merges, removes, or splits it.

A Reg is move-only. Owning it is the permission to touch that register, so build peripheral structs from Reg fields and hand them out once.

pub struct Reg<T> {
    // Private implementation fields omitted.
}

Reg.at

Function · Source

SAFETY: address must be a valid, T-aligned device register for this target, accessible with T-sized loads and stores, and no other handle or code may access it in a conflicting way while this handle exists.

pub unsafe fn at(address: usize) -> Reg<T>

Requires an unsafe context. Follow the source safety preconditions and the linked guide before calling this API.

Reg.address

Function · Source

pub fn address(&self) -> usize

Reg.read

Function · Source

pub fn read(&self) -> T

Reg.write

Function · Source

pub fn write(&mut self, value: T)

Reg.modify

Function · Source

Read-modify-write: clear the clear bits, then set the set bits. Not atomic with respect to interrupts; wrap shared registers in a Critical section or use the chip’s set/clear aliases instead.

pub fn modify(&mut self, clear: T, set: T)

Reg.set_bits

Function · Source

pub fn set_bits(&mut self, mask: T)

Reg.clear_bits

Function · Source

pub fn clear_bits(&mut self, mask: T)

Reg.any

Function · Source

True when any bit in mask reads as one.

pub fn any(&self, mask: T) -> bool

Reg.get

Function · Source

The value of the field mask.

pub fn get(&self, mask: T) -> T

Reg.set

Function · Source

Read-modify-write of the field mask. Traps if value does not fit.

pub fn set(&mut self, mask: T, value: T)

Reg.wait_set

Function · Source

Poll until every bit in mask reads one, at most attempts reads. Use it for ready flags; a stuck device then yields Error.Timeout instead of hanging forever.

pub fn wait_set(&self, mask: T, attempts: u32) -> void!Error

Reg.wait_clear

Function · Source

Poll until every bit in mask reads zero, at most attempts reads.

pub fn wait_clear(&self, mask: T, attempts: u32) -> void!Error

RegisterBlock

Struct · Source

A peripheral’s 32-bit registers at byte offsets from one base address. Implements Registers, so drivers in std/embedded/peripheral reach the hardware through it. Every access is one volatile 32-bit load or store, like Reg<u32>. Move-only: owning it is the permission to use the whole block.

pub struct RegisterBlock: Registers {
    // Private implementation fields omitted.
}

RegisterBlock.at

Function · Source

SAFETY: base must be the 4-aligned base address of one peripheral on this target, every offset its driver uses must be a valid 32-bit register of it, and no other handle or code may access those registers in a conflicting way while this handle exists.

pub unsafe fn at(base: usize) -> RegisterBlock

Requires an unsafe context. Follow the source safety preconditions and the linked guide before calling this API.

RegisterBlock.base

Function · Source

pub fn base(&self) -> usize

RegisterBlock.read

Function · Source

pub fn read(&mut self, offset: usize) -> u32

RegisterBlock.write

Function · Source

pub fn write(&mut self, offset: usize, value: u32)

Critical

Struct · Source

Masks interrupts on the current core while it is alive and restores the previous state when dropped, so sections nest correctly:

section := hal.Critical.enter() unsafe { TICKS += 1 } core.drop(section)

Bare-metal Cortex-M and RISC-V mask interrupts; hosted OS targets have no interrupts visible to programs and make this a no-op. It never excludes other threads or cores; use std/sync for those.

pub struct Critical {
    // Private implementation fields omitted.
}

Critical.enter

Function · Source

pub fn enter() -> Critical

Handler

Struct · Source

A slot for an interrupt handler registered at run time. The vector-table entry point stays an extern "C" function with the interrupt’s name and calls run, so firmware can switch handlers without rebuilding:

static mut TIMER: hal.Handler = hal.NO_HANDLER

extern “C” fn TIMER_IRQ_0() { unsafe { TIMER.run() } }

section := hal.Critical.enter() unsafe { TIMER.set(on_tick) } core.drop(section)

A handler is a plain function pointer, so it captures no locals and stays valid for the whole program; it keeps state in static mut storage. Change a shared slot inside a critical section, which also orders the store before the next interrupt on this core.

pub struct Handler {
    // Private implementation fields omitted.
}

Handler.set

Function · Source

pub fn set(&mut self, function: fn())

Handler.clear

Function · Source

pub fn clear(&mut self)

Handler.is_set

Function · Source

pub fn is_set(&self) -> bool

Handler.run

Function · Source

Calls the registered handler; false when the slot is empty.

pub fn run(&self) -> bool

NO_HANDLER

Constant · Source

An empty handler slot, for initializing static mut storage.

pub const NO_HANDLER: Handler = Handler { function: none }

write_pin

Function · Source

Drive an output pin to high.

pub fn write_pin<P: OutputPin>(pin: &mut P, high: bool)

delay_ms

Function · Source

pub fn delay_ms<D: Delay>(delay: &mut D, milliseconds: u32)

elapsed_us

Function · Source

The microseconds a counter has run since since_us, one of its own now_us times; 0 for a time still ahead.

pub fn elapsed_us<C: Counter>(counter: &C, since_us: u64) -> u64

wait_until

Function · Source

Busy-wait until a counter reaches time_us.

pub fn wait_until<C: Counter>(counter: &C, time_us: u64)

schedule_in_us

Function · Source

Fire an alarm microseconds from now. InvalidInput if that lies beyond the alarm’s reach.

pub fn schedule_in_us<A: Alarm>(alarm: &mut A, microseconds: u64) -> void!Error

wait_for_alarm

Function · Source

Busy-wait until an alarm fires, then clear it.

pub fn wait_for_alarm<A: Alarm>(alarm: &mut A)

Deadline

Struct · Source

A time on a counter by which something must have happened, for drivers that poll a device and give up on one that is stuck:

deadline := hal.Deadline.after(timer, 10_000) for !ready(bus)? { if deadline.passed(timer) { return err(hal.Error.Timeout) } }

It holds only the time, so it never borrows the counter, and the same counter can delay between checks.

pub struct Deadline {
    // Private implementation fields omitted.
}

Deadline.at

Function · Source

The deadline at time_us, a now_us time of the counter it is checked against.

pub fn at(time_us: u64) -> Deadline

Deadline.after

Function · Source

The deadline microseconds from the counter’s present time.

pub fn after<C: Counter>(counter: &C, microseconds: u64) -> Deadline

Deadline.time_us

Function · Source

pub fn time_us(&self) -> u64

Deadline.passed

Function · Source

True once the counter has reached the deadline.

pub fn passed<C: Counter>(&self, counter: &C) -> bool

Deadline.remaining_us

Function · Source

The microseconds left until the deadline; 0 once it has passed.

pub fn remaining_us<C: Counter>(&self, counter: &C) -> u64

Deadline.wait

Function · Source

Busy-wait until the counter reaches the deadline.

pub fn wait<C: Counter>(&self, counter: &C)

Ticker

Struct · Source

Ticks at a fixed period on a counter, for work that repeats, such as sampling a sensor every 10 ms. Each tick falls a whole number of periods after the start, so the ticks do not drift however late they are seen. A tick missed entirely, because the program was busy for longer than a period, is skipped rather than delivered late.

pub struct Ticker {
    // Private implementation fields omitted.
}

Ticker.start

Function · Source

Ticks every period_us, at least 1, the first one period from now.

pub fn start<C: Counter>(counter: &C, period_us: u64) -> Ticker

Ticker.period_us

Function · Source

pub fn period_us(&self) -> u64

Ticker.next_us

Function · Source

The counter time of the next tick.

pub fn next_us(&self) -> u64

Ticker.ready

Function · Source

True once per tick: when the counter has reached the next tick, which then moves on to the first tick still ahead.

pub fn ready<C: Counter>(&mut self, counter: &C) -> bool

Ticker.wait

Function · Source

Busy-wait for the next tick.

pub fn wait<C: Counter>(&mut self, counter: &C)

ticks_to_us

Function · Source

The microseconds ticks at tick_hz last, rounded down. A rate of 0 gives 0.

pub fn ticks_to_us(ticks: u64, tick_hz: u32) -> u64

ticks_to_ns

Function · Source

The nanoseconds ticks at tick_hz last, rounded down, saturating at the largest u64 (584 years).

pub fn ticks_to_ns(ticks: u64, tick_hz: u32) -> u64

us_to_ticks

Function · Source

The ticks at tick_hz in microseconds, rounded up, so that waiting that many ticks lasts at least that long.

pub fn us_to_ticks(microseconds: u64, tick_hz: u32) -> u64

elapsed_ticks

Function · Source

The ticks a tick counter has run since since, one of its own now_ticks counts; 0 for a count still ahead.

pub fn elapsed_ticks<C: TickCounter>(counter: &C, since: u64) -> u64

schedule_in_ticks

Function · Source

Fire a compare channel ticks from now. InvalidInput if that lies beyond the channel’s reach.

pub fn schedule_in_ticks<C: Compare>(channel: &mut C, ticks: u64) -> void!Error

wait_for_compare

Function · Source

Busy-wait until a compare channel fires, then clear it.

pub fn wait_for_compare<C: Compare>(channel: &mut C)

start_periodic_us

Function · Source

Start a periodic timer with a period of period_us. InvalidInput unless the period is a whole number of the timer’s ticks, since a rounded period would drift, or if the timer cannot make it.

pub fn start_periodic_us<P: PeriodicTimer>(timer: &mut P, period_us: u64) -> void!Error

wait_periods

Function · Source

Busy-wait until at least one period of a running periodic timer ends, and return how many did, as poll_periods counts them. Waits forever on a timer that is not running.

pub fn wait_periods<P: PeriodicTimer>(timer: &mut P) -> u32

capture_ticks

Function · Source

Wait for the next event on a capture channel, polling at most polls times (NO_POLL_LIMIT for no limit), and return its tick count; Timeout after that, and errors as for poll_event.

pub fn capture_ticks<C: InputCapture>(input: &mut C, polls: u32) -> u64!Error

set_duty_fraction

Function · Source

Set a PWM output high for numerator / denominator of each period, rounded to the nearest step the output has. InvalidInput if the denominator is zero or below the numerator.

pub fn set_duty_fraction<P: PwmOutput>(output: &mut P, numerator: u32, denominator: u32) -> void!Error

set_duty_percent

Function · Source

Set a PWM output high for percent of each period, 0 to 100.

pub fn set_duty_percent<P: PwmOutput>(output: &mut P, percent: u32) -> void!Error

set_pulse_us

Function · Source

Make a PWM output’s pulses pulse_us long, for an output whose period is period_us: a hobby servo, for example, expects a 50 Hz output (a period of 20_000 us) and turns from one end to the other as the pulse goes from about 1000 to 2000 us. InvalidInput if the pulse is longer than the period.

pub fn set_pulse_us<P: PwmOutput>(output: &mut P, pulse_us: u32, period_us: u32) -> void!Error

read_millivolts

Function · Source

One read of an analog input as a voltage in millivolts, for a converter whose reference is reference_mv, such as 3300 for a 3.3 V supply.

pub fn read_millivolts<A: AnalogInput>(input: &mut A, reference_mv: u32) -> u32!Error

random_u32

Function · Source

A uniformly distributed u32 from rng.

pub fn random_u32<R: Rng>(rng: &mut R) -> u32!Error

random_u64

Function · Source

A uniformly distributed u64 from rng.

pub fn random_u64<R: Rng>(rng: &mut R) -> u64!Error

random_below

Function · Source

A uniformly distributed value in 0..bound from rng, without the bias a plain random_u32(rng)? % bound has: a die roll is random_below(rng, 6)? + 1. InvalidInput if bound is zero.

pub fn random_below<R: Rng>(rng: &mut R, bound: u32) -> u32!Error

SoftRng

Struct · Source

A fast software generator, xoshiro128**, for when a hardware generator is slow or absent: seed it once from the chip’s generator with from_rng, then draw as many numbers as needed at a few cycles each. Implements Rng. Its output is statistically uniform but predictable to anyone who learns its 128-bit state, so it is not for cryptographic keys. new with a fixed seed repeats the same sequence, for tests and reproducible simulations.

pub struct SoftRng: Rng {
    // Private implementation fields omitted.
}

SoftRng.new

Function · Source

A generator whose state is expanded from seed.

pub fn new(seed: u64) -> SoftRng

SoftRng.from_rng

Function · Source

A generator whose 128-bit state is read from source, such as a board’s rng. Fails as source.fill does.

pub fn from_rng<S: Rng>(source: &mut S) -> SoftRng!Error

SoftRng.next_u32

Function · Source

The next uniformly distributed u32. Never fails.

pub fn next_u32(&mut self) -> u32

SoftRng.fill

Function · Source

Fill bytes from the generator. Never fails.

pub fn fill(&mut self, bytes: &mut[u8]) -> void!Error

date_time_of_ms

Function · Source

time_ms, milliseconds since the Unix epoch, as a UTC date and time.

pub fn date_time_of_ms(time_ms: u64) -> time.DateTime!Error

ms_of_date_time

Function · Source

value as milliseconds since the Unix epoch, rounded down; InvalidInput before the epoch.

pub fn ms_of_date_time(value: &time.DateTime) -> u64!Error

rtc_now

Function · Source

The clock’s time as a UTC date and time. Busy if it is not set.

pub fn rtc_now<R: Rtc>(clock: &mut R) -> time.DateTime!Error

rtc_set

Function · Source

Set the clock to value, a UTC date and time. InvalidInput before the epoch or past what the clock counts to.

pub fn rtc_set<R: Rtc>(clock: &mut R, value: &time.DateTime) -> void!Error

rtc_alarm_at

Function · Source

Fire the clock’s alarm at value, a UTC date and time.

pub fn rtc_alarm_at<R: RtcAlarm>(clock: &mut R, value: &time.DateTime) -> void!Error

rtc_alarm_in

Function · Source

Fire the clock’s alarm milliseconds after now_ms(); 0 fires at once. A clock that counts seconds reports the start of the current second, so its alarm fires up to a second early.

pub fn rtc_alarm_in<R: Rtc + RtcAlarm>(clock: &mut R, milliseconds: u64) -> void!Error

read_register

Function · Source

pub fn read_register<B: I2c>(bus: &mut B, address: u8, register: u8) -> u8!Error

read_registers

Function · Source

pub fn read_registers<B: I2c>(bus: &mut B, address: u8, first: u8, buffer: &mut[u8]) -> void!Error

write_register

Function · Source

pub fn write_register<B: I2c>(bus: &mut B, address: u8, register: u8, value: u8) -> void!Error

SpiDevice

Struct · Source

One device on a shared SPI bus, selected by an active-low chip-select pin. The device owns its pin; the bus is passed to each transaction, so several devices share one bus and the borrow checker keeps transactions apart.

The poll_* methods run the same transactions on a SpiPoll bus without waiting: the device stays selected from the first poll until the transaction finishes, fails, or is cancelled, and other devices must not use the bus meanwhile.

pub struct SpiDevice<P: OutputPin> {
    // Private implementation fields omitted.
}

SpiDevice.new

Function · Source

Takes the chip-select pin and deselects the device.

pub fn new(select: P) -> SpiDevice<P>

SpiDevice.poll_transfer

Function · Source

Advance a full-duplex exchange in place with the device selected; see SpiPoll.poll_transfer.

pub fn poll_transfer<B: SpiPoll>(&mut self, bus: &mut B, bytes: &mut[u8]) -> bool!Error

SpiDevice.poll_write

Function · Source

Advance a write with the device selected; see SpiPoll.poll_write.

pub fn poll_write<B: SpiPoll>(&mut self, bus: &mut B, bytes: &[u8]) -> bool!Error

SpiDevice.poll_write_read

Function · Source

Advance a write of command and then a read of buffer.len bytes in the same selection, as write_read does.

pub fn poll_write_read<B: SpiPoll>(&mut self, bus: &mut B, command: &[u8], buffer: &mut[u8]) -> bool!Error

SpiDevice.cancel

Function · Source

Abandon a polled transaction, if one runs, and deselect the device.

pub fn cancel<B: SpiPoll>(&mut self, bus: &mut B)

SpiDevice.is_busy

Function · Source

True while a polled transaction runs.

pub fn is_busy(&self) -> bool

SpiDevice.transfer

Function · Source

Full-duplex exchange in place with the device selected.

pub fn transfer<B: Spi>(&mut self, bus: &mut B, bytes: &mut[u8]) -> void!Error

SpiDevice.write

Function · Source

pub fn write<B: Spi>(&mut self, bus: &mut B, bytes: &[u8]) -> void!Error

SpiDevice.write_read

Function · Source

Write command, then read buffer.len bytes in the same selection.

pub fn write_read<B: Spi>(&mut self, bus: &mut B, command: &[u8], buffer: &mut[u8]) -> void!Error

SpiDevice.release

Function · Source

Give back the chip-select pin.

pub fn release(self) -> P

DEFAULT_POLL_LIMIT

Constant · Source

Polls a blocking adapter or helper makes before it gives up with Timeout: far more than any transaction a device answers takes (a 256-byte I2C transfer at 100 kHz is about 25 ms, tens of thousands of polls), so only a stuck bus reaches it. NO_POLL_LIMIT waits as long as it takes.

pub const DEFAULT_POLL_LIMIT: u32 = 50_000_000

NO_POLL_LIMIT

Constant · Source

pub const NO_POLL_LIMIT: u32 = 0

BlockingI2c

Struct · Source

An I2C bus with the blocking I2c protocol over any I2cPoll implementation: each transaction polls until it finishes, and after DEFAULT_POLL_LIMIT polls (or set_poll_limit’s) cancels it and reports Timeout. A controller that implements only the polling form thereby serves every blocking driver too.

pub struct BlockingI2c<B: I2cPoll>: I2c {
    // Private implementation fields omitted.
}

BlockingI2c.new

Function · Source

pub fn new(bus: B) -> BlockingI2c<B>

BlockingI2c.set_poll_limit

Function · Source

Give up after polls polls per transaction; NO_POLL_LIMIT never does.

pub fn set_poll_limit(&mut self, polls: u32)

BlockingI2c.write

Function · Source

pub fn write(&mut self, address: u8, bytes: &[u8]) -> void!Error

BlockingI2c.read

Function · Source

pub fn read(&mut self, address: u8, buffer: &mut[u8]) -> void!Error

BlockingI2c.write_read

Function · Source

pub fn write_read(&mut self, address: u8, bytes: &[u8], buffer: &mut[u8]) -> void!Error

BlockingI2c.bus

Function · Source

The bus, for its own methods.

pub fn bus(&mut self) -> &mut B

BlockingI2c.release

Function · Source

pub fn release(self) -> B

BlockingSpi

Struct · Source

An SPI bus with the blocking Spi protocol over any SpiPoll implementation, as BlockingI2c is for I2C.

pub struct BlockingSpi<B: SpiPoll>: Spi {
    // Private implementation fields omitted.
}

BlockingSpi.new

Function · Source

pub fn new(bus: B) -> BlockingSpi<B>

BlockingSpi.set_poll_limit

Function · Source

pub fn set_poll_limit(&mut self, polls: u32)

BlockingSpi.transfer

Function · Source

pub fn transfer(&mut self, bytes: &mut[u8]) -> void!Error

BlockingSpi.write

Function · Source

pub fn write(&mut self, bytes: &[u8]) -> void!Error

BlockingSpi.bus

Function · Source

pub fn bus(&mut self) -> &mut B

BlockingSpi.release

Function · Source

pub fn release(self) -> B

finish_transfer

Function · Source

Wait for a DMA buffer transfer to finish; errors as for poll_finish.

pub fn finish_transfer<T: DmaBuffer>(transfer: &mut T) -> void!Error

capture

Function · Source

Wait for the next measurement of a PWM input, polling at most polls times (NO_POLL_LIMIT for no limit); Timeout after that.

pub fn capture<P: PwmInput>(input: &mut P, polls: u32) -> PulseCapture!Error

send_frame

Function · Source

Send a CAN frame, waiting for a free transmit buffer for at most polls polls (NO_POLL_LIMIT for no limit); Timeout after that, as on a bus where no other node acknowledges frames, so none ever leaves.

pub fn send_frame<C: Can>(can: &mut C, frame: &CanFrame, polls: u32) -> void!Error

receive_frame

Function · Source

Wait for a CAN frame, for at most polls polls; Timeout after that.

pub fn receive_frame<C: Can>(can: &mut C, frame: &mut CanFrame, polls: u32) -> void!Error

write_samples

Function · Source

Queue all of samples on an I2S output, waiting for room; Timeout after polls polls without progress (NO_POLL_LIMIT for no limit).

pub fn write_samples<O: I2sOutput>(output: &mut O, samples: &[i32], polls: u32) -> void!Error

read_samples

Function · Source

Fill all of samples from an I2S input, waiting for them; Timeout after polls polls without progress.

pub fn read_samples<I: I2sInput>(input: &mut I, samples: &mut[i32], polls: u32) -> void!Error

sample_from_i16

Function · Source

A 16-bit sample as an I2S sample, and an I2S sample’s top 16 bits.

pub fn sample_from_i16(value: i16) -> i32

sample_to_i16

Function · Source

pub fn sample_to_i16(sample: i32) -> i16

Search every guide, reference page, and API declaration.