Crazyflie Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 22

DownloadCrazyflie Guide
Open PDF In BrowserView PDF
Crazyflie Guide
(AKA Drones for Dummies)

Typeset by Brian Raymond,
Contributed to by Tameez Latib, Joey Miller
Under the guidance of:
Prof. Tabuada’s Cyber-Physical Systems Laboratory and
Prof. Fragouli’s Algorithmic Research in Network Information
Flow Laboratory
August 20, 2018

Contents
1 Native Installation
1.1 Crazyflie Python Library . .
1.2 Crazyflie Python Client . . .
1.3 Crazyflie Firmware . . . . . .
1.4 Crazyflie LPS Node Firmware

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

3
3
3
3
4

2 VM
2.1
2.2
2.3
2.4

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

4
4
4
5
5

3 ROS Installation
3.1 Installation Script . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 ROS Crazyflie Installation . . . . . . . . . . . . . . . . . . . . . .

5
5
5

4 Running Crazyflie
4.1 PC Client . . . . . . . . . . . .
4.2 Updating Repos . . . . . . . .
4.3 Updating Crazyradio Firmware
4.4 Compiling Crazyflie Firmware .
4.5 Adding USB Drivers . . . . . .
4.6 Bootloading the Crazyflie . . .

.
.
.
.
.
.

5
5
6
6
6
7
7

5 Running ROS
5.1 ROS Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 Terminal Commands . . . . . . . . . . . . . . . . . . . . . . . . .
5.3 Tips & Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7
7
7
8

6 Custom Firmware
6.1 Crazyflie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2 Loco-Positioning System . . . . . . . . . . . . . . . . . . . . . . .

8
8
8

Installation and Software
Installation . . . . . . . . . .
Installed Software . . . . . . .
System tweaks . . . . . . . .
Projects . . . . . . . . . . . .

7 Debugging
7.1 Crazyflie Firmware Debugging
7.1.1 STM32 . . . . . . . . .
7.1.2 nRF51 . . . . . . . . . .
7.2 Crazyflie Python Lib . . . . . .
7.3 ROS . . . . . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

9
9
9
12
12
13

8 Loco-Positioning System
13
8.1 Configuring Drones . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8.2 Configuring Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8.3 Node Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1

9 Setpoint Following
13
9.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.2 Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10 Logging
16
10.1 Loggable Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.2 Skeleton Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.3 AltLogger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
11 Custom Communication
11.1 Crazyflie *
) Base Station
11.1.1 Crazyflie Code . .
11.1.2 Base Station Code
11.2 Crazyflie *
) Beacon . . .
11.2.1 Crazyflie Code . .
11.2.2 Beacon Code . . .
11.3 Crazyflie *
) Crazyflie . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

2

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

18
18
18
19
19
19
20
21

1
1.1

Native Installation
Crazyflie Python Library

In terminal, type the following to install cflib:
$ git clone https :// github . com / bitcraze / crazyflie - lib - python . git
$ pip install -e path / to / cflib
To use USB radio without being root:
$ sudo groupadd plugdev
$ sudo usermod -a -G plugdev < username >
You will also either need to create or edit the following file:
# / etc / udev / rules . d /99 - crazyradio . rules
SUBSYSTEM == " usb " , ATTRS { idVendor }== " 1915 " , ATTRS { idProduct }== " 7777 " , MODE = "
0664 " , GROUP = " plugdev "
# to connect Crazyflie 2.0 via usb
SUBSYSTEM == " usb " , ATTRS { idVendor }== " 0483 " , ATTRS { idProduct }== " 5740 " , MODE = "
0664 " , GROUP = " plugdev "

1.2

Crazyflie Python Client

To install the client, clone the following repo and install:
$ git clone https :// github . com / bitcraze / crazyflie - clients - python . git
$ sudo apt - get install python3 python3 - pip python3 - pyqt5 python3 - pyqt5 . qtsvg
$ pip3 install -e .

1.3

Crazyflie Firmware

