Epicardium API

This page details all available Epicardium API functions. All these functions are defined in

#include "epicardium.h"

Interrupts

Next to API calls, Epicardium API also has an interrupt mechanism to serve the other direction. These interrupts can be enabled/disabled (masked/unmasked) using epic_interrupt_enable() and epic_interrupt_disable().

These interrupts work similar to hardware interrupts: You will only get a single interrupt, even if multiple events occured since the ISR last ran (this behavior is new since version 1.16).

Warning

Never attempt to call the API from inside an ISR. This might trigger an assertion if a call is already being made from thread context. We plan to lift this restriction at some point, but for the time being, this is how it is.

int epic_interrupt_enable(api_int_id_t int_id)

Enable/unmask an API interrupt.

Parameters
  • int_id – The interrupt to be enabled

int epic_interrupt_disable(api_int_id_t int_id)

Disable/mask an API interrupt.

Parameters
  • int_id – The interrupt to be disabled

int epic_interrupt_is_enabled(api_int_id_t int_id, bool * enabled)

Check if an API interrupt is enabled.

Parameters
  • int_id (int) – The interrupt to be checked

  • enabled (bool*) – true will be stored here if the interrupt is enabled. false otherwise.

Returns

0 on success, -EINVAL if the interrupt is unknown.

New in version 1.16.

The following interrupts are defined:

EPIC_INT_RESET

Reset Handler

EPIC_INT_CTRL_C

^C interrupt. See epic_isr_ctrl_c() for details.

EPIC_INT_UART_RX

UART Receive interrupt. See epic_isr_uart_rx().

EPIC_INT_RTC_ALARM

RTC Alarm interrupt. See epic_isr_rtc_alarm().

EPIC_INT_BHI160_ACCELEROMETER

BHI160 Accelerometer. See epic_isr_bhi160_accelerometer().

EPIC_INT_BHI160_ORIENTATION

BHI160 Orientation Sensor. See epic_isr_bhi160_orientation().

EPIC_INT_BHI160_GYROSCOPE

BHI160 Gyroscope. See epic_isr_bhi160_gyroscope().

EPIC_INT_MAX30001_ECG

MAX30001 ECG. See epic_isr_max30001_ecg().

EPIC_INT_BHI160_MAGNETOMETER

BHI160 Magnetometer. See epic_isr_bhi160_magnetometer().

EPIC_INT_MAX86150

MAX86150 ECG and PPG sensor. See epic_isr_max86150().

EPIC_INT_BLE

Bluetooth Low Energy event. See epic_isr_ble().

Core API

The following functions control execution of code on core 1.

void epic_exit(int ret)

Stop execution of the current payload and return to the menu.

Parameters
  • ret (int) – Return code.

Returns

epic_exit() will never return.

int epic_exec(char * name)

Stop execution of the current payload and immediately start another payload.

Parameters
  • name (char*) –

    Name (path) of the new payload to start. This can either be:

    • A path to an .elf file (l0dable).

    • A path to a .py file (will be loaded using Pycardium).

    • A path to a directory (assumed to be a Python module, execution starts with __init__.py in this folder).

Returns

epic_exec() will only return in case loading went wrong. The following error codes can be returned:

  • -ENOENT: File not found.

  • -ENOEXEC: File not a loadable format.

void epic_system_reset()

Reset/Restart card10

PMIC API

int epic_read_battery_voltage(float * result)

Read the current battery voltage.

int epic_read_battery_current(float * result)

Read the current battery current.

int epic_read_chargein_voltage(float * result)

Read the current charge voltage.

int epic_read_chargein_current(float * result)

Read the current charge current.

int epic_read_system_voltage(float * result)

Read the current system voltage.

int epic_read_thermistor_voltage(float * result)

Read the current thermistor voltage.

UART/Serial Interface

void epic_uart_write_str(const char * str, size_t length)

Write a string to all connected serial devices. This includes:

  • Real UART, whose pins are mapped onto USB-C pins. Accessible via the HW-debugger.

  • A CDC-ACM device available via USB.

  • Maybe, in the future, bluetooth serial?

Parameters
  • str – String to write. Does not necessarily have to be NULL-terminated.

  • length – Amount of bytes to print.

int epic_uart_read_char()

Try reading a single character from any connected serial device.

If nothing is available, epic_uart_read_char() returns (-1).

Returns

The byte or (-1) if no byte was available.

int epic_uart_read_str(char * buf, size_t cnt)

Read as many characters as possible from the UART queue.

epic_uart_read_str() will not block if no new data is available. For an example, see epic_isr_uart_rx().

Parameters
  • buf (char*) – Buffer to be filled with incoming data.

  • cnt (size_t) – Size of buf.

Returns

Number of bytes read. Can be 0 if no data was available. Might be a negative value if an error occured.

void epic_isr_uart_rx()

Interrupt Service Routine for EPIC_INT_UART_RX

UART receive interrupt. This interrupt is triggered whenever a new character becomes available on any connected UART device. This function is weakly aliased to epic_isr_default() by default.

Example:

void epic_isr_uart_rx(void)
{
        char buffer[33];
        int n = epic_uart_read_str(&buffer, sizeof(buffer) - 1);
        buffer[n] = '\0';
        printf("Got: %s\n", buffer);
}

int main(void)
{
        epic_interrupt_enable(EPIC_INT_UART_RX);

        while (1) {
                __WFI();
        }
}
void epic_isr_ctrl_c()

Interrupt Service Routine for EPIC_INT_CTRL_C

A user-defineable ISR which is triggered when a ^C (0x04) is received on any serial input device. This function is weakly aliased to epic_isr_default() by default.

To enable this interrupt, you need to enable EPIC_INT_CTRL_C:

epic_interrupt_enable(EPIC_INT_CTRL_C);

Buttons

enum epic_button

Button IDs

BUTTON_LEFT_BOTTOM

1, Bottom left button (bit 0).

BUTTON_RIGHT_BOTTOM

2, Bottom right button (bit 1).

BUTTON_RIGHT_TOP

