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

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

This sample runs a CiA 402 drive, node 6 at 500 kbit/s, on the board’s CAN bus, with a simulated motor: its velocity follows the target with a 200 ms time constant while the drive is operation enabled, coasts down once disabled and ramps down faster on a quick stop, which it then reports done. The model is the control loop: it runs on its own every millisecond, in the tick interrupt, and shares only atomics with the node, so it never waits for the stack. In profile velocity, the write callback hands it a new target as soon as it is written, and the main thread reports its velocity every 10 ms. In cyclic synchronous velocity, the SYNC callback hands it the target RPDO 2 applies and reports its velocity, which TPDO 2 then sends with the statusword. TPDO 1 sends the statusword and the mode on every change.

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 and starts the node, enables the drive in cyclic synchronous velocity with SYNC at 100 Hz, checks that the velocity follows two targets, quick stops it, then enables it in profile velocity and waits for the target to be reached. 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/drive/master.py --interface socketcan --channel can0 \--eds build/canopen/od.eds
```

Run:

`pbl samples samples/subsys/canopen/drive`

Boards:

every board

## Sources

od.yaml

```
device:type: 0x00020192name: PebbleOS CANopen drive sampleproduct\_code: 2revision: 1heartbeat:producer: 100cia402:modes: [pv, csv]rpdos:- mapping: [controlword, modes\_of\_operation]# Applied on SYNC- transmission: 1mapping: [target\_velocity]tpdos:- transmission: 254inhibit: 10mapping: [statusword, modes\_of\_operation\_display]# Sampled on SYNC- transmission: 1mapping: [statusword, velocity\_actual\_value]
```

src/main.c

```
#include "od.h"#include \<stdatomic.h\>#include \<stdint.h\>#include \<stdio.h\>#include \<stdlib.h\>#include \<string.h\>#include \<pbl/canopen/canopen.h\>#include \<pbl/canopen/cia402.h\>#include \<pbl/drivers/can.h\>#include \<pbl/kernel/thread.h\>#include \<pbl/kernel/time.h\>#include \<pbl/kernel/timer.h\>#define NODE\_ID 6U#define BITRATE 500000U/\* Control loop period, and how often the main thread reports what it does \*/#define LOOP\_PERIOD\_MS 1#define REPORT\_PERIOD\_MS 10/\* Time constant of the simulated motor, and of its quick stop ramp \*/#define TAU\_MS 200#define QS\_TAU\_MS 50/\* Target reached within this many units per second \*/#define WINDOW 10/\* Fractional bits of the model's velocity \*/#define Q 256enum command {CMD\_COAST,CMD\_RUN,CMD\_QUICK\_STOP,};static struct pbl\_canopen s\_co;static struct pbl\_cia402 s\_drive;static struct pbl\_timer s\_loop;/\* \* What the node and the control loop share. The loop never waits for the node: it only loads and \* stores lock-free atomics, so it may as well run in a zero-latency interrupt. \*/static atomic\_int\_least32\_t s\_target;static atomic\_int\_least32\_t s\_velocity;static atomic\_uint\_least8\_t s\_command;/\* The control loop, the simulated motor here, in the tick interrupt. \*/static void prv\_loop(struct pbl\_timer \*timer) {static int32\_t velocity\_q;enum command command = atomic\_load(&s\_command);int32\_t target = command == CMD\_RUN ? atomic\_load(&s\_target) : 0;int32\_t tau = command == CMD\_QUICK\_STOP ? QS\_TAU\_MS : TAU\_MS;int32\_t step;pbl\_timer\_start(timer, PBL\_MSEC(LOOP\_PERIOD\_MS));step = (target \* Q - velocity\_q) \* LOOP\_PERIOD\_MS / tau;velocity\_q = step == 0 ? target \* Q : velocity\_q + step;atomic\_store(&s\_velocity, velocity\_q / Q);}/\* Report the loop's velocity and what follows from it. \*/static void prv\_report(void) {int32\_t velocity = atomic\_load(&s\_velocity);uint8\_t command = atomic\_load(&s\_command);int32\_t target = command == CMD\_RUN ? atomic\_load(&s\_target) : 0;(void)pbl\_canopen\_od\_write(&s\_co, OD\_VELOCITY\_ACTUAL\_VALUE, 0U, &velocity, sizeof(velocity));pbl\_cia402\_set\_status(&s\_drive, PBL\_CIA402\_SW\_TARGET\_REACHED,abs(target - velocity) \<= WINDOW ? PBL\_CIA402\_SW\_TARGET\_REACHED : 0U);if (command == CMD\_QUICK\_STOP && velocity == 0 &&atomic\_compare\_exchange\_strong(&s\_command, &command, CMD\_COAST)) {pbl\_cia402\_quick\_stop\_done(&s\_drive);}}static int prv\_switch\_on(struct pbl\_cia402 \*drive, void \*arg) {printf("drive: power stage on\n");return 0;}static void prv\_switch\_off(struct pbl\_cia402 \*drive, void \*arg) {printf("drive: power stage off\n");}static int prv\_enable(struct pbl\_cia402 \*drive, void \*arg) {int32\_t target = 0;printf("drive: enabled\n");(void)pbl\_canopen\_od\_read(&s\_co, OD\_TARGET\_VELOCITY, 0U, &target, sizeof(target));atomic\_store(&s\_target, target);atomic\_store(&s\_command, CMD\_RUN);return 0;}/\* The motor coasts to a stop. \*/static void prv\_disable(struct pbl\_cia402 \*drive, void \*arg) {printf("drive: disabled\n");atomic\_store(&s\_command, CMD\_COAST);}/\* The loop ramps the motor down, and prv\_report() tells the drive once it stands still. \*/static void prv\_quick\_stop(struct pbl\_cia402 \*drive, void \*arg) {printf("drive: quick stop\n");atomic\_store(&s\_command, CMD\_QUICK\_STOP);}static int prv\_set\_mode(struct pbl\_cia402 \*drive, enum pbl\_cia402\_mode mode, void \*arg) {printf("drive: mode %d\n", mode);return 0;}static const struct pbl\_cia402\_ops s\_ops = {.switch\_on = prv\_switch\_on,.switch\_off = prv\_switch\_off,.enable = prv\_enable,.disable = prv\_disable,.quick\_stop = prv\_quick\_stop,.set\_mode = prv\_set\_mode,};/\* Profile velocity: a new target goes to the loop as soon as it is written. \*/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\_TARGET\_VELOCITY &&pbl\_cia402\_mode(&s\_drive) == PBL\_CIA402\_MODE\_PROFILE\_VELOCITY) {int32\_t target;memcpy(&target, data, sizeof(target));atomic\_store(&s\_target, target);}return 0;}/\* \* Cyclic synchronous velocity: the target RPDO 2 applied goes to the loop, and TPDO 2 samples the \* velocity reported here. \*/static void prv\_sync(struct pbl\_canopen \*co, uint8\_t counter, uint32\_t cycles, void \*arg) {int32\_t target;if (pbl\_cia402\_mode(&s\_drive) != PBL\_CIA402\_MODE\_CYCLIC\_VELOCITY) {return;}if (pbl\_canopen\_od\_read(&s\_co, OD\_TARGET\_VELOCITY, 0U, &target, sizeof(target)) ==(int)sizeof(target)) {atomic\_store(&s\_target, target);}prv\_report();}static void prv\_nmt(struct pbl\_canopen \*co, enum pbl\_canopen\_nmt\_state state, void \*arg) {printf("drive: NMT %02x\n", state);}static const struct pbl\_canopen\_callbacks s\_cb = {.nmt = prv\_nmt,.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, "drive: node init failed (%d)\n", ret);return ret;}ret = pbl\_cia402\_init(&s\_drive, &s\_co, &s\_ops, nullptr);if (ret != 0) {fprintf(stderr, "drive: drive init failed (%d)\n", ret);return ret;}ret = pbl\_canopen\_start(&s\_co);if (ret != 0) {fprintf(stderr, "drive: start failed (%d)\n", ret);return ret;}printf("drive: node %u at %u bit/s\n", NODE\_ID, BITRATE);pbl\_timer\_init(&s\_loop, prv\_loop);pbl\_timer\_start(&s\_loop, PBL\_MSEC(LOOP\_PERIOD\_MS));for (;;) {pbl\_thread\_sleep(PBL\_MSEC(REPORT\_PERIOD\_MS));prv\_report();}return 0;}
```

master.py

```
#!/usr/bin/env python3# SPDX-FileCopyrightText: 2026 Core Devices LLC# SPDX-License-Identifier: Apache-2.0"""CANopen master for the drive sample.Resets the drive, starts it, runs it in cyclic synchronous velocity mode withSYNC and a target velocity in RPDO 2, quick stops it, then runs it in profilevelocity mode and disables it."""import argparseimport sysimport timeimport canopenNODE\_ID=6SW\_STATE=0x6FSW\_SWITCH\_ON\_DISABLED=0x40SW\_OPERATION\_ENABLED=0x27SW\_TARGET\_REACHED=1\<\<10MODE\_PV=3MODE\_CSV=9def wait\_status(node,mask,value,timeout=2):end=time.monotonic()+timeoutwhiletime.monotonic()\<end:sw=node.sdo["statusword"].rawifsw&mask==value:returnswtime.sleep(0.02)sys.exit(f"statusword 0x{sw:04x}, expected 0x{value:04x} in 0x{mask:04x}")def enable(node,mode):node.sdo["modes\_of\_operation"].raw=modenode.sdo["controlword"].raw=0x06node.sdo["controlword"].raw=0x0Fwait\_status(node,SW\_STATE,SW\_OPERATION\_ENABLED)print(f"mode {node.sdo['modes\_of\_operation\_display'].raw}: operation enabled")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="python-can channel")parser.add\_argument("--bitrate",type=int,default=500000)parser.add\_argument("--eds",required=True,help="od.eds from the build directory")parser.add\_argument("--sync",type=float,default=100,help="SYNC rate in Hz")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)node.tpdo.read()node.rpdo.read()node.nmt.state="OPERATIONAL"wait\_status(node,SW\_STATE,SW\_SWITCH\_ON\_DISABLED)network.sync.start(1/args.sync)enable(node,MODE\_CSV)fortargetin(1000,-500):node.rpdo[2]["target\_velocity"].raw=targetnode.rpdo[2].start(1/args.sync)time.sleep(1.5)node.tpdo[2].wait\_for\_reception(1)actual=node.tpdo[2]["velocity\_actual\_value"].rawprint(f"target {target}: actual {actual}")ifabs(actual-target)\>10:sys.exit("velocity not reached")node.rpdo[2].stop()node.sdo["controlword"].raw=0x0Bwait\_status(node,SW\_STATE,SW\_SWITCH\_ON\_DISABLED)print(f"quick stop: actual {node.sdo['velocity\_actual\_value'].raw}")enable(node,MODE\_PV)node.sdo["target\_velocity"].raw=2000wait\_status(node,SW\_TARGET\_REACHED,SW\_TARGET\_REACHED,timeout=3)print(f"target reached: actual {node.sdo['velocity\_actual\_value'].raw}")node.sdo["controlword"].raw=0x06network.sync.stop()node.nmt.state="PRE-OPERATIONAL"print("done")finally:network.disconnect()if\_\_name\_\_=="\_\_main\_\_":main()
```

## Output

```
drive: node 6 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/drive.md](https://github.com/coredevices/pebbleos/blob/7c542d7a9d6fddb551ac1d242c8bf3c8a6cc6ce6/docs/samples/subsys/canopen/drive.md).