To install the Crazyflie 2.0 firmware and be able to edit it:
$ git clone https :// github . com / bitcraze / crazyflie - firmware . git
$ sudo add - apt - repository ppa : terry . guo / gcc - arm - embedded # For ubuntu 14.04
64 b
$ sudo add - apt - repository ppa : team - gcc - arm - embedded / ppa # For ubuntu 16.04 64
b
$ sudo apt - get update
$ sudo apt - get install libnewlib - arm - none - eabi
Compiling is done with ‘make’

3

1.4

Crazyflie LPS Node Firmware

To install the location positioning system (LPS) firmware and be able to edit it:
$ git clone https :// github . com / bitcraze / lps - node - firmware . git
$ sudo apt - get install libncurses5 : i386
$ sudo apt - get install gcc - arm - none - eabi
Compiling is done with ‘make’

2

VM Installation and Software

2.1

Installation

In order to get the Crazyflie in the air quickly, Bitcraze has set up its own Virtual Machine that is preloaded
with all the essential software and code necessary to begin flying the Crazyflie. The virtual machine is intended
to be run in Oracle VirtualBox. If you wish to run the VM in WMPlayer you will need to install some additional
tools yourself. The Virtual Machine itself has an online index. If you wish to get the latest version of the VM,
it can be found on their VM release page on Github.
One error that may come up iswhen running the VM will say something to the effect that there is an issue with
the USB controller. To fix this, be sure to select the USB 1.1 OHCI configuration. Once this is done, the virtual
machine should hopefully install and boot smoothly. Once it finishes installing, boot up the VM and click on the
desktop configuration file named Update all Projects to automatically update all Crazyflie Github Repos. The
Following is all the information necessary about the VM. It can also be found in the README on the Desktop
of the VM.
*
*
*
*

The
The
The
The

2.2

username is : bitcraze
password is : crazyflie
virtual machine has 30 GB drive and 1 GB of RAM
virtual machine is using Xubuntu 14.04.4 LTS

Installed Software

The following software has been pre-installed (besides basic setup)
• Virtualbox guest additions

• pyusb, pygame and pyqt

• gnu-arm-none-eabi + build tools

• PyQtGraph

• Git

• Qt4 and Qt Designer

• gitg

• KDE Marble with Python-bindings

• PyCharm

• KiCad

• Oracle Java JRE (for PyCharm)

• Eclipse with compiling/debugging/flashing
4

• Leafpad
• EmbSys RegView for Eclipse

2.3

• dfu-util

System tweaks

The udev rules to access the Crazyradio and the NRF bootloader have been added to the udev configuration.
They have also been added to the Virtual Box pre-set filters.

2.4

Projects

The following projects have been pre-cloned into the /home/bitcraze/projects directory:
• crazyflie-pc-client

• crazyradio-electronics

• crazyflie-firmware

• crazyflie2-nrf-firmware

• crazyflie-bootloader

• crazyflie2-stm-firmware

• crazyradio-firmware

• crazyflie2-stm-bootloader

3
3.1

ROS Installation
Installation Script

Rather than install ROS Kinetic via the website for Ubuntu 16.04, run the following script via terminal:
$ wget -- output - document install_ros . sh https :// raw . githu buserc onten t . com / il dionigi / drone - cyphy / master / install . sh
$ chmod +755 install . sh
$ bash install . sh

3.2

ROS Crazyflie Installation

Clone the following repository into your ∼/catkin ws/src/ and then run catkin make within ∼/catkin ws/ to
compile the library and install it.
$ git clone https :// github . com / il - dionigi / c r a zy f l ie _ r os _ c yp h y . git

4
4.1

Running Crazyflie
PC Client

The Crazyflie PC client can be run by using the following command:

5

#
$
#
$

On virtual machine :
python3 / home / bitcraze / projects / crazyflie - pc - client / bin / cfclient
On native install :
cfclient

Or by using the shortcut on the desktop.
Please note: If no other input device is passed to the VM the “VirtualBox USB Tablet” device will be used. Do
not connect to the Crazyflie using this device, since the thrust will then be controlled by the mouse movements
on the screen.

4.2

Updating Repos

Updating to the latest versions of all the repositories can be done by using the following:
#
$
#
$