4, Top right button (bit 2).

BUTTON_LEFT_TOP

8, Top left (power) button (bit 3).

BUTTON_RESET

8, Top left (power) button (bit 3).

uint8_t epic_buttons_read(uint8_t mask)

Read buttons.

epic_buttons_read() will read all buttons specified in mask and return set bits for each button which was reported as pressed.

Note

The reset button cannot be unmapped from reset functionality. So, while you can read it, it cannot be used for app control.

Example:

#include "epicardium.h"

uint8_t pressed = epic_buttons_read(BUTTON_LEFT_BOTTOM | BUTTON_RIGHT_BOTTOM);

if (pressed & BUTTON_LEFT_BOTTOM) {
        // Bottom left button is pressed
}

if (pressed & BUTTON_RIGHT_BOTTOM) {
        // Bottom right button is pressed
}
Parameters
  • mask (uint8_t) –

    Mask of buttons to read. The 4 LSBs correspond to the 4 buttons:

    3

    2

    1

    0

    Reset

    Right Top

    Right Bottom

    Left Bottom

    Use the values defined in epic_button for masking, as shown in the example above.

Returns

Returns nonzero value if unmasked buttons are pushed.

Wristband GPIO

enum gpio_pin

GPIO pins IDs

EPIC_GPIO_WRISTBAND_1

1, Wristband connector 1

EPIC_GPIO_WRISTBAND_2

2, Wristband connector 2

EPIC_GPIO_WRISTBAND_3

3, Wristband connector 3

EPIC_GPIO_WRISTBAND_4

4, Wristband connector 4

enum gpio_mode

GPIO pin modes

EPIC_GPIO_MODE_IN

Configure the pin as input

EPIC_GPIO_MODE_OUT

Configure the pin as output

EPIC_GPIO_PULL_UP

Enable the internal pull-up resistor

EPIC_GPIO_PULL_DOWN

Enable the internal pull-down resistor

int epic_gpio_set_pin_mode(uint8_t pin, uint8_t mode)

Set the mode of a card10 GPIO pin.

epic_gpio_set_pin_mode() will set the pin specified by pin to the mode mode. If the specified pin ID is not valid this function will do nothing.

Example:

#include "epicardium.h"

// Configure wristband pin 1 as output.
if (epic_gpio_set_pin_mode(GPIO_WRISTBAND_1, GPIO_MODE_OUT)) {
    // Do your error handling here...
}
Parameters
  • pin (uint8_t) – ID of the pin to configure. Use on of the IDs defined in gpio_pin.

  • mode (uint8_t) – Mode to be configured. Use a combination of the gpio_mode flags.

Returns

0 if the mode was set, -EINVAL if pin is not valid or the mode could not be set.

int epic_gpio_get_pin_mode(uint8_t pin)

Get the mode of a card10 GPIO pin.

epic_gpio_get_pin_mode() will get the current mode of the GPIO pin specified by pin.

Example:

#include "epicardium.h"

// Get the mode of wristband pin 1.
int mode = epic_gpio_get_pin_mode(GPIO_WRISTBAND_1);
if (mode < 0) {
    // Do your error handling here...
} else {
    // Do something with the queried mode information
}
Parameters
  • pin (uint8_t) – ID of the pin to get the configuration of. Use on of the IDs defined in gpio_pin.

Returns

Configuration byte for the specified pin or -EINVAL if the pin is not valid.

int epic_gpio_write_pin(uint8_t pin, bool on)

Write value to a card10 GPIO pin,

epic_gpio_write_pin() will set the value of the GPIO pin described by pin to either on or off depending on on.

Example:

#include "epicardium.h"

// Get the mode of wristband pin 1.
int mode = epic_gpio_get_pin_mode(GPIO_WRISTBAND_1);
if (mode < 0) {
    // Do your error handling here...
} else {
    // Do something with the queried mode information
}
Parameters
  • pin (uint8_t) – ID of the pin to get the configuration of. Use on of the IDs defined in gpio_pin.

  • on (bool) – Sets the pin to either true (on/high) or false (off/low).

Returns

0 on succcess, -EINVAL if pin is not valid or is not configured as an output.

int epic_gpio_read_pin(uint8_t pin)

Read value of a card10 GPIO pin.

epic_gpio_read_pin() will get the value of the GPIO pin described by pin.

Example:

#include "epicardium.h"

// Get the current value of wristband pin 1.
uint32_t value = epic_gpio_read_pin(GPIO_WRISTBAND_1);
if (mode == -EINVAL) {
    // Do your error handling here...
} else {
    // Do something with the current value
}
Parameters
  • pin (uint8_t) – ID of the pin to get the configuration of. Use on of the IDs defined in gpio_pin.

Returns

-EINVAL if pin is not valid, an integer value otherwise.

LEDs

void epic_leds_set(int led, uint8_t r, uint8_t g, uint8_t b)

Set one of card10’s RGB LEDs to a certain color in RGB format.

This function is rather slow when setting multiple LEDs, use leds_set_all() or leds_prep() + leds_update() instead.

Parameters
  • led (int) – Which LED to set. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • r (uint8_t) – Red component of the color.

  • g (uint8_t) – Green component of the color.

  • b (uint8_t) – Blue component of the color.

int epic_leds_get_rgb(int led, uint8_t * rgb)

Get one of card10’s RGB LEDs in format of RGB.

epic_leds_get_rgb() will get the value of a RGB LED described by led.

Parameters
  • led (int) – Which LED to get. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • * rgb (uint8_t) – need tree byte array to get the value of red, green and blue.

Returns

0 on success or -EPERM if the LED is blocked by personal-state.

New in version 1.10.

void epic_leds_flash_rocket(int led, uint8_t valiue, int millis)

Set one of the rockets to flash for a certain time.

epic_leds_flash_rocket() will set a timer for the flash of a rocket.

Parameters
  • led (int) – Number of the rocket that sould flash

  • value (uint8_t) – brightness of the ‘on’-state of this rocket ( 0 < value < 32)

  • millis (int) – time in milliseconds defining the duration of the flash (i.e. how long is the rocket ‘on’)

