Skip to content

Exercise Files for the DroneBlocks InnovatED STEM Air Land and Sea Course

Notifications You must be signed in to change notification settings

feraco/crazyflie-python-basics-Air-Land-Sea

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

πŸš€ Crazyflie Motion Commands

πŸ›« Takeoff & Landing

mc.take_off(height=0.3)  # Take off to 0.3 meters (default height)
mc.land()                # Land the drone
mc.stop()                # Immediately stop all movement

πŸ“ Basic Movements

mc.forward(distance_m)  # Move forward by X meters
mc.back(distance_m)     # Move backward by X meters
mc.left(distance_m)     # Move left by X meters
mc.right(distance_m)    # Move right by X meters
mc.up(distance_m)       # Move up by X meters
mc.down(distance_m)     # Move down by X meters

Example:

mc.forward(0.5)  # Move forward 0.5 meters
mc.left(0.3)     # Move left 0.3 meters
mc.down(0.2)     # Move down 0.2 meters

πŸ”„ Rotations (Yaw)

mc.turn_left(angle_deg)   # Turn left (counterclockwise) by X degrees
mc.turn_right(angle_deg)  # Turn right (clockwise) by X degrees

Example:

mc.turn_left(90)   # Turn left by 90 degrees
mc.turn_right(180) # Turn right by 180 degrees

🏎️ Velocity-Based Movements (Continuous Speed Control)

mc.start_linear_motion(vx, vy, vz, rate_yaw=0)  # Move at a velocity
# vx β†’ Forward speed (m/s)
# vy β†’ Sideways speed (m/s)
# vz β†’ Vertical speed (m/s)
# rate_yaw β†’ Rotation speed (deg/s)

Example:

mc.start_linear_motion(0.5, 0, 0)  # Move forward at 0.5 m/s
mc.start_linear_motion(0, 0, 0.3)  # Move up at 0.3 m/s
mc.start_linear_motion(0.2, 0.2, 0, 30)  # Move diagonally & rotate at 30Β°/s

⚠️ This function must be stopped manually with mc.stop()


πŸ”„ Circle and Curve Movements

mc.circle_right(radius_m, velocity_m_s)  # Fly a circle to the right
mc.circle_left(radius_m, velocity_m_s)   # Fly a circle to the left

Example:

mc.circle_right(radius_m=1.0, velocity_m_s=0.5)  # Circle right with 1m radius
mc.circle_left(radius_m=0.5, velocity_m_s=0.3)   # Circle left with 0.5m radius

πŸŒ€ Spiral Motion

mc.spiral(duration=6, radius=0.3, turns=3, ascend=True)
mc.spiral(duration=6, radius=0.3, turns=3, ascend=False)

Example:

cf.spiral(5, 0.2, 2, True)
# πŸ‘‰ This will fly a tight spiral upward:
# - 5 seconds duration
# - 0.2 meter radius (tight circle)
# - 2 full spiral turns
# - True = ascending

πŸš€ Crazyflie Flow Deck Commands & Conditional Statements

The Flow Deck is an optical flow and distance sensor that enables autonomous positioning for the Crazyflie drone. It allows the drone to hover, move precisely, and hold position without external tracking systems.

πŸ“Œ Required Import for Flow Deck

from cflib.positioning.motion_commander import MotionCommander

πŸ“‘ Flow Deck Sensor Readings

πŸ”Ή Get Height (Z-axis distance)

altitude = mc.get_height()
print(f"Current altitude: {altitude} meters")

πŸ”Ή Get Optical Flow-Based Velocity

velocity = mc.get_velocity()
print(f"Velocity (X, Y, Z): {velocity}")

πŸ”Ή Get Position Estimate

position = mc.get_position()
print(f"Estimated position (X, Y, Z): {position}")

πŸ›« Takeoff & Landing with Flow Deck

mc.take_off(0.5)  # Takeoff to 0.5 meters using Flow Deck
mc.land()  # Land safely using Flow Deck

πŸ“ Position Control (Using Flow Deck)

mc.move_distance(x=0.5, y=0.0, z=0.0)  # Move forward 0.5 meters
mc.move_distance(x=0.0, y=0.5, z=0.0)  # Move right 0.5 meters
mc.move_distance(x=0.0, y=0.0, z=0.3)  # Move up 0.3 meters

πŸ”„ Flow Deck-Based Conditional Statements

πŸ”Ή Example: Stop Moving if Height is Too Low

altitude = mc.get_height()
if altitude < 0.2:
    print("Warning: Too low! Stopping movement.")
    mc.stop()

πŸ”Ή Example: Hover Until a Certain Height is Reached

while mc.get_height() < 0.5:
    print("Ascending...")
    mc.up(0.1)
    time.sleep(0.1)

print("Reached target altitude!")

πŸ”Ή Example: Move Only if Altitude is Safe

if mc.get_height() > 0.3:
    mc.move_distance(0.5, 0, 0)  # Move forward 0.5m
else:
    print("Altitude too low, not moving!")

🏁 Full Example: Smart Movement with Flow Deck

from crazyflie_controller import CrazyflieController
import time

drone = CrazyflieController()

try:
    drone.mc.take_off(0.5)  # Takeoff to 0.5m

    if drone.mc.get_height() > 0.3:
        drone.mc.move_distance(0.5, 0, 0)
        drone.mc.move_distance(0, 0.5, 0)
    else:
        print("Altitude too low! Adjusting height...")
        drone.mc.up(0.2)

    drone.mc.land()