On virtual machine :
/ home / bitcraze / bin / u p d at e _ al l_ pr o j ec t s . sh
On native install :
/ home / d e s ir e d Re p o To U p da t e git pull

On the virtual machine, the shortcut on the desktop may also be used.

4.3

Updating Crazyradio Firmware

Download the latest firmware and run the following commands:
$ cd / home / bitcraze / projects / crazyradio - firmware
$ python usbtools / launchBootloader . py
If you have not activated the USB filter for the NRF bootloader, pass the newly found ”NRF BOOT” USB device
to the virtual machine and then run the following command:
$ python usbtools / nrfbootload . py flash new_f irmwar e_file . bin

4.4

Compiling Crazyflie Firmware

A version of the Crazyflie firmware that is upgradable using the Crazyradio bootloader can be built using the
following commands:
$ cd / InstallLocation / crazyflie - firmware
$ make CLOAD =1 DEBUG =0
This firmware can then be downloaded to the Crazyflie using the cfclient or the “Flash using radio” make target
in Eclipse.

6

4.5

Adding USB Drivers

Finally, be sure to right-click on the USB at the bottom of the Virtual Machine and select USB Settings. This
will allow you to add USB drivers to the VM and is necessary to run a controller for flying the drone or allow it
to recognize the CrazyRadio Dongle.

4.6

Bootloading the Crazyflie

Once the Drone has been assembled, it is necessary to flash the latest firmware onto the drone itself. Select the
latest release zip file and use it for bootloading. To bootload the Crazyflie, hold the power button for 3 seconds
and it should begin to flash blue LED’s. If it makes the ordinary startup jingle and rotates its motors, turn it
off and try again. Open up the CFClient and click on the connect tab on the top to open a drop down menu.
Select Bootloader and then click on Initiate bootloader cold boot in the new window. It should connect to the
Crazyflie. Once it is connected, click on browse and select the zip file you previously downloaded. Now click
program and wait for it to finish flashing the firmware. once it has completed, be sure to click restart in firmware
mode. Failure to do so will result in the Crazyflie not being updated to the new firmware.

5

Running ROS

5.1

ROS Flow

About ROS topics:
ROS uses topics to manage shared data; one ‘node’ or process can publish data as a message to a topic, ad then
another node can get that data by subscribing. An example of a subscriber/publisher can be found in interface.py.
It subscribes to the location data that the server gets from he drone, and it publishes data the server should send.
About the code:
The launch files use crazyflie add node to add the crazyflie based on its uri and then calls the crazyflie server
node and the python script. The server is in direct communication with the drone; it gets messages to send based
on the subscribed topics, i.e. based on which topic the python code publishes to.

5.2
$
$
$
$
$
$
$
$

Terminal Commands

roscore // start the roscore which is needed for further commands
roslaunch  < file > // run a . launch file
e . g . roslaunch crazyflie_demo position . launch
rosrun crazyflie_tools < tool > // e . g . scan , which scans
rostopic echo < topic > // echos all data published to topic
rostopic list -v // lists all topics + how many subscribers / publishers
rostopic info < topic > // lists which nodes are published / subscribed
rosrun rqt_graph rqt_graph // shows a graph of publishers / subscribers

7

5.3

Tips & Tricks

An easy way to run catkin make from any directory is by adding the following line to your ∼/.bashrc:
$ ~/. bashrc
$ cm = ‘ cd ~/ catkin_ws && catkin_make && cd -’
This allows one to type ‘cm’ from any directory to compile/make the ROS library and then return to the directory
the command was executed from.
Note, however, that catkin make only needs to be run if C code is modified, and not if python code or launch
files are changed.
On creating a python file, it must be chmod’d to add executable permission.
If you get a what() timeout error, this usually means the connection failed because it could not find the drone,
you must change the address in the launch file.

6

Custom Firmware

6.1

Crazyflie