New in version 1.16.

void epic_leds_set_hsv(int led, float h, float s, float v)

Set one of card10’s RGB LEDs to a certain color in HSV format.

This function is rather slow when setting multiple LEDs, use leds_set_all_hsv() or leds_prep_hsv() + leds_update() instead.

Parameters
  • led (int) – Which LED to set. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • h (float) – Hue component of the color. (0 <= h < 360)

  • s (float) – Saturation component of the color. (0 <= s <= 1)

  • v (float) – Value/Brightness component of the color. (0 <= v <= 0)

void epic_leds_set_all(uint8_t * pattern, uint8_t len)

Set multiple of card10’s RGB LEDs to a certain color in RGB format.

The first len leds are set, the remaining ones are not modified.

Parameters
  • pattern (uint8_t[len][r,g,b]) – Array with RGB Values with 0 <= len <= 15. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • len (uint8_t) – Length of 1st dimension of pattern, see above.

void epic_leds_set_all_hsv(float * pattern, uint8_t len)

Set multiple of card10’s RGB LEDs to a certain color in HSV format.

The first len led are set, the remaining ones are not modified.

Parameters
  • pattern (uint8_t[len][h,s,v]) – Array of format with HSV Values with 0 <= len <= 15. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs. (0 <= h < 360, 0 <= s <= 1, 0 <= v <= 1)

  • len (uint8_t) – Length of 1st dimension of pattern, see above.

void epic_leds_prep(int led, uint8_t r, uint8_t g, uint8_t b)

Prepare one of card10’s RGB LEDs to be set to a certain color in RGB format.

Use leds_update() to apply changes.

Parameters
  • led (int) – Which LED to set. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • r (uint8_t) – Red component of the color.

  • g (uint8_t) – Green component of the color.

  • b (uint8_t) – Blue component of the color.

void epic_leds_prep_hsv(int led, float h, float s, float v)

Prepare one of card10’s RGB LEDs to be set to a certain color in HSV format.

Use leds_update() to apply changes.

Parameters
  • led (int) – Which LED to set. 0-10 are the LEDs on the top and 11-14 are the 4 “ambient” LEDs.

  • h (uint8_t) – Hue component of the color. (float, 0 <= h < 360)

  • s (uint8_t) – Saturation component of the color. (float, 0 <= s <= 1)

  • v (uint8_t) – Value/Brightness component of the color. (float, 0 <= v <= 0)

void epic_leds_dim_bottom(uint8_t value)

Set global brightness for top RGB LEDs.

Aside from PWM, the RGB LEDs’ overall brightness can be controlled with a current limiter independently to achieve a higher resolution at low brightness which can be set with this function.

Parameters
  • value (uint8_t) – Global brightness of top LEDs. (1 <= value <= 8, default = 1)

void epic_leds_dim_top(uint8_t value)

Set global brightness for bottom RGB LEDs.

Aside from PWM, the RGB LEDs’ overall brightness can be controlled with a current limiter independently to achieve a higher resolution at low brightness which can be set with this function.

Parameters
  • value (uint8_t) – Global brightness of bottom LEDs. (1 <= value <= 8, default = 8)

void epic_leds_set_powersave(bool eco)

Enables or disables powersave mode.

Even when set to zero, the RGB LEDs still individually consume ~1mA. Powersave intelligently switches the supply power in groups. This introduces delays in the magnitude of ~10µs, so it can be disabled for high speed applications such as POV.

Parameters
  • eco (bool) – Activates powersave if true, disables it when false. (default = True)

void epic_leds_update()

Updates the RGB LEDs with changes that have been set with leds_prep() or leds_prep_hsv().

The LEDs can be only updated in bulk, so using this approach instead of leds_set() or leds_set_hsv() significantly reduces the load on the corresponding hardware bus.

void epic_leds_set_rocket(int led, uint8_t value)

Set the brightness of one of the rocket LEDs.

Parameters
  • led (int) –

    Which LED to set.

    ID

    Color

    Location

    0

    Blue

    Left

    1

    Yellow

    Top

    2

    Green

    Right

  • value (uint8_t) – Brightness of LED (value between 0 and 31).

int epic_leds_get_rocket(int led)

Get the brightness of one of the rocket LEDs.

Parameters
  • led (int) –

    Which LED to get.

    ID

    Color

    Location

    0

    Blue

    Left

    1

    Yellow

    Top

    2

    Green

    Right

Returns value

Brightness of LED (value between 0 and 31) or -EINVAL if the LED/rocket does not exists.

New in version 1.10.

void epic_set_flashlight(bool power)

Turn on the bright side LED which can serve as a flashlight if worn on the left wrist or as a rad tattoo illuminator if worn on the right wrist.

Parameters
  • power (bool) – Side LED on if true.

void epic_leds_set_gamma_table(uint8_t rgb_channel, uint8_t * gamma_table)

Set gamma lookup table for individual rgb channels.

Since the RGB LEDs’ subcolor LEDs have different peak brightness and the linear scaling introduced by PWM is not desireable for color accurate work, custom lookup tables for each individual color channel can be loaded into the Epicardium’s memory with this function.

Parameters
  • rgb_channel (uint8_t) – Color whose gamma table is to be updated, 0->Red, 1->Green, 2->Blue.

  • gamma_table (uint8_t[256]) – Gamma lookup table. (default = 4th order power function rounded up)

void epic_leds_clear_all(uint8_t r, uint8_t g, uint8_t b)

Set all LEDs to a certain RGB color.

Parameters
  • r (uint8_t) – Value for the red color channel.

  • g (uint8_t) – Value for the green color channel.

  • b (uint8_t) – Value for the blue color channel.

BME680

New in version 1.4.

struct bme680_sensor_data

BME680 Sensor Data

float temperature

Temperature in degree celsius

float humidity

Humidity in % relative humidity

float pressure

Pressure in hPa

float gas_resistance

Gas resistance in Ohms

