pebble
  • Tutorials
  • Get the SDK
  • Guides
  • Documentation
  • PebbleOS
  • Mobile App
  • Examples
  • Index 01
  • Community
  • Blog
  • More
Privacy
Cookies
Publish

PebbleOS

  • Overview
  • Start here
    • Getting started guide
  • Pebble Firmware
    • Overview
    • Playground
    • Application SDK
  • Development
    • The pbl CLI
    • Build system
    • Samples
      • Kernel
      • Subsystems
      • Drivers
      • Third-party
      • Rust
      • Benchmarks
    • Emulator and simulator
    • Testing
    • Debugging
    • Conventions
  • System
    • Architecture overview
    • Kernel
    • Drivers
    • Subsystems
    • Libraries
    • Third-party
  • Hardware
    • Boards
    • Board Add-ons
    • Programmers
  • Community
    • Contribution Guidelines
  • Reference
    • Reference
    • Kconfig options

CAN: Echoed pings

This sample joins the board’s CAN bus at 500 kbit/s and sends ten pings, 0x100 frames carrying a counter, each waiting for another node to acknowledge it. Received frames are queued by the receive callback, which runs in the controller’s interrupt, and an acceptance filter only lets in 0x101 frames: the main thread waits for each ping to come back as one, and prints how long it took. At the end it prints the error counters and stops the controller.

The board needs a transceiver on its CAN pins and another node on the bus, terminated at both ends. echo.py makes a host with a CAN adapter that node: it sends each ping back as 0x101. It needs python-can, with the interface and channel of the adapter:

pip install python-can
samples/drivers/can/echo.py --interface socketcan --channel can0

Without another node, the first ping is never acknowledged, and the sample says so.

Warning

Some boards may suffer from this problem: while the board resets or powers up, its CAN TX pin is low or floating, and the transceiver drives the bus dominant. The other node then stays in error warning, and some host drivers drop the frames it receives, so echo.py sees no pings. A pull-up on TX fixes it.

Run:

pbl samples samples/drivers/can

Boards:

every board

Sources

src/main.c
#include <errno.h>
#include <stdint.h>
#include <stdio.h>

#include <pbl/drivers/can.h>
#include <pbl/kernel/delay.h>
#include <pbl/kernel/msgq.h>
#include <pbl/kernel/time.h>

#define BITRATE   500000U
#define PING_ID   0x100U
#define ECHO_ID   0x101U
#define PINGS     10U
#define ECHO_MS   100U
#define PERIOD_MS 100U

static PBL_MSGQ_DEFINE(s_rx_q, sizeof(struct pbl_can_frame), 4);

/* Called from the controller interrupt: only queue the frame. */
static void prv_rx(const struct pbl_can *can, const struct pbl_can_frame *frame, void *arg) {
  (void)pbl_msgq_put(&s_rx_q, frame, PBL_NO_WAIT);
}

/* Wait for the echo of ping @p seq, skipping other frames. */
static int prv_wait_echo(uint32_t seq) {
  uint64_t end = pbl_uptime_ms() + ECHO_MS;
  struct pbl_can_frame frame;

  for (uint64_t now = pbl_uptime_ms(); now < end; now = pbl_uptime_ms()) {
    if (pbl_msgq_get(&s_rx_q, &frame, PBL_MSEC((uint32_t)(end - now))) != 0) {
      break;
    }
    if (frame.id == ECHO_ID && frame.len == 4U && frame.data32[0] == seq) {
      return 0;
    }
  }

  return -ETIMEDOUT;
}