If the project you are currently working on requires you to modify the firmware, there are two repositories you
will need to focus on. The first is the Crazyflie 2.0 Firmware and the second is the Crazyflie 2.0 NRF Firmware.
Clone these repositories and make your modifications as necessary. Once you are finished, run the make file and
copy the binary created. The zip file downloaded in the last section contains 2 binaries and a json file. The
json file specifies the names of the binaries so it is easiest to rename the binaries you generate from the make
to the names of the binaries in the zip, extract the json file and then zip them up to create your new firmware
package. The binaries are thankfully named appropriately such that it is easy to tell which one corresponds to
NRF and the one for the ordinary firmware. Once you have your new zip file, follow the same steps in the section
on Bootloading the drone to flash your modified firmware to the drone itself.

6.2

Loco-Positioning System

To modify the firmware for the LPS system, you will need to modify the lps node firmware repository and upload
it the node using lps tools.
To install and run lps tools:
#
$
#
$

To install , navigate to cloned folder and type :
pip3 install -e .[ pyqt5 ]
To run :
python3 -m lpstools
8

If trying to modify the firmware on 64bit Linux, make sure you have the following 32bit libraries:
$ sudo apt - get install libncurses5 : i386
Then once files are modified, run the following in the root directory and upload the ‘.dfu’ in ‘lps-node-firmware/bin’
with lpstools:
$ make clean ; make

7

Debugging

7.1

Crazyflie Firmware Debugging

For debugging the Crazyflie, the debug adapter sold through bitcraze and a ST-Link/v2 will be needed. To
install the proper ST-Link v2 drivers, do the following:
$
$
$
#
$
#
$
#
$

git clone https :// github . com / texane / stlink stlink . git
cd stlink
make
install binaries
sudo cp build / Debug / st -* / usr / local / bin
install udev rules
sudo cp etc / udev / rules . d /49 - stlinkv * / etc / udev / rules . d /
restart udev rules
sudo restart udev

Also be sure to install Eclipse Photon and openOCD both on-system and within Eclipse as a debugging plugin
(reference link for both).
7.1.1

STM32

Within Eclipse:
Go to ‘Run’ → ‘Debug Configuration’. Create a new ‘GDB OpenOCD Debugging’ configuration and call it
‘Crazyflie 2.0 STM32.’
Under Main:
Make ‘Project’ your firmware folder and ‘C/C++ Application’ your cf2.elf file. Within ‘Build (if required) before
launching’ section set ‘Build Configuration’ to ‘Select Automatically’ and click on ‘Use workspace settings’.

9

Under Debugger:
Within ‘OpenOCD Client Setup’ section ensure that executable is ‘${openocd path}/${openocd executable}’,
‘GDB port’ is 3333, ‘Telnet port’ is 4444, and ‘Config options’ are ‘ -f “board/stm32discovery.cfg” ’.
Within ‘GDB Client Setup’ ensure that ‘Executable’ is ‘/usr/bin/arm-none-eabi-gdb’ and the ‘Commands’ are
‘set mem inaccesible-by-default off’.

Under Startup:
Ensure it is the same as the following.

10

11

Under Common:
Within ‘Save as’ section check ‘Shared file’ and set the location to the folder of the crazyflie firmware.

Under the Build Targets view add the following targets by clicking ‘New Build Target’: “Make CLOAD DEBUG” with the parameters “all CLOAD=1 DEBUG=1” “Make CLOAD” with the parameters “all CLOAD=1
DEBUG=0” “Make DEBUG” with the parameters “all CLOAD=0 DEBUG=1” “Flash using debugger” with
parameters “flash” “Flash using radio” with parameters “cload”
To run the debugger within Eclipse:
> Make DEBUG
> Flash using debugger
> Run → Debug Configurations → Crazyflie 2.0 STM32 → Debug
7.1.2

nRF51

Currently unsure how to debug.

7.2

Crazyflie Python Lib

The debugging of the python code is a lot simpler as you can just use the python debugger (pdb) library.
This can be done by either running the following terminal command:
$ python -m pdb myscript . py
Or adding ‘import pdb; pdb.set trace()’ where you want to break the file you wish to debug and then running
the file via terminal.
Within terminal, these are key commands:
$
$
$
$

h
l
s
n

#
#
#
#