int epic_bme680_init()

Initialize the BM680 sensor.

New in version 1.4.

Returns

0 on success or -Exxx on error. The following errors might occur:

  • -EFAULT: On NULL-pointer.

  • -EINVAL: Invalid configuration.

  • -EIO: Communication with the device failed.

  • -ENODEV: Device was not found.

int epic_bme680_deinit()

De-Initialize the BM680 sensor.

New in version 1.4.

Returns

0 on success or -Exxx on error. The following errors might occur:

  • -EFAULT: On NULL-pointer.

  • -EINVAL: Invalid configuration.

  • -EIO: Communication with the device failed.

  • -ENODEV: Device was not found.

int epic_bme680_read_sensors(struct bme680_sensor_data * data)

Get the current BME680 data.

New in version 1.4.

Parameters
  • data – Where to store the environmental data.

Returns

0 on success or -Exxx on error. The following errors might occur:

  • -EFAULT: On NULL-pointer.

  • -EINVAL: Sensor not initialized.

  • -EIO: Communication with the device failed.

  • -ENODEV: Device was not found.

MAX86150

struct max86150_sensor_config

Configuration for a MAX86150 sensor.

This struct is used when enabling a sensor using epic_max86150_enable_sensor().

size_t sample_buffer_len

Number of samples Epicardium should keep for this sensor. Do not set this number too high as the sample buffer will eat RAM.

uint16_t ppg_sample_rate

Sample rate for PPG from the sensor in Hz. Maximum data rate is limited to 200 Hz for all sensors though some might be limited at a lower rate.

Possible values are 10, 20, 50, 84, 100, 200.

struct max86150_sensor_data

MAX86150 Sensor Data

uint32_t red

Red LED data

uint32_t ir

IR LED data

int32_t ecg

ECG data

int epic_max86150_enable_sensor(struct max86150_sensor_config * config, size_t config_size)

Enable a MAX86150 PPG and ECG sensor.

Calling this function will instruct the MAX86150 to collect a data from the sensor. You can then retrieve the samples using epic_stream_read().

Parameters
Returns

A sensor descriptor which can be used with epic_stream_read() or a negative error value:

  • -ENOMEM: The MAX86150 driver failed to create a stream queue.

  • -ENODEV: The MAX86150 driver failed due to physical connectivity problem (broken wire, unpowered, etc).

  • -EINVAL: config->ppg_sample_rate is not one of 10, 20, 50, 84, 100, 200 or config_size is not size of config.

New in version 1.16.

int epic_max86150_disable_sensor()

Disable the MAX86150 sensor.

Returns

0 in case of success or forward negative error value from stream_deregister.

New in version 1.16.

void epic_isr_max86150()

Interrupt Service Routine for EPIC_INT_MAX86150

epic_isr_max86150() is called whenever the MAX86150 PPG sensor has new data available.

Personal State

Card10 can display your personal state.

If a personal state is set the top-left LED on the bottom side of the harmonics board is directly controlled by epicardium and it can’t be controlled by pycardium.

To re-enable pycardium control the personal state has to be cleared. To do that simply set it to STATE_NONE.

The personal state can be set to be persistent which means it won’t get reset on pycardium application change/restart.

enum personal_state

Possible personal states.

STATE_NONE

0, No personal state - LED is under regular application control.

STATE_NO_CONTACT

1, “no contact, please!” - I am overloaded. Please leave me be - red led, continuously on.

STATE_CHAOS

2, “chaos” - Adventure time - blue led, short blink, long blink.

STATE_COMMUNICATION

3, “communication” - want to learn something or have a nice conversation - yellow led, long blinks.

STATE_CAMP

4, “camp” - I am focussed on self-, camp-, or community maintenance - green led, fade on and off.

STATE_MAX

STATE_MAX gives latest value and count of possible STATEs*

int epic_personal_state_set(uint8_t state, bool persistent)

Set the users personal state.

Using epic_personal_state_set() an application can set the users personal state.

Parameters
  • state (uint8_t) – The users personal state. Must be one of personal_state.

  • persistent (bool) – Indicates whether the configured personal state will remain set and active on pycardium application restart/change.

Returns

0 on success, -EINVAL if an invalid state was requested.

int epic_personal_state_get()

Get the users personal state.

Using epic_personal_state_get() an application can get the currently set personal state of the user.

Returns

A value with exactly one value of personal_state set.

int epic_personal_state_is_persistent()

Get whether the users personal state is persistent.

Using epic_personal_state_is_persistent() an app can find out whether the users personal state is persistent or transient.

Returns

1 if the state is persistent, 0 otherwise.

Sensor Data Streams

A few of card10’s sensors can do continuous measurements. To allow performant access to their data, the following function is made for generic access to streams.

int epic_stream_read(int sd, void * buf, size_t count)

Read sensor data into a buffer. epic_stream_read() will read as many sensor samples into the provided buffer as possible and return the number of samples written. If no samples are available, epic_stream_read() will return 0 immediately.

epic_stream_read() expects the provided buffer to have a size which is a multiple of the sample size for the given stream. For the sample-format and size, please consult the sensors documentation.

Before reading the internal sensor sample queue, epic_stream_read() will call a sensor specific poll function to allow the sensor driver to fetch new samples from its hardware. This should, however, never take a long amount of time.

Parameters
  • sd (int) – Sensor Descriptor. You get sensor descriptors as return values when activating the respective sensors.

  • buf (void*) – Buffer where sensor data should be read into.

  • count (size_t) – How many bytes to read at max. Note that fewer bytes might be read. In most cases, this should be sizeof(buf).

Returns

Number of data packets read (not number of bytes) or a negative error value. Possible errors:

  • -ENODEV: Sensor is not currently available.

  • -EBADF: The given sensor descriptor is unknown.

  • -EINVAL: count is not a multiple of the sensor’s sample size.

  • -EBUSY: The descriptor table lock could not be acquired.

Example:

#include "epicardium.h"

struct foo_measurement sensor_data[16];
int foo_sd, n;