int main(void) {
  const struct pbl_can_config cfg = {.bitrate = BITRATE};
  const struct pbl_can_filter filter = {.id = ECHO_ID, .mask = PBL_CAN_STD_ID_MASK};
  struct pbl_can_frame ping = {.id = PING_ID, .len = 4U};
  struct pbl_can_err_cnt cnt;
  enum pbl_can_bus_state state;
  unsigned int echoed = 0U;
  int ret;

  ret = pbl_can_configure(CAN_BUS, &cfg);
  if (ret >= 0) {
    ret = pbl_can_add_filter(CAN_BUS, &filter);
  }
  if (ret < 0) {
    fprintf(stderr, "can: configuration failed (%d)\n", ret);
    return ret;
  }

  pbl_can_set_rx_callback(CAN_BUS, prv_rx, nullptr);

  ret = pbl_can_start(CAN_BUS);
  if (ret != 0) {
    fprintf(stderr, "can: start failed (%d)\n", ret);
    return ret;
  }

  printf("can: %u bit/s\n", BITRATE);

  for (uint32_t seq = 0U; seq < PINGS; seq++) {
    uint64_t start = pbl_uptime_ms();

    /* Without a callback, wait for the frame to go: another node has to acknowledge it. */
    ping.data32[0] = seq;
    ret = pbl_can_send(CAN_BUS, &ping, PBL_MSEC(ECHO_MS), nullptr, nullptr);
    if (ret != 0) {
      fprintf(stderr, "can: ping %u not sent (%d), no other node on the bus?\n", (unsigned int)seq,
              ret);
      break;
    }

    if (prv_wait_echo(seq) == 0) {
      printf("can: echo %u in %u ms\n", (unsigned int)seq, (unsigned int)(pbl_uptime_ms() - start));
      echoed++;
    } else {
      printf("can: no echo %u\n", (unsigned int)seq);
    }

    pbl_sleep_ms(PERIOD_MS);
  }

  (void)pbl_can_get_state(CAN_BUS, &state, &cnt);
  printf("can: %u of %u echoed, tx errors %u, rx errors %u\n", echoed, PINGS, cnt.tx, cnt.rx);

  (void)pbl_can_stop(CAN_BUS);

  printf("Sample done\n");

  return 0;
}
echo.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Core Devices LLC
# SPDX-License-Identifier: Apache-2.0

"""Echo the pings of the CAN sample: each 0x100 frame back as 0x101.

Needs python-can and a CAN adapter it supports, e.g.:

    pip install python-can
    ./echo.py --interface socketcan --channel can0
    ./echo.py --interface pcan --channel PCAN_USBBUS1
"""

import argparse

import can

PING_ID = 0x100
ECHO_ID = 0x101


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--interface", required=True, help="python-can interface")
    parser.add_argument("--channel", required=True, help="adapter channel")
    parser.add_argument(
        "--bitrate", type=int, default=500000, help="bit rate (default: 500000)"
    )
    args = parser.parse_args()

    with can.Bus(
        interface=args.interface, channel=args.channel, bitrate=args.bitrate
    ) as bus:
        print(f"echoing 0x{PING_ID:03x} as 0x{ECHO_ID:03x}, Ctrl-C to stop", flush=True)
        try:
            for msg in bus:
                if (
                    msg.arbitration_id != PING_ID
                    or msg.is_extended_id
                    or msg.is_remote_frame
                ):
                    continue
                bus.send(
                    can.Message(
                        arbitration_id=ECHO_ID, data=msg.data, is_extended_id=False
                    )
                )
                print(f"echoed {msg.data.hex()}", flush=True)
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    main()

Output

can: 500000 bit/s
can: echo 0 in \d+ ms
can: echo 1 in \d+ ms
can: echo 2 in \d+ ms
can: echo 3 in \d+ ms
can: echo 4 in \d+ ms
can: echo 5 in \d+ ms
can: echo 6 in \d+ ms
can: echo 7 in \d+ ms
can: echo 8 in \d+ ms
can: echo 9 in \d+ ms
can: 10 of 10 echoed, tx errors \d+, rx errors \d+
Sample done

Generated from PebbleOS 013613c8a. This page is maintained in the pebbleos repository: docs/samples/drivers/can.md.

Overview

  • Sources
  • Output