help
list code around current break
step to next executed line
step to next line in current file
12

$ c # continue to next breakpoint

7.3

8

ROS

Loco-Positioning System

8.1

Configuring Drones

To install the Loco-Positioning deck onto the Crazyflie, be sure to place the flat end of the deck that has the
‘0xBC’ logo face down over the battery. The drone must be powered off while installing and removing the deck.
Push all the pins through the inserts on the deck and it should now be ready to use with the Loco-Positioning
System (LPS).
Note: We found that for the Crazyflie to work, we needed to re-flash (see Section 4.4) the firmware as the drone
is only configured for currently connected decks (e.g. flow deck and LPS deck).

8.2

Configuring Nodes

To flash node firmware to the Loco-Positioning Nodes, you will need to install the LPS configuration tool. Clone
the following Git Repository and follow the instructions in the README. If you are running Windows on your
device, you can alternatively install it by downloading the lps-tools-win32-install file. Once you have installed
the configuration tool, you must download the firmware for the nodes. Select the .dfu file. To update the node,
open up the LPS configuration tool and plug in the node via USB while holding down the button labeled DFU.
If on Windows, you will need to follow instructions on installing the nodes USB driver with Zadig. In the client,
click on the browse button and select the firmware file you recently downloaded. Now click update and finally
press the reset button on the node once it completes the update. Once all the nodes are updated, connect them
to the computer normally and configure the ID. If you wish to operate in TWR mode, make sure the Mode is
set to Anchor (TWR). Click apply and assign every node a different ID. Mark them with electrical tape or some
other method to easily keep track of the IDs of the nodes.
If the above doesn’t work for setting the ID/ switching the mode or flashing a new firmware is not required, there
is another method. By installing picocom and plugging in a beacon, one is able to modify the beacon’s ID or
mode via terminal in the following way:
$
$
$
$

sudo apt - get install picocom
dmesg # use this to find the address
picocom / dev / ttyACM0 # this was the address on my device
h # help command which lists all other commands

8.3

Node Placement

Place the anchors in the room at least 2 meters apart with a line of site to the flying volume. For TWR Mode,
4 anchors is the minimum with 6 being ideal and 8 if redundancy is needed.
13

9
9.1

Setpoint Following
Setup

To accomplish this, we used the Crazyflie2.0 with the ‘Flow deck’ and the ‘Loco-Postioning deck’ as the flow
sensor aides in velocity/ height calculations while the loco-positoning deck aides in absolute position calculations.
This is all done with Bitcraze’s internal kalman filter and pid functions which are a part of the crazyflie firmware
code.

9.2

Code

For setpoint following we heavily modified Luigi Pannochhi’s code which utilizes the built-in commander python
library provided by bitcraze. The python script takes in an input to specify which type of path following it
should use: ‘l’ for loco-positioning based, ‘p’ for positioning based, and ‘v’ for velocity based. The names are a
little deceiving, however, as both ‘l’ and ‘p’ use the beacons. The difference between the two is that ‘l’ creates
setpoints internally using thrust, roll, pitch, and yaw while ‘p’ creates setpoints using x, y, z, and yaw.
The following is a look at each of these setpoint following functions. Note that there are globals DT, T, VMAX,
and START HEIGHT. DT is the default dT for go straight d, T is the default time of flight, VMAX is the
maximum velocity limit, and START HEIGHT is the initial hover height.

14

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