foo_sd = epic_foo_sensor_enable(9001);

while (1) {
        n = epic_stream_read(
                foo_sd,
                &sensor_data,
                sizeof(sensor_data)
        );

        // Print out the measured sensor samples
        for (int i = 0; i < n; i++) {
                printf("Measured: %?\n", sensor_data[i]);
        }
}

BHI160 Sensor Fusion

card10 has a BHI160 onboard which is used as an IMU. BHI160 exposes a few different sensors which can be accessed using Epicardium API.

New in version 1.4.

Example:

#include "epicardium.h"

// Configure a sensor & enable it
struct bhi160_sensor_config cfg = {0};
cfg.sample_buffer_len = 40;
cfg.sample_rate = 4;   // Hz
cfg.dynamic_range = 2; // g

int sd = epic_bhi160_enable_sensor(BHI160_ACCELEROMETER, &cfg);

// Read sensor data
while (1) {
        struct bhi160_data_vector buf[10];

        int n = epic_stream_read(sd, buf, sizeof(buf));

        for (int i = 0; i < n; i++) {
                printf("X: %6d Y: %6d Z: %6d\n",
                       buf[i].x,
                       buf[i].y,
                       buf[i].z);
        }
}

// Disable the sensor
epic_bhi160_disable_sensor(BHI160_ACCELEROMETER);

BHI160 Sensor Types

enum bhi160_sensor_type

BHI160 virtual sensor type.

BHI160_ACCELEROMETER

Accelerometer

BHI160_MAGNETOMETER

Magnetometer

BHI160_ORIENTATION

Orientation

BHI160_GYROSCOPE

Gyroscope

BHI160_GRAVITY

Gravity (Unimplemented)

BHI160_LINEAR_ACCELERATION

Linear acceleration (Unimplemented)

BHI160_ROTATION_VECTOR

Rotation vector (Unimplemented)

BHI160_UNCALIBRATED_MAGNETOMETER

Uncalibrated magnetometer (Unimplemented)

BHI160_GAME_ROTATION_VECTOR

Game rotation vector (whatever that is supposed to be)

BHI160_UNCALIBRATED_GYROSCOPE

Uncalibrated gyroscrope (Unimplemented)

BHI160_GEOMAGNETIC_ROTATION_VECTOR

Geomagnetic rotation vector (Unimplemented)

BHI160 Sensor Data Types

struct bhi160_data_vector

Vector Data. The scaling of these values is dependent on the chosen dynamic range. See the individual sensor’s documentation for details.

int16_t x

X

int16_t y

Y

int16_t z

Z

uint8_t status

Status

BHI160 API

struct bhi160_sensor_config

Configuration for a BHI160 sensor.

This struct is used when enabling a sensor using epic_bhi160_enable_sensor().

size_t sample_buffer_len

Number of samples Epicardium should keep for this sensor. Do not set this number too high as the sample buffer will eat RAM.

uint16_t sample_rate

Sample rate for the sensor in Hz. Maximum data rate is limited to 200 Hz for all sensors though some might be limited at a lower rate.

uint16_t dynamic_range

Dynamic range. Interpretation of this value depends on the sensor type. Please refer to the specific sensor in bhi160_sensor_type for details.

uint8_t [8] _padding

Always zero. Reserved for future parameters.

int epic_bhi160_enable_sensor(enum bhi160_sensor_type sensor_type, struct bhi160_sensor_config * config)

Enable a BHI160 virtual sensor. Calling this function will instruct the BHI160 to collect data for this specific virtual sensor. You can then retrieve the samples using epic_stream_read().

Parameters
Returns

A sensor descriptor which can be used with epic_stream_read() or a negative error value:

  • -EBUSY: The BHI160 driver is currently busy with other tasks and could not be acquired for enabling a sensor.

New in version 1.4.

int epic_bhi160_disable_sensor(enum bhi160_sensor_type sensor_type)

Disable a BHI160 sensor.

Parameters

New in version 1.4.

void epic_bhi160_disable_all_sensors()

Disable all BHI160 sensors.

New in version 1.4.

BHI160 Interrupt Handlers

void epic_isr_bhi160_accelerometer()

Interrupt Service Routine for EPIC_INT_BHI160_ACCELEROMETER

epic_isr_bhi160_accelerometer() is called whenever the BHI160 accelerometer has new data available.

void epic_isr_bhi160_magnetometer()

Interrupt Service Routine for EPIC_INT_BHI160_MAGNETOMETER

epic_isr_bhi160_magnetometer() is called whenever the BHI160 magnetometer has new data available.

void epic_isr_bhi160_orientation()

Interrupt Service Routine for EPIC_INT_BHI160_ORIENTATION

epic_isr_bhi160_orientation() is called whenever the BHI160 orientation sensor has new data available.

void epic_isr_bhi160_gyroscope()

Interrupt Service Routine for EPIC_INT_BHI160_GYROSCOPE

epic_isr_bhi160_orientation() is called whenever the BHI160 gyroscrope has new data available.

Vibration Motor

void epic_vibra_set(int status)

Turn vibration motor on or off

Parameters
  • status – 1 to turn on, 0 to turn off.

void epic_vibra_vibrate(int millis)

Turn vibration motor on for a given time

Parameters
  • millis – number of milliseconds to run the vibration motor.

Display

The card10 has an LCD screen that can be accessed from user code.

There are two ways to access the display:

  • immediate mode, where you ask Epicardium to draw shapes and text for you. Most functions in this subsection are related to immediate mode.

  • framebuffer mode, where you provide Epicardium with a memory range where you already drew graphics whichever way you wanted and Epicardium will copy them to the display. To use framebuffer mode, use the epic_disp_framebuffer() function.

enum disp_linestyle

Line-Style

LINESTYLE_FULL
LINESTYLE_DOTTED
enum disp_fillstyle

Fill-Style

FILLSTYLE_EMPTY
FILLSTYLE_FILLED
DISP_WIDTH

Width of display in pixels

DISP_HEIGHT

Height of display in pixels

union disp_framebuffer

