I just bought the Crazyflie 2.0 drone. This is my first drone, and it is my first time programming a drone.
My first goal is simple: Make the drone hover in place stably for 10 seconds.
I found a simple example script that turns up the thrust and then lands the drone. I modified this to 1) extend the time to 10 seconds, 2) reverse thrust if the drone starts tipping, and 3) constantly display the roll, pitch, and yaw in the console.
When I run this, the drone often flies randomly around the room and runs into things; it does not just lift up and hover stably. Why is this? How can I improve things so that it's much more stable? Do I need more sensors, or can I pull this off with just programming?
"""
Simple example that connects to the first Crazyflie found, hovers, and disconnects.
"""
import time
import sys
from threading import Thread
import logging
import cflib # noqa
from cfclient.utils.logconfigreader import LogConfig # noqa
from cflib.crazyflie import Crazyflie # noqa
logging.basicConfig(level=logging.ERROR)
class HoverTest:
"""Example that connects to the first Crazyflie found, hovers, and disconnects."""
def __init__(self, link_uri):
""" Initialize and run the example with the specified link_uri """
self._cf = Crazyflie()
self._cf.connected.add_callback(self._connected)
self._cf.disconnected.add_callback(self._disconnected)
self._cf.connection_failed.add_callback(self._connection_failed)
self._cf.connection_lost.add_callback(self._connection_lost)
self._cf.open_link(link_uri)
self._status = {}
self._status['gyro.x'] = 0
self._status['gyro.y'] = 0
self._status['gyro.z'] = 0
print("Connecting to %s" % link_uri)
def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print("Connected to %s" % link_uri)
# The definition of the logconfig can be made before connecting
self._lg_gryo = LogConfig(name="gyro", period_in_ms=10)
self._lg_gryo.add_variable("gyro.x", "float")
self._lg_gryo.add_variable("gyro.y", "float")
self._lg_gryo.add_variable("gyro.z", "float")
# Adding the configuration cannot be done until a Crazyflie is
# connected, since we need to check that the variables we
# would like to log are in the TOC.
try:
self._cf.log.add_config(self._lg_gryo)
# This callback will receive the data
self._lg_gryo.data_received_cb.add_callback(self._gryo_log_data)
# This callback will be called on errors
self._lg_gryo.error_cb.add_callback(self._gryo_log_error)
# Start the logging
self._lg_gryo.start()
except KeyError as e:
print("Could not start log configuration,"
"{} not found in TOC".format(str(e)))
except AttributeError:
print("Could not add gyro log config, bad configuration.")
# Start a separate thread to do the motor test.
# Do not hijack the calling thread!
Thread(target=self._hover).start()
def _connection_failed(self, link_uri, msg):
"""Callback when connection initial connection fails (i.e no Crazyflie
at the specified address)"""
print("Connection to %s failed: %s" % (link_uri, msg))
def _connection_lost(self, link_uri, msg):
"""Callback when disconnected after a connection has been made (i.e
Crazyflie moves out of range)"""
print("Connection to %s lost: %s" % (link_uri, msg))
def _disconnected(self, link_uri):
"""Callback when the Crazyflie is disconnected (called in all cases)"""
print("Disconnected from %s" % link_uri)
def _gryo_log_error(self, logconf, msg):
"""Callback from the log API when an error occurs"""
print("Error when logging %s: %s" % (logconf.name, msg))
def _gryo_log_data(self, timestamp, data, logconf):
"""Callback froma the log API when data arrives"""
# print("[%d][%s]: %s" % (timestamp, logconf.name, data))
self._status['gyro.x'] = data['gyro.x']
self._status['gyro.y'] = data['gyro.y']
self._status['gyro.z'] = data['gyro.z']
def _hover(self):
start_time = time.time()
run_time = 7
thrust_multiplier = 1
thrust_step = 500
thrust = 20000
max_thrust = 39000
roll = -1.00
pitch = -2.00
yaw = 0
# Unlock startup thrust protection.
self._cf.commander.send_setpoint(0, 0, 0, 0)
# Turn on altitude hold.
self._cf.param.set_value("flightmode.althold","True")
while thrust >= 20000:
# Update the position.
self._cf.commander.send_setpoint(roll, pitch, yaw, thrust)
time.sleep(0.01)
if thrust >= max_thrust and time.time() - start_time >= run_time:
# Reverse thrust
thrust_multiplier = -1
if thrust <= max_thrust or thrust_multiplier == -1:
thrust += thrust_step * thrust_multiplier
# Reverse thrust if the drone tips over.
if abs(self._status['gyro.x']) >= 75 or abs(self._status['gyro.y']) >= 75:
print('Aborting')
thrust_multiplier = -2
print(self._status['gyro.x'], self._status['gyro.y'], self._status['gyro.z'])
self._cf.commander.send_setpoint(0, 0, 0, 0)
# Make sure that the last packet leaves before the link is closed
# since the message queue is not flushed before closing
time.sleep(0.1)
self._cf.close_link()
if __name__ == '__main__':
# Initialize the low-level drivers (don't list the debug drivers)
cflib.crtp.init_drivers(enable_debug_driver=False)
# Scan for Crazyflies and use the first one found
print("Scanning interfaces for Crazyflies...")
available = cflib.crtp.scan_interfaces()
print("Crazyflies found:")
for i in available:
print(i[0])
if len(available) > 0:
le = HoverTest(available[0][0])
else:
print("No Crazyflies found, cannot run example")
As you can see, I tried simply adjusting the roll and pitch (to -1.00 and -2.00), but that did not help much. When I use the GUI and a joystick to control the drone and I adjust the roll and pitch trim values to -1.00 and -2.00, this definitely helps stabilize the drone.
Any ideas are welcome. Thank you!