def go_straight_d ( cf , d_x , d_y , z , t , dt = DT ) :
if ( t = = 0) :
return
steps = int ( t / dt )
v = [ d_x /t , d_y / t ]
for r in range ( steps ) :
cf . commander . send_hover_setpoint ( v [0] , v [1] , 0 , z )
time . sleep ( dt )
def l oco_follow_paths ( scf ) :
cf = scf . cf
cf . param . set_value ( ’ flightmode . posSet ’ , ’1 ’)
for position in sequence :
for i in range (200) :
cf . commander . send_setpoint ( position [1] , position [0] ,
position [3] , int ( position [2] * 1000) )
time . sleep (0.01)
time . sleep (0.1)
def pos_follow_paths ( scf ) :
cf = scf . cf
cf . param . set_value ( ’ flightmode . posSet ’ , ’1 ’)
cf . commander . send_hover_setpoint (0 ,0 ,0 , START_HEIGHT )
time . sleep (1)
cf . commander . s en d_ pos it io n_s et po in t (0 ,0 , START_HEIGHT ,0)
time . sleep (1)
for position in sequence :
cf . commander . s en d_ pos it io n_s et po int ( position [0] , position [1] ,
position [2] , 0)
time . sleep (1)
def vel_follow_paths ( scf ) :
cf = scf . cf
cf . param . set_value ( ’ flightmode . posSet ’ , ’1 ’)
cf . commander . send_hover_setpoint (0 ,0 ,0 , START_HEIGHT )
time . sleep (1)
movement = sequence [0]
for position in sequence :
movement = ( position [0] - position_internal [0] ,
position [1] - position_internal [1] ,
position [2] , position [3])
t = T
if ( abs ( movement [0] / T ) > VMAX or abs ( movement [1] / T ) > VMAX ) :
t = abs ( movement [0] / VMAX ) if abs ( movement [0] / VMAX ) >
abs ( movement [1] / VMAX ) else abs ( movement [1] / VMAX )
go_straight_d ( cf , movement [0] , movement [1] , movement [2] , t )
time . sleep (1)
for i in range (4) :
position_internal [ i ] = position [ i ]
time . sleep (0.1)

15

10
10.1

Logging
Loggable Variables

To see all the variables which can be logged, open the cfclient, connect to the crazyflie, and enable the Log TOC
by selecting ‘View → Tabs’ in the top menu bar and checking the box next to ‘Log TOC.’ This should then
enable the following tab, which may be perused to see all variables logged by each of the key words.

Logging is done by creating a LogConfig with the name of the measurement to be recorded, and then adding
variables with the names formatted according to the Log TOC.

10.2
1
2
3
4
5
6
7
8
9
10
11

Skeleton Code

import cflib
import logging
from cflib . crazyflie . log import LogConfig
dataLog = errorLog = pos_writer = log_timestamp = log_conf = Logger = None
def begin_logging ( cf ) :
global Logger
Logger = SkeletonLogger ( cf )
Logger . start_logging ()

16

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

class SkeletonLogger :
def __init__ ( self , cf ) :
self . cf = cf
logging . basicConfig ( level = logging . ERROR )
def start_logging ( self ) :
global pos_writer
pos_log_file = open ( self . directory + self . log_timestamp
+ ’ _pos . csv ’ , ’ wb ’)
pos_writer = csv . writer ( pos_log_file )
pos_writer . writerow ([ ’ time ’ , ’ x_pos ’ , ’ y_pos ’ , ’ z_pos ’ ])
log_pos = LogConfig ( name = ’ Position ’ , period_in_ms = 10)
try :
log_pos . add_variable ( ’ kalman . stateX ’ , ’ float ’)
log_pos . add_variable ( ’ kalman . stateY ’ , ’ float ’)
log_pos . add_variable ( ’ kalman . stateZ ’ , ’ float ’)
self . cf . log . add_config ( log_pos )
# This callback will receive the data
log_pos . data_received_cb . add_callback ( print_pos )
# This callback will be called on errors
log_pos . error_cb . add_callback ( log_error )
# Start the logging
log_pos . start ()
except KeyError as e :
print ( ’ Could not start log configuration , ’
’ {} not found in TOC ’. format ( str ( e ) ) )
except AttributeError :
print ( ’ Could not add Position log config , bad configuration . ’)
def print_pos ( timestamp , data , self ) :
print ([ timestamp , data [ ’ kalman . stateX ’] , data [ ’ kalman . stateY ’] ,
data [ ’ kalman . stateZ ’ ]])
def log_error ( self , logconf , msg ) :
""" Callback from the log API when an error occurs """
print ( ’ Error when logging % s : % s ’ % ( logconf . name , msg ) )
if self . errorLog = = None :
if not os . path . exists ( DIRECTORY ) :
os . makedirs ( DIRECTORY )
self . errorLog = open ( DIRECTORY + datetime . datetime . now () .
strftime ( " Error Log % Y -% m -% d_ % H : % M : % S " ) , ’a ’)
else :
self . errorLog . write ( ’ Error when logging % s : % s \ n ’
% ( logconf . name , msg ) )

