This sample runs a CANopen device, node 5 at 500 kbit/s, on the board’s CAN
bus. Its object dictionary comes from od.yaml: a counter the main thread
increments every 500 ms, sent in TPDO 1 on every change, at most every 10 ms
and at least every second, while the node is operational; an output written
by RPDO 1 or an SDO; and a label to read and write with segmented SDOs. The
write callback prints every value the bus writes, and the NMT callback every
state change. While operational, the SYNC callback measures how long after its reception it runs, and the sample prints the
worst case every 5 seconds.
The board needs a transceiver on its CAN pins and a CANopen master on the
bus, terminated at both ends. master.py makes a host with a CAN adapter
that master: it resets the node, reads its identity and label, writes a new
label, starts it, checks that the counter increases and writes the output.
--sync then sends SYNC at a given rate, for --duration seconds, for
the sample to report its latency. It needs python-can and
canopen, with the interface and channel of
the adapter and the EDS file the build generates:
pip install python-can canopen
samples/subsys/canopen/device/master.py --interface socketcan --channel can0 \
--eds build/canopen/od.eds
pbl samples samples/subsys/canopen/device
every board
device:
name: PebbleOS CANopen sample
product_code: 1
revision: 1
heartbeat:
producer: 1000
tpdos:
# The counter, on every change, at most every 10 ms and at least every second
- transmission: 254
inhibit: 100
event_timer: 1000
mapping: [counter]
rpdos:
- mapping: [output]
objects:
- index: 0x2000
name: counter
type: u32
access: ro
pdo: true
- index: 0x2001
name: output
type: u8
access: rw
pdo: true
- index: 0x2002
name: label
type: string
size: 32
access: rw
default: PebbleOS
#include "od.h"
#include <stdint.h>
#include <stdio.h>
#include <pbl/canopen/canopen.h>
#include <pbl/drivers/can.h>
#include <pbl/kernel/thread.h>
#include <pbl/kernel/time.h>
#define NODE_ID 5U
#define BITRATE 500000U
#define PERIOD_MS 500U
#define REPORT_MS 5000U
static struct pbl_canopen s_co;
static uint32_t s_syncs;
static uint32_t s_sync_max_us;
static const char *prv_state_name(enum pbl_canopen_nmt_state state) {
switch (state) {
case PBL_CANOPEN_NMT_INITIALIZING:
return "initializing";
case PBL_CANOPEN_NMT_STOPPED:
return "stopped";
case PBL_CANOPEN_NMT_OPERATIONAL:
return "operational";
case PBL_CANOPEN_NMT_PRE_OPERATIONAL:
return "pre-operational";
default:
return "?";
}
}
static void prv_nmt(struct pbl_canopen *co, enum pbl_canopen_nmt_state state, void *arg) {
printf("canopen: NMT %s\n", prv_state_name(state));
}
static void prv_reset(struct pbl_canopen *co, enum pbl_canopen_reset reset, void *arg) {
printf("canopen: reset %s\n", reset == PBL_CANOPEN_RESET_NODE ? "node" : "communication");
}
/* Every write from the bus, by an SDO or the RPDO, goes through here first. */
static int prv_write(struct pbl_canopen *co, uint16_t index, uint8_t subindex, const void *data,
size_t len, void *arg) {
if (index == OD_OUTPUT) {
printf("canopen: output %u\n", *(const uint8_t *)data);
} else if (index == OD_LABEL) {
printf("canopen: label %.*s\n", (int)len, (const char *)data);
}
return 0;
}
/* A control loop would run its step here: how late it runs after the SYNC came in. */
static void prv_sync(struct pbl_canopen *co, uint8_t counter, uint32_t cycles, void *arg) {
uint32_t us =
(uint32_t)((uint64_t)(pbl_cycle_get_32() - cycles) * 1000000U / pbl_cycles_per_sec());
s_syncs++;
if (us > s_sync_max_us) {
s_sync_max_us = us;
}
}
static const struct pbl_canopen_callbacks s_cb = {
.nmt = prv_nmt,
.reset = prv_reset,
.write = prv_write,
.sync = prv_sync,
};
int main(void) {
const struct pbl_canopen_config cfg = {
.can = CAN_BUS,
.od = &od,
.node_id = NODE_ID,
.bitrate = BITRATE,
.cb = &s_cb,
};
int ret;
ret = pbl_canopen_init(&s_co, &cfg);
if (ret != 0) {
fprintf(stderr, "canopen: init failed (%d)\n", ret);
return ret;
}
ret = pbl_canopen_start(&s_co);
if (ret != 0) {
fprintf(stderr, "canopen: start failed (%d)\n", ret);
return ret;
}
printf("canopen: node %u at %u bit/s\n", NODE_ID, BITRATE);
/* The counter goes out in TPDO 1 on every change, while operational. */
for (uint32_t counter = 1U;; counter++) {
pbl_thread_sleep(PBL_MSEC(PERIOD_MS));
(void)pbl_canopen_od_write(&s_co, OD_COUNTER, 0U, &counter, sizeof(counter));
if ((counter % (REPORT_MS / PERIOD_MS)) == 0U && s_syncs != 0U) {
printf("canopen: %u SYNC, latency up to %u us\n", (unsigned int)s_syncs,
(unsigned int)s_sync_max_us);
s_syncs = 0U;
s_sync_max_us = 0U;
}
}
return 0;
}
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Core Devices LLC
# SPDX-License-Identifier: Apache-2.0
"""CANopen master for the device sample.
Resets the node, reads its identity and label over SDO, writes a new label,
reads its PDO configuration, starts it and checks the counter TPDO and the
output RPDO, then optionally sends SYNC for a while.
"""
import argparse
import sys
import time
import canopen
NODE_ID = 5
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--interface", required=True, help="python-can interface, e.g. socketcan"
)
parser.add_argument(
"--channel", required=True, help="python-can channel, e.g. can0"
)
parser.add_argument("--bitrate", type=int, default=500000)
parser.add_argument(
"--sync",
type=float,
default=0,
help="send SYNC at this rate, in Hz, at the end",
)
parser.add_argument(
"--duration", type=float, default=10, help="how long to send SYNC, in seconds"
)
parser.add_argument(
"--eds", required=True, help="od.eds from the sample's build directory"
)
args = parser.parse_args()
network = canopen.Network()
network.connect(
interface=args.interface, channel=args.channel, bitrate=args.bitrate
)
node = canopen.RemoteNode(NODE_ID, args.eds)
network.add_node(node)
try:
node.nmt.state = "RESET"
node.nmt.wait_for_bootup(5)
print("boot-up received")
print(f"device name: {node.sdo[0x1008].raw}")
print(f"product code: 0x{node.sdo[0x1018][2].raw:x}")
print(f"label: {node.sdo['label'].raw}")
node.sdo["label"].raw = "written by master.py"
print(f"label: {node.sdo['label'].raw}")
node.tpdo.read()
node.rpdo.read()
node.nmt.state = "OPERATIONAL"
node.nmt.wait_for_heartbeat(2)
print(f"state: {node.nmt.state}")
values = []
for _ in range(3):
node.tpdo[1].wait_for_reception(2)
values.append(node.tpdo[1]["counter"].raw)
print(f"counter: {values}")
if values != sorted(values) or len(set(values)) != len(values):
sys.exit("counter not increasing")
for value in (0x5A, 0xA5):
node.rpdo[1]["output"].raw = value
node.rpdo[1].transmit()
time.sleep(0.1)
if node.sdo["output"].raw != value:
sys.exit(f"output not 0x{value:x}")
print("output written")
if args.sync:
print(f"SYNC at {args.sync:g} Hz for {args.duration:g} s")
network.sync.start(1 / args.sync)
time.sleep(args.duration)
network.sync.stop()
node.nmt.state = "PRE-OPERATIONAL"
print("done")
finally:
network.disconnect()
if __name__ == "__main__":
main()
canopen: NMT pre-operational
canopen: node 5 at 500000 bit/s
Generated from PebbleOS 7c542d7a9. This page is maintained in the pebbleos repository: docs/samples/subsys/canopen/device.md.