Simvik

Peripherals that can be taken once

Give out a peripheral's handle only once, as Rust's Peripherals::take() does. An easy embedded C problem (Rust for embedded), run and graded in the browser.

easy · Rust for embedded · ownership · singletons · rust

In embedded Rust, Peripherals::take() returns the device's peripherals the first time and None after that, so two parts of the program can never both think they own the UART. C does not enforce this, but the same discipline can be written by hand.

Write uart_take(): the first call returns a pointer to the one uart_t instance (named "USART1", with reg pointing at fake_uart_reg); every later call returns NULL until uart_release(u) gives it back. uart_release ignores pointers that are not the instance or not currently taken, and returns whether it accepted the release.

Starter code

static uart_t uart1 = { "USART1", &fake_uart_reg };

uart_t *uart_take(void) {
  return &uart1;
}

bool uart_release(uart_t *u) {
  (void)u;
  return true;
}

Example tests

Only one owner

uart_t *a = uart_take();
uart_t *b = uart_take();
printf("%s %s\n", a ? a->name : "NULL", b ? b->name : "NULL");

Expected output:

USART1 NULL

Learn it first

  • Rust for embedded · Ownership and borrowing, no_std, embedded-hal, RTIC and Embassy.