---
title: "CANopen: Device"
canonical_url: https://developer.repebble.com/pebbleos/docs/samples/subsys/canopen/device/
last_updated: 2026-12-01
sdk_version: 4.44
---
# CANopen: Device

Source: https://developer.repebble.com/pebbleos/docs/samples/subsys/canopen/device/

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](https://python-can.readthedocs.io) and [canopen](https://canopen.readthedocs.io), 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
```

Run:

`pbl samples samples/subsys/canopen/device`

Boards:

every board

## Sources

od.yaml

```
device:name: PebbleOS CANopen sampleproduct\_code: 1revision: 1heartbeat:producer: 1000tpdos:# The counter, on every change, at most every 10 ms and at least every second- transmission: 254inhibit: 100event\_timer: 1000mapping: [counter]rpdos:- mapping: [output]objects:- index: 0x2000name: countertype: u32access: ropdo: true- index: 0x2001name: outputtype: u8access: rwpdo: true- index: 0x2002name: labeltype: stringsize: 32access: rwdefault: PebbleOS
```

src/main.c

```
#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 5000Ustatic 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;}
```

master.py

```
#!/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 theoutput RPDO, then optionally sends SYNC for a while."""import argparseimport sysimport timeimport canopenNODE\_ID=5def 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\_inrange(3):node.tpdo[1].wait\_for\_reception(2)values.append(node.tpdo[1]["counter"].raw)print(f"counter: {values}")ifvalues!=sorted(values)orlen(set(values))!=len(values):sys.exit("counter not increasing")forvaluein(0x5A,0xA5):node.rpdo[1]["output"].raw=valuenode.rpdo[1].transmit()time.sleep(0.1)ifnode.sdo["output"].raw!=value:sys.exit(f"output not 0x{value:x}")print("output written")ifargs.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()
```

## Output

```
canopen: NMT pre-operational
canopen: node 5 at 500000 bit/s
```

Generated from PebbleOS [7c542d7a9](https://github.com/coredevices/pebbleos/commit/7c542d7a9d6fddb551ac1d242c8bf3c8a6cc6ce6). This page is maintained in the pebbleos repository: [docs/samples/subsys/canopen/device.md](https://github.com/coredevices/pebbleos/blob/7c542d7a9d6fddb551ac1d242c8bf3c8a6cc6ce6/docs/samples/subsys/canopen/device.md).