This code may be copy/pasted into a python script, and the begin logging function be called by passing a Crazyflie
handle. Note that if using a SyncCrazyflie handle called ‘scf,’ one should instead pass ‘scf.cf’ to begin logging.

17

10.3

AltLogger

AltLogger.py is the robust, custom logger class that we created. To use, simply put ‘include AltLogger as
AltLogger’ in your python script header, and then once having created the Crazyflie handle, call AltLogger.begin logging(). Called with just the Crazyflie handle, this function saves data about stability, position,
acceleration, and gyroscope to .csv files in a folder called ‘/LoggedData/’ in the same directory as file being ran.
The following is the header for the function:
1
2
3
4
5
6
7
8

allowedItems = [ ’ stab ’ , ’ pos ’ , ’ acc ’ , ’ gyro ’]
defaultPath = ’. / LoggedData / ’
def begin_logging ( handle , arg1 = None , arg2 = None )
# By default , arg1 = allowedItems and arg2 = defaultPath
# To pass something other than allowedItems , pass a list subset of allowedItems
# To pass something other than defaultPath , pass a string that is a valid file path
# Note : None , either , or both of these may be passed , order independent

11
11.1
11.1.1

Custom Communication
Crazyflie *
) Base Station
Crazyflie Code

When consoleCommInit is called, it creates the header for our CRTP packet and this allows us to direct it at a
particular port. It also creates a new task/process. This process will block until it receives a packet with the right
header. Then, we can interpret this custom data from the PC. In the sample code, we also call consoleCommPuts,
which puts a string into the buffer ready to be sent and consoleCommPflush, which puts and flushes.
1 // consoleComm . c
2
3 void consoleCommInit () {
4
if ( isInit ) return ;
5
messageToPrint . size = 0;
6
messageToPrint . header = CRTP_HEADER ( CRTP_PORT_CONSOLE , 0) ;
7
v S e m a p h o r e C r e a t e B i n a r y ( consoleLock ) ;
8
xTaskCreate ( consoleCommTask , CONSOLE_COMM_TASK_NAME ,
9
CONSOLE_COMM_TASK_STACKSIZE , NULL , C O N S O L E _ C O M M _ T A S K _ P R I ) ;
10
isInit = true ;
11
co nsoleC ommPfl ush ( " Console Comm init ! " ) ;
12 }

18

1 // consoleComm . c
2
3 void consoleCommTask ( void * prm ) {
4
crt pInitT askQu eue ( CR TP_POR T_CONS OLE ) ;
5
6
while (1) {
7
c r t p R e c e i v e P a c ke t B l o c k ( CRTP_PORT_CONSOLE , & messageReceived ) ;
8
9
// process data in messageReceived . data
10
}
11 }

11.1.2

Base Station Code

For the Base Station to communicate it needs to send a packet to the drone using the CRTProtocol. We included
this in the commander class but it could be done anywhere with the correct includes.
1
2
3
4
5
6

def send_message ( self , str ) :
for i in range ( len ( str ) / 29 + 1) :
pk = CRTPPacket ()
pk . port = CRTPPort . DRONE
pk . data = struct . pack ( ’ <30 s ’ , str [29 * i :(30 * ( i + 1) ) -( i + 1) ])
self . _cf . send_packet ( pk )

11.2
11.2.1

Crazyflie *
) Beacon
Crazyflie Code

When the drone receives a packet from the beacon we check the type of packet it is. If it is of type LPS TWR RELAY B2D
(B2D = Beacon to Drone), then we can process it within beaconComm’s analyzePayload() function. Currently,
we have this function make a call to consoleCommPflush().
1
2
3
4
5
6
7
8
9
10