Framebuffer

The frambuffer stores pixels as RGB565, but byte swapped. That is, for every (x, y) coordinate, there are two uint8_ts storing 16 bits of pixel data.

Todo

Document (x, y) in relation to chirality.

Example: Fill framebuffer with red

union disp_framebuffer fb;
uint16_t red = 0b1111100000000000;
for (int y = 0; y < DISP_HEIGHT; y++) {
        for (int x = 0; x < DISP_WIDTH; x++) {
                fb.fb[y][x][0] = red >> 8;
                fb.fb[y][x][1] = red & 0xFF;
        }
}
epic_disp_framebuffer(&fb);
uint8_t [80][160][2] fb

Coordinate based access (as shown in the example above).

uint8_t [25600] raw

Raw byte-indexed access.

int epic_disp_open()

Locks the display.

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_close()

Unlocks the display again.

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_update()

Causes the changes that have been written to the framebuffer to be shown on the display :return: 0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_print(int16_t posx, int16_t posy, const char * pString, uint16_t fg, uint16_t bg)

Prints a string into the display framebuffer

Parameters
  • posx – x position to print to.

  • posy – y position to print to.

  • pString – string to print

  • fg – foreground color in rgb565

  • bg – background color in rgb565

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_print_adv(uint8_t font, int16_t posx, int16_t posy, const char * pString, uint16_t fg, uint16_t bg)

Prints a string into the display framebuffer with font type selectable

Parameters
  • fontName – number of font, use FontName enum

  • posx – x position to print to.

  • posy – y position to print to.

  • pString – string to print

  • fg – foreground color in rgb565

  • bg – background color in rgb565, no background is drawn if bg==fg

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_clear(uint16_t color)

Fills the whole screen with one color

Parameters
  • color – fill color in rgb565

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_pixel(int16_t x, int16_t y, uint16_t color)

Draws a pixel on the display

Parameters
  • x – x position;

  • y – y position;

  • color – pixel color in rgb565

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_line(int16_t xstart, int16_t ystart, int16_t xend, int16_t yend, uint16_t color, enum disp_linestyle linestyle, uint16_t pixelsize)

Draws a line on the display

Parameters
  • xstart – x starting position

  • ystart – y starting position

  • xend – x ending position

  • yend – y ending position

  • color – line color in rgb565

  • linestyle – 0 for solid, 1 for dottet (almost no visual difference)

  • pixelsize – thickness of the line; 1 <= pixelsize <= 8

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_rect(int16_t xstart, int16_t ystart, int16_t xend, int16_t yend, uint16_t color, enum disp_fillstyle fillstyle, uint16_t pixelsize)

Draws a rectangle on the display

Parameters
  • xstart – x coordinate of top left corner

  • ystart – y coordinate of top left corner

  • xend – x coordinate of bottom right corner

  • yend – y coordinate of bottom right corner

  • color – line color in rgb565

  • fillstyle – 0 for empty, 1 for filled

  • pixelsize – thickness of the rectangle outline; 1 <= pixelsize <= 8

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_circ(int16_t x, int16_t y, uint16_t rad, uint16_t color, enum disp_fillstyle fillstyle, uint16_t pixelsize)

Draws a circle on the display

Parameters
  • x – x coordinate of the center; 0 <= x <= 160

  • y – y coordinate of the center; 0 <= y <= 80

  • rad – radius of the circle

  • color – fill and outline color of the circle (rgb565)

  • fillstyle – 0 for empty, 1 for filled

  • pixelsize – thickness of the circle outline; 1 <= pixelsize <= 8

Returns

0 on success or a negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_framebuffer(union disp_framebuffer * fb)

Immediately send the contents of a framebuffer to the display. This overrides anything drawn by immediate mode graphics and displayed using epic_disp_update.

Parameters
  • fb – framebuffer to display

Returns

0 on success or negative value in case of an error:

  • -EBUSY: Display was already locked from another task.

int epic_disp_ctx(void * data, size_t length)

Render a ctx drawlist. The drawlist is expected to consist of complete commands, i.e. not only a multiple of 9 bytes, but to not chop of CTX_CONT entries. The function is blocking and reads data from core1s memory space.

Data

pointer to journal data

Length

length of journal data, in bytes.

Returns

0 on success or negative value in case of an error:

int epic_disp_backlight(uint16_t brightness)

Set the backlight brightness.

Note that this function does not require acquiring the display.

Parameters
  • brightness – brightness from 0 - 100

Returns

0 on success or negative value in case of an error

int epic_light_sensor_run()

Start continuous readout of the light sensor. Will read light level at preconfigured interval and make it available via epic_light_sensor_get().

If the continuous readout was already running, this function will silently pass.

Returns

0 if the start was successful or a negative error value if an error occured. Possible errors:

  • -EBUSY: The timer could not be scheduled.

int epic_light_sensor_get(uint16_t * value)

Get the last light level measured by the continuous readout.

Parameters
  • value (uint16_t*) – where the last light level should be written.

Returns

0 if the readout was successful or a negative error value. Possible errors:

  • -ENODATA: Continuous readout not currently running.

int epic_light_sensor_stop()

Stop continuous readout of the light sensor.

If the continuous readout wasn’t running, this function will silently pass.

Returns

0 if the stop was sucessful or a negative error value if an error occured. Possible errors:

  • -EBUSY: The timer stop could not be scheduled.

uint16_t epic_light_sensor_read()

Get the light level directly.

Each call has an intrinsic delay of about 240us, I recommend another 100-300us delay between calls. Whether or not the IR LED is fast enough is another issue.

Returns

Light level

New in version 1.8.

File

Except for epic_file_open(), which models C stdio’s fopen function, close, read and write model close(2), read(2) and write(2). All file-related functions return >= 0 on success and -Exyz on failure, with error codes from errno.h (EIO, EINVAL etc.)

int epic_file_open(const char * filename, const char * modeString)
int epic_file_close(int fd)
int epic_file_read(int fd, void * buf, size_t nbytes)
int epic_file_write(int fd, const void * buf, size_t nbytes)