except KeyboardInterrupt:
    print("Emergency stop activated!")

drone.close()

πŸš€ Now, you can use Flow Deck-powered movements and logic for safe and accurate Crazyflie flights!

πŸš€ Crazyflie Multi-Ranger Deck Commands & Conditional Statements

The Multi-Ranger Deck allows the Crazyflie drone to detect obstacles in five directions (front, back, left, right, up) using time-of-flight sensors. It enables collision avoidance, autonomous navigation, and environmental awareness.


πŸ“Œ Required Import for Multi-Ranger Deck

Before using Multi-Ranger Deck commands, ensure you import the Multiranger class:

from cflib.swarms.multiranger import Multiranger

πŸ“‘ Multi-Ranger Sensor Readings

You can read the distance measurements in meters from each direction.

ranger = Multiranger(drone.scf)  # Initialize Multi-Ranger sensor

πŸ”Ή Get Distance from Each Sensor

front_dist = ranger.front  # Distance to obstacle in front
back_dist = ranger.back    # Distance to obstacle in back
left_dist = ranger.left    # Distance to obstacle on the left
right_dist = ranger.right  # Distance to obstacle on the right
up_dist = ranger.up        # Distance to obstacle above

πŸ”Ή Example: Print All Sensor Readings

print(f"Front: {ranger.front} m, Back: {ranger.back} m")
print(f"Left: {ranger.left} m, Right: {ranger.right} m")
print(f"Up: {ranger.up} m")

🏎️ Autonomous Obstacle Avoidance

You can use if statements to make the drone react to obstacles.

πŸ”Ή Example: Stop if an Obstacle is Too Close

if ranger.front < 0.3:
    print("Obstacle ahead! Stopping.")
    mc.stop()

πŸ”Ή Example: Avoid Obstacles by Turning

if ranger.front < 0.3:
    print("Obstacle detected! Turning left.")
    mc.turn_left(45)  # Turn 45 degrees left

πŸ”Ή Example: Move Back if Blocked in Front

if ranger.front < 0.3 and ranger.back > 0.5:
    print("Obstacle ahead! Moving back.")
    mc.back(0.3)

πŸ”„ Multi-Ranger Conditional Loops

You can use while loops to continuously check sensor data and adjust movements.

πŸ”Ή Example: Fly Until an Obstacle is Detected

while ranger.front > 0.5:
    mc.forward(0.1)  # Move forward 10 cm
    time.sleep(0.1)

print("Obstacle detected! Stopping.")
mc.stop()

πŸ”Ή Example: Follow a Wall (Keep a Fixed Distance)

while True:
    if ranger.right > 0.4:  # If too far from the wall, move right
        mc.right(0.1)
    elif ranger.right < 0.3:  # If too close, move left
        mc.left(0.1)

    time.sleep(0.1)

πŸ”Ή Example: Hover and Avoid Obstacles Automatically

while True:
    if ranger.front < 0.3:
        mc.turn_left(45)  # Turn left if an obstacle is ahead
    elif ranger.left < 0.3:
        mc.turn_right(45)  # Turn right if too close to the left
    else:
        mc.forward(0.1)  # Otherwise, keep moving forward

    time.sleep(0.1)

🏁 Full Example: Smart Obstacle Avoidance with Multi-Ranger

from crazyflie_controller import CrazyflieController
from cflib.swarms.multiranger import Multiranger
import time

drone = CrazyflieController()
ranger = Multiranger(drone.scf)  # Initialize Multi-Ranger sensors

try:
    drone.mc.take_off(0.5)  # Takeoff to 0.5m

    while True:
        # If an obstacle is detected in front, turn left
        if ranger.front < 0.3:
            print("Obstacle ahead! Turning left.")
            drone.mc.turn_left(45)
        # If there's space, move forward
        elif ranger.front > 0.5:
            drone.mc.forward(0.1)
        
        # If it's too close to the left, turn right
        if ranger.left < 0.3:
            drone.mc.turn_right(45)

        time.sleep(0.1)

except KeyboardInterrupt:
    print("Emergency stop activated!")

drone.mc.land()  # Land safely
drone.close()

πŸ“œ Summary of Multi-Ranger Commands & Conditionals

Command Description
ranger.front Distance to the front obstacle (meters)
ranger.back Distance to the back obstacle
ranger.left Distance to the left obstacle
ranger.right Distance to the right obstacle
ranger.up Distance to an obstacle above
if ranger.front < X: Check if an object is closer than X meters
while ranger.front > X: Keep moving until an obstacle is closer than X meters
mc.turn_left(45) Turn left if an obstacle is detected
mc.forward(0.1) Move forward only if space is clear
mc.stop() Stop all motion when an obstacle is detected

πŸš€ Next Steps

  • Test these scripts to see how the drone reacts to obstacles.
  • Modify distance thresholds (0.3m, 0.5m, etc.) to fine-tune obstacle avoidance.
  • Combine with Flow Deck for even better autonomous navigation.

Now, you can use the Multi-Ranger Deck to avoid obstacles and navigate autonomously! πŸš€

Binder

About

Exercise Files for the DroneBlocks InnovatED STEM Air Land and Sea Course

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Jupyter Notebook 96.6%
  • Python 3.4%