// lpstwrtag . c
case LPS _TWR_R ELAY_ B2D :
{
b e a c o n A n a l y z e P a y l o a d (( char *) rxPacket . payload ) ;
ranging_complete = true ;
messageToSend = 0;
messageExpected = 0;
return 0;
break ;
}
Note that in sendMessageToBeacon(), we set the messageToSend flag which tells lpstwrtag.c to communicate our
custom messages instead of its normal poll → ans → final → report routing. Within the CRTPPAcket we set
the header to LPS TWR RELAY D2B instead of LPS TWR POLL which is just a #define.
19

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// lpstwrtag . c
void initiateRanging ( dwDevice_t * dev ) {
//
...
if ( messageToSend ) {
messageExpected = 1;
memcpy ( txPacket . payload , message , LP S_MAX_ DATA_S IZE ) ;
txPacket . payload [ LPS_TWR_TYPE ] = LP S_TWR_ RELAY_ D2B ;
}
else {
txPacket . payload [ LPS_TWR_TYPE ] = LPS_TWR_POLL ;
}
txPacket . payload [ LPS_TWR_SEQ ] = ++ curr_seq ;
txPacket . sourceAddress = options - > tagAddress ;
txPacket . destAddress = options - > anchorAddress [ current_anchor ];
dwNewTransmit ( dev ) ;
dwSetDefaults ( dev ) ;
dwSetData ( dev , ( uint8_t *) & txPacket , M A C 8 0 2 1 5 4 _ H E A D E R _ L E N G T H +2+28) ;
//
...
}
The file/header pair beaconComm has functions similar to those of consoleComm, but on beaconCommFlush
(and the subsequent call to beaconCommSendMessage) it puts the data into a buffer in lpstwrtag, which will be
sent on the next communication cycle between the beacon and drone.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

// beaconComm . c
static bool b e a c o n C o m m S e n d M e s s a g e ( void ) {
s en dM es sa eT oB ea co n ( message ) ;
con soleCo mmPfl ush ( message ) ;
messageLength = 2;
// First byte is the header , and the second is the sequence number
return true ;
}
//
...
void s en d M es s a ge T o Be a c on ( char * msg ) {
messageToSend = 1;
co nsoleC ommPfl ush ( msg ) ;
memcpy ( message , msg , LP S_MAX_ DATA_S IZE ) ;
}

11.2.2

Beacon Code

On the beacon’s side of the firmware, we just modified uwb twr anchor.c to listen for the header which specifies
the packet as being a part of our custom communication. Note that RELAY D2B is defined the same as
LPS TWR RELAY D2B in the Crazyflie side of the firmware. RELAY B2D signifies the packet as being from
the Beacon to the Drone (Crazyflie).

20

1 // uwb_twr_anchor . c
2 case RELAY_D2B :
3 {
4
txPacket . payload [ TYPE ] = RELAY_B2D ;
5
txPacket . payload [ SEQ ] = rxPacket . payload [ SEQ ];
6
memcpy ( receivedMsg , rxPacket . payload + 2 , PAYLOAD_LENGTH - 2) ;
7
8
// do something to process the data
9
10
dwNewTransmit ( dev ) ;
11
dwSetDefaults ( dev ) ;
12
dwSetData ( dev , ( uint8_t *) & txPacket , M A C 8 0 2 1 5 4 _ H E A D E R _ L E N G T H +2+
PAYLOAD_LENGTH ) ;
13
14
dw WaitFo rRespo nse ( dev , true ) ;
15
dwStartTransmit ( dev ) ;
16
17
break ;
18 }

11.3

Crazyflie *
) Crazyflie

Currently abandoned for other work

21



Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.5
Linearized                      : No
Page Count                      : 22
Page Mode                       : UseOutlines
Author                          : 
Title                           : 
Subject                         : 
Creator                         : LaTeX with hyperref package
Producer                        : pdfTeX-1.40.16
Create Date                     : 2018:08:20 11:29:32-07:00
Modify Date                     : 2018:08:20 11:29:32-07:00
Trapped                         : False
PTEX Fullbanner                 : This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) kpathsea version 6.2.1
EXIF Metadata provided by EXIF.tools

Navigation menu