Write bytes to a file.

Parameters
  • fd (int) – Descriptor returned by epic_file_open().

  • buf (void*) – Data to write.

  • nbytes (size_t) – Number of bytes to write.

Returns

< 0 on error, nbytes on success. (Partial writes don’t occur on success!)

int epic_file_flush(int fd)
int epic_file_seek(int fd, long offset, int whence)
int epic_file_tell(int fd)
enum epic_stat_type
EPICSTAT_NONE

Basically ENOENT. Although epic_file_stat() returns an error for ‘none’, the type will still be set to none additionally.

This is also used internally to track open FS objects, where we use EPICSTAT_NONE to mark free objects.

EPICSTAT_FILE

normal file

EPICSTAT_DIR

directory

EPICSTAT_MAX_PATH

Maximum length of a path string (=255).

struct epic_stat
enum epic_stat_type type

Entity Type: file, directory or none

uint32_t size

Size in bytes.

char [256] name

File Name.

int epic_file_stat(const char * path, struct epic_stat * stat)

stat path

Parameters
  • filename (char*) – path to stat

  • stat (epic_stat*) – pointer to result

Returns

0 on success, negative on error

int epic_file_opendir(const char * path)

Open a directory, for enumerating its contents.

Use epic_file_readdir() to iterate over the directories entries.

Example:

#include "epicardium.h"

int fd = epic_file_opendir("/path/to/dir");

struct epic_stat entry;
for (;;) {
        epic_file_readdir(fd, &entry);

        if (entry.type == EPICSTAT_NONE) {
                // End
                break;
        }

        printf("%s\n", entry.name);
}

epic_file_close(fd);
Parameters
  • path (char*) – Directory to open.

Returns

> 0 on success, negative on error

int epic_file_readdir(int fd, struct epic_stat * stat)

Read one entry from a directory.

Call epic_file_readdir() multiple times to iterate over all entries of a directory. The end of the entry list is marked by returning EPICSTAT_NONE as the epic_stat.type.

Parameters
  • fd (int) – Descriptor returned by epic_file_opendir().

  • stat (epic_stat*) – Pointer where to store the result. Pass NULL to reset iteration offset of fd back to the beginning.

Returns

0 on success, negative on error

Unlink (remove) a file.

Parameters
  • path (char*) – file to delete

Returns

0 on success, negative on error

int epic_file_rename(const char * oldp, const char * newp)

Rename a file or directory.

Parameters
  • oldp (char*) – old name

  • newp (char*) – new name

Returns

0 on success, negative on error

int epic_file_mkdir(const char * dirname)

Create directory in CWD

Parameters
  • dirname (char*) – directory name

Returns

0 on success, negative on error

RTC

uint32_t epic_rtc_get_monotonic_seconds()

Get the monotonic time in seconds.

Returns

monotonic time in seconds

New in version 1.11.

uint64_t epic_rtc_get_monotonic_milliseconds()

Get the monotonic time in ms.

Returns

monotonic time in milliseconds

New in version 1.11.

uint32_t epic_rtc_get_seconds()

Read the current RTC value.

Returns

Unix time in seconds

uint64_t epic_rtc_get_milliseconds()

Read the current RTC value in ms.

Returns

Unix time in milliseconds

void epic_rtc_set_milliseconds(uint64_t milliseconds)

Sets the current RTC time in milliseconds

int epic_rtc_schedule_alarm(uint32_t timestamp)

Schedule the RTC alarm for the given timestamp.

Parameters
  • timestamp (uint32_t) – When to schedule the IRQ

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -EINVAL: RTC is in a bad state

void epic_isr_rtc_alarm()

Interrupt Service Routine for EPIC_INT_RTC_ALARM

epic_isr_rtc_alarm() is called when the RTC alarm triggers. The RTC alarm can be scheduled using epic_rtc_schedule_alarm().

RNG

int epic_trng_read(uint8_t * dest, size_t size)

Read random bytes from the TRNG.

Be aware that this function returns raw unprocessed bytes from the TRNG. They might be biased or have other kinds of imperfections.

Use epic_csprng_read() for cryptographically safe random numbers instead.

Warning

The exact behaviour of the TRNG is not well understood. Its distribution and other parameters are unknown. Only use this function if you really want the unmodified values from the hardware TRNG to experiment with it.

Parameters
  • * dest (uint8_t) – Destination buffer

  • size – Number of bytes to read.

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -EFAULT: Invalid destination address.

int epic_csprng_read(uint8_t * dest, size_t size)

Read random bytes from the CSPRNG.

The random bytes returned are safe to be used for cryptography.

Parameters
  • * dest (uint8_t) – Destination buffer

  • size – Number of bytes to read.

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -EFAULT: Invalid destination address.

MAX30001

struct max30001_sensor_config

Configuration for a MAX30001 sensor.

This struct is used when enabling the sensor using epic_max30001_enable_sensor().

size_t sample_buffer_len

Number of samples Epicardium should keep for this sensor. Do not set this number too high as the sample buffer will eat RAM.

uint16_t sample_rate

Sample rate for the sensor in Hz.

bool usb

Set to true if the second lead comes from USB-C

bool bias

Set to true if the interal lead bias of the MAX30001 is to be used.

uint8_t [8] _padding

Always zero. Reserved for future parameters.

int epic_max30001_enable_sensor(struct max30001_sensor_config * config)

Enable a MAX30001 ECG sensor.

Calling this function will instruct the MAX30001 to collect data for this sensor. You can then retrieve the samples using epic_stream_read().

Parameters
Returns

A sensor descriptor which can be used with epic_stream_read() or a negative error value:

  • -EBUSY: The MAX30001 driver is currently busy with other tasks and could not be acquired for enabling a sensor.

New in version 1.6.

int epic_max30001_disable_sensor()

Disable MAX30001

New in version 1.6.

void epic_isr_max30001_ecg()

Interrupt Service Routine for EPIC_INT_MAX30001_ECG

This interrupt handler is called whenever the MAX30001 ECG has new data available.

USB

int epic_usb_shutdown()

De-initialize the currently configured USB device (if any)

int epic_usb_storage()

Configure the USB peripheral to export the internal FLASH as a Mass Storage device.

int epic_usb_cdcacm()

Configure the USB peripheral to provide card10’s stdin/stdout on a USB CDC-ACM device.

WS2812

void epic_ws2812_write(uint8_t pin, uint8_t * pixels, uint32_t n_bytes)

Takes a gpio pin specified with the gpio module and transmits the led data. The format GG:RR:BB is expected.

Parameters
  • pin (uint8_t) – The gpio pin to be used for data.

  • * pixels (uint8_t) – The buffer, in which the pixel data is stored.

  • n_bytes (uint32_t) – The size of the buffer.

New in version 1.10.

Configuration

int epic_config_get_integer(const char * key, int * value)

Read an integer from the configuration file

Parameters
  • key (char*) – Name of the option to read

  • value (int*) – Place to read the value into

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: Value can not be read

New in version 1.13.

int epic_config_get_boolean(const char * key, bool * value)

Read a boolean from the configuration file

Parameters
  • key (char*) – Name of the option to read

  • value (bool*) – Place to read the value into

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: Value can not be read

New in version 1.13.

int epic_config_get_string(const char * key, char * buf, size_t buf_len)

Read a string from the configuration file.

If the buffer supplied is too small for the config option, no error is reported and the first buf_len - 1 characters are returned (0 terminated).

Parameters
  • key (char*) – Name of the option to read

  • buf (char*) – Place to read the string into

  • buf_len (size_t) – Size of the provided buffer

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: Value can not be read

New in version 1.13.

int epic_config_set_string(const char * key, const char * value)

Write a string to the configuration file.

Parameters
  • key (char*) – Name of the option to write

  • value (char*) – The value to write

Returns

0 on success or a negative value if an error occured. Possivle errors:

  • -EINVAL: Parameters out of range

  • -ENOENT: Key already exists but can not be read

  • -EIO : Unspecified I/O error

  • Any fopen/fread/fwrite/fclose related error code

New in version 1.16.

Bluetooth Low Energy (BLE)

enum ble_event_type

BLE event type

BLE_EVENT_NONE

No event pending

BLE_EVENT_HANDLE_NUMERIC_COMPARISON

Numeric comparison requested

BLE_EVENT_PAIRING_FAILED

A pairing procedure has failed

BLE_EVENT_PAIRING_COMPLETE

A pairing procedure has successfully completed

BLE_EVENT_SCAN_REPORT

New scan data is available

struct epic_scan_report

Scan report data. Bases on hciLeAdvReportEvt_t from BLE stack.

TODO: 64 bytes for data is an arbitrary number ATM

void epic_isr_ble()

Interrupt Service Routine for EPIC_INT_BLE

epic_isr_ble() is called when the BLE stack wants to signal an event to the application. You can use epic_ble_get_event() to obtain the event which triggered this interrupt.

Currently supported events:

BLE_EVENT_HANDLE_NUMERIC_COMPARISON:

An ongoing pairing procedure requires a numeric comparison to complete. The compare value can be retreived using epic_ble_get_compare_value().

BLE_EVENT_PAIRING_FAILED:

A pairing procedure failed. The stack automatically went back advertising and accepting new pairings.

BLE_EVENT_PAIRING_COMPLETE:

A pairing procedure has completed sucessfully. The stack automatically persists the pairing information, creating a bond.

New in version 1.16.

enum ble_event_type epic_ble_get_event()

Retreive the event which triggered epic_isr_ble()

The handling code needs to ensure to handle interrupts in a timely manner as new events will overwrite each other. Reading the event automatically resets it to BLE_EVENT_NONE.

Returns

Event which triggered the interrupt.

New in version 1.16.

uint32_t epic_ble_get_compare_value()

Retrieve the compare value of an ongoing pairing procedure.

If no pairing procedure is ongoing, the returned value is undefined.

Returns

6 digit long compare value

New in version 1.16.

int epic_ble_get_last_pairing_name(char * buf, size_t buf_size)

Retrieve the (file) name of the last pairing which was successful.

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: There was no successful pairing yet.

New in version 1.16.

int epic_ble_get_peer_device_name(char * buf, size_t buf_size)

Retrieve the name of the peer to which we are connected

The name might be empty if the peer device does not expose it or if it has not yet been read from it.

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: There is no active connection at the moment.

New in version 1.16.

void epic_ble_compare_response(bool confirmed)

Indicate wether the user confirmed the compare value.

If a pariring procedure involving a compare value is ongoing and this function is called with confirmed set to true, it will try to proceed and complete the pairing process. If called with false, the pairing procedure will be aborted.

Parameters
  • confirmed (bool) – true if the user confirmed the compare value.

New in version 1.16.

void epic_ble_set_mode(bool bondable, bool scanner)

Set the desired mode of the BLE stack.

There are three allowed modes:

  • Peripheral which is not bondable (bondable = false, scanner = false).

  • Peripheral which is bondable (bondable = true, scanner = false).

  • Observer which scans for advertisements (bondable = false, scanner = true).

By default the card10 will not allow new bondings to be made. New bondings have to explicitly allowed by calling this function.

While bondable the card10 will change its advertisements to indicate to scanning hosts that it is available for discovery.

When scanning is active, BLE_EVENT_SCAN_REPORT events will be sent and the scan reports can be fetched using epic_ble_get_scan_report().

When switching applications new bondings are automatically disallowed and scanning is stopped.

Parameters
  • bondable (bool) – true if new bondings should be allowed.

  • scanner (bool) – true if scanning should be turned on.

New in version 1.16.

int epic_ble_get_scan_report(struct epic_scan_report * rpt)

Retrieve a scan report from the queue of scan reports.

Parameters
  • epic_scan_report* rpt (struct) – Pointer where the report will be stored.

Returns

0 on success or a negative value if an error occured. Possible errors:

  • -ENOENT: No scan report available