📚 Quick Navigation
Table of Contents
- Getting Started
- Connection Functions
- Flight Commands
- Flight Sequences
- Flight Variables
- LED Functions
- Sound Functions
- Sensors - Range Sensor
- Sensors - Optical Flow Sensor
- Sensors - Gyroscope Sensor
- Sensors - Pressure Sensor
- Sensors - Color Sensor
- Sensors - State Data
- Controller Functions
- Screen Functions
- Best Practices
- Practice Questions
Getting Started
Installation
from codrone_edu.drone import *
drone = Drone()
Connection Functions
Basic Example
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(2)
drone.land()
drone.close()
pair()
Description
Connects your controller with the program. You can also set a specific USB port name for more reliable pairing.
Syntax
pair()
pair(portname)
Parameters
- portname (string, optional): A string containing the port name or number (e.g., 'COM3' on Windows, '/dev/ttyUSB0' on Linux/Mac)
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair() # Pair automatically (may not always work)
# drone.pair(port_name='COM3') # Pair with a specific port
drone.takeoff()
drone.hover(1)
drone.land()
drone.close()
Notes
- Automatic pairing may not always work; use specific port name for reliability
- On Windows, ports are typically 'COM1', 'COM2', etc.
- On Linux/Mac, ports are typically '/dev/ttyUSB0', '/dev/ttyUSB1', etc.
Flight Commands
close()
Description
Closes the connection between your controller and the program. Always call this function at the end of your program to properly disconnect.
Syntax
close()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(1)
drone.land()
drone.close() # Closes connection between controller and program
Notes
- Always call
close()at the end of your program - This ensures proper cleanup and disconnection
takeoff()
Description
Makes the drone take off at an average height of 80 centimeters and hover. The drone will always hover for 1 second to stabilize before executing the next command.
Syntax
takeoff()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff() # Takes off to ~80cm and hovers for 1 second
drone.hover(3)
drone.land()
drone.close()
Notes
- IMPORTANT: The takeoff height (80cm) cannot be modified
- The drone automatically hovers for 1 second after takeoff for stabilization
- Always include a
hover()ortime.sleep()beforeland()if taking off and immediately landing
land()
Description
Makes the drone stop all commands, hover, and make a soft landing at its current position. The function also resets all flight motion variables to 0.
Syntax
land()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(3) # Include hover() or time.sleep() to prevent land() from skipping
drone.land()
drone.close()
Notes
- IMPORTANT: If you want to take off and immediately land, include a
hover()ortime.sleep()betweentakeoff()andland(), otherwise the CoDrone EDU may miss the land command - Resets all flight motion variables to 0
- Performs a soft landing at current position
emergency_stop()
Description
Immediately stops all commands and motors, causing the drone to stop flying instantly. The function also resets all flight motion variables to 0. Use this for emergency situations.
Syntax
emergency_stop()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(3) # Recommended to have hover() or time.sleep(1) before emergency_stop
drone.emergency_stop()
drone.close()
Notes
- WARNING: This immediately stops all motors - the drone will drop
- Use only in emergency situations
- Recommended to include
hover()ortime.sleep()before calling this function - Resets all flight motion variables to 0
hover()
Description
Makes the drone hover for a specified amount of time. If no parameters are given, it will hover indefinitely until given another command.
Syntax
hover()
hover(duration)
Parameters
- duration (integer, optional): Duration of hovering in seconds. If not provided, hovers indefinitely.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(3) # Hover for 3 seconds
drone.hover() # Hover indefinitely until next command
drone.land()
drone.close()
Notes
- Without parameters, the drone hovers until the next command
- Useful for stabilization between flight commands
- Always include
hover()ortime.sleep()beforeland()oremergency_stop()
go()
Description
A beginner-friendly function that allows the drone to move in a given direction at a specified power level for a specified duration.
Syntax
go(direction, power=50, duration=1)
Parameters
- direction (string, required): The direction of movement. Options: "forward", "backward", "left", "right", "up", "down"
- power (int, optional): The power at which the drone flies (0-100). Defaults to 50% if not defined.
- duration (float, optional): The duration of the movement in seconds. Defaults to 1 second if not defined.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
# Move in different directions
drone.go("forward", 30, 1) # Move forward at 30% power for 1 second
drone.go("backward", 30, 1) # Move backward at 30% power for 1 second
drone.go("right", 30, 1) # Move right at 30% power for 1 second
drone.go("left", 30, 1) # Move left at 30% power for 1 second
drone.go("up", 40, 0.5) # Move up at 40% power for 0.5 seconds
drone.go("down", 40, 0.5) # Move down at 40% power for 0.5 seconds
drone.land()
drone.close()
Notes
- Power range: 0-100 (0 = no movement, 100 = maximum power)
- Duration can be a float (e.g., 0.5, 1.5, 2.3)
- Simple and beginner-friendly movement function
avoid_wall()
Description
A looped method that makes the drone fly forward until it reaches a desired distance from an object based on the front range sensor. The range of the front sensor is from 0cm to 100cm.
Syntax
avoid_wall()
avoid_wall(timeout)
avoid_wall(distance)
avoid_wall(timeout, distance)
Parameters
- timeout (integer, optional): Duration in seconds that the function will run. Default value is 2 seconds.
- distance (integer, optional): Distance in centimeters the drone will stop at in front of an object. Default value is 70cm.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
# Fly forward until a wall is found 50cm away. Run this loop for 10 seconds.
drone.avoid_wall(10, 50)
drone.land()
drone.close()
Notes
- Front range sensor range: 0-100cm
- Function runs in a loop until timeout is reached or distance is achieved
- Useful for obstacle avoidance
keep_distance()
Description
A looped method that makes the drone fly forward until it reaches a desired distance. Once the desired distance is reached, the drone will maintain that distance. The sensor range is up to 150cm.
Syntax
keep_distance()
keep_distance(timeout)
keep_distance(distance)
keep_distance(timeout, distance)
Parameters
- timeout (integer, optional): Duration in seconds that the function will execute. Default value is 2 seconds.
- distance (integer, optional): Distance in centimeters the drone will stop and maintain distance in front of an object. Default value is 50 centimeters.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
# Maintain a distance of 60cm from an object once detected for 10 seconds
drone.keep_distance(10, 60)
drone.land()
drone.close()
Notes
- Sensor range: up to 150cm
- Drone maintains distance once reached
- Useful for following objects or maintaining position
get_trim()
Description
Gets the current trim values for pitch, roll, and yaw. Trim values help adjust the drone's balance and stability.
Syntax
get_trim()
Parameters
None
Returns
tuple: A tuple containing (pitch_trim, roll_trim, yaw_trim)
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
# Get current trim values
pitch, roll, yaw = drone.get_trim()
print(f"Pitch: {pitch}, Roll: {roll}, Yaw: {yaw}")
drone.close()
Flight Sequences
reset_trim()
Description
Resets all trim values (pitch, roll, yaw) to 0.
Syntax
reset_trim()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.reset_trim() # Reset all trim values to 0
drone.close()
set_trim()
Description
Sets the trim values for pitch, roll, and yaw to adjust the drone's balance and stability.
Syntax
set_trim(pitch, roll, yaw)
Parameters
- pitch (integer): Pitch trim value (-100 to 100)
- roll (integer): Roll trim value (-100 to 100)
- yaw (integer): Yaw trim value (-100 to 100)
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
# Set trim values to adjust balance
drone.set_trim(10, -5, 0) # Pitch: 10, Roll: -5, Yaw: 0
drone.close()
move_forward()
Description
Moves the drone forward at a specified power for a specified duration.
Syntax
move_forward(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.move_forward(50, 2) # Move forward at 50% power for 2 seconds
drone.land()
drone.close()
Flight Variables
move_backward()
Description
Moves the drone backward at a specified power for a specified duration.
Syntax
move_backward(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.move_backward(50, 2) # Move backward at 50% power for 2 seconds
drone.land()
drone.close()
move_left()
Description
Moves the drone left at a specified power for a specified duration.
Syntax
move_left(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.move_left(50, 2) # Move left at 50% power for 2 seconds
drone.land()
drone.close()
move_right()
Description
Moves the drone right at a specified power for a specified duration.
Syntax
move_right(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.move_right(50, 2) # Move right at 50% power for 2 seconds
drone.land()
drone.close()
move_distance()
Description
Moves the drone a specific distance in a specific direction.
Syntax
move_distance(direction, distance, power=50)
Parameters
- direction (string): Direction ("forward", "backward", "left", "right", "up", "down")
- distance (float): Distance in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.move_distance("forward", 100, 50) # Move forward 100cm at 50% power
drone.land()
drone.close()
send_absolute_position()
Description
Sends the drone to an absolute position using x, y, z coordinates.
Syntax
send_absolute_position(x, y, z, power=50)
Parameters
- x (float): X position in centimeters
- y (float): Y position in centimeters
- z (float): Z position (height) in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.send_absolute_position(50, 30, 80, 50) # Move to position (50, 30, 80)
drone.land()
drone.close()
LED Functions
turn()
Description
Turns the drone a specified number of degrees.
Syntax
turn(direction, degrees, power=50)
Parameters
- direction (string): "left" or "right"
- degrees (float): Number of degrees to turn
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.turn("right", 90, 50) # Turn right 90 degrees at 50% power
drone.land()
drone.close()
turn_degree()
Description
Turns the drone a specified number of degrees using the gyroscope for accuracy.
Syntax
turn_degree(degrees, power=50)
Parameters
- degrees (float): Number of degrees to turn (positive = right, negative = left)
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.turn_degree(90, 50) # Turn right 90 degrees
drone.turn_degree(-90, 50) # Turn left 90 degrees
drone.land()
drone.close()
turn_left()
Description
Turns the drone left at a specified power for a specified duration.
Syntax
turn_left(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.turn_left(50, 1) # Turn left at 50% power for 1 second
drone.land()
drone.close()
Sound Functions
turn_right()
Description
Turns the drone right at a specified power for a specified duration.
Syntax
turn_right(power, duration)
Parameters
- power (integer): Power level (0-100)
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.turn_right(50, 1) # Turn right at 50% power for 1 second
drone.land()
drone.close()
circle()
Description
Makes the drone fly in a circle pattern.
Syntax
circle(radius, power=50, duration=5)
Parameters
- radius (float): Radius of the circle in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
- duration (float, optional): Duration in seconds. Default is 5.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.circle(100, 50, 5) # Fly in a circle with 100cm radius
drone.land()
drone.close()
flip()
Description
Makes the drone perform a flip in a specified direction.
Syntax
flip(direction)
Parameters
- direction (string): Direction of flip ("forward", "backward", "left", "right")
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.flip("forward") # Perform a forward flip
drone.hover(2)
drone.land()
drone.close()
Notes
- Ensure adequate height before performing flips
- Flips require sufficient battery power
spiral()
Description
Makes the drone fly in a spiral pattern.
Syntax
spiral(radius, height, power=50, duration=5)
Parameters
- radius (float): Starting radius in centimeters
- height (float): Height change in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
- duration (float, optional): Duration in seconds. Default is 5.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.spiral(50, 30, 50, 5) # Spiral with 50cm radius, 30cm height change
drone.land()
drone.close()
square()
Description
Makes the drone fly in a square pattern.
Syntax
square(side_length, power=50)
Parameters
- side_length (float): Length of each side in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.square(100, 50) # Fly in a square with 100cm sides
drone.land()
drone.close()
Sensors - Range Sensor
sway()
Description
Makes the drone sway back and forth in a specified direction.
Syntax
sway(direction, distance, power=50, duration=5)
Parameters
- direction (string): Direction of sway ("left", "right", "forward", "backward")
- distance (float): Distance of sway in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
- duration (float, optional): Duration in seconds. Default is 5.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.sway("left", 50, 50, 5) # Sway left and right 50cm
drone.land()
drone.close()
triangle()
Description
Makes the drone fly in a triangle pattern.
Syntax
triangle(side_length, power=50)
Parameters
- side_length (float): Length of each side in centimeters
- power (integer, optional): Power level (0-100). Default is 50.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.triangle(100, 50) # Fly in a triangle with 100cm sides
drone.land()
drone.close()
Sensors - Optical Flow Sensor
get_move_values()
Description
Gets the current movement values for pitch, roll, throttle, and yaw.
Syntax
get_move_values()
Parameters
None
Returns
tuple: A tuple containing (pitch, roll, throttle, yaw)
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
pitch, roll, throttle, yaw = drone.get_move_values()
print(f"Pitch: {pitch}, Roll: {roll}, Throttle: {throttle}, Yaw: {yaw}")
drone.close()
move()
Description
Moves the drone using the current movement values set by set_pitch(), set_roll(), set_throttle(), and set_yaw().
Syntax
move(duration)
Parameters
- duration (float): Duration in seconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(30)
drone.set_roll(0)
drone.set_throttle(0)
drone.set_yaw(0)
drone.move(2) # Move for 2 seconds with set values
drone.land()
drone.close()
print_move_values()
Description
Prints the current movement values to the console.
Syntax
print_move_values()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.set_pitch(30)
drone.print_move_values() # Prints current movement values
drone.close()
reset_move()
Description
Resets all movement values to 0 and stops the drone.
Syntax
reset_move()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(30)
drone.move(2)
drone.reset_move() # Reset and stop
drone.land()
drone.close()
Sensors - Gyroscope Sensor
reset_move_values()
Description
Resets all movement values (pitch, roll, throttle, yaw) to 0 without stopping the drone.
Syntax
reset_move_values()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(30)
drone.move(2)
drone.reset_move_values() # Reset values to 0
drone.land()
drone.close()
set_pitch()
Description
Sets the pitch value for forward/backward movement (-100 to 100).
Syntax
set_pitch(value)
Parameters
- value (integer): Pitch value (-100 to 100). Positive = forward, Negative = backward.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(30) # Set forward pitch
drone.set_roll(0)
drone.set_throttle(0)
drone.set_yaw(0)
drone.move(2)
drone.land()
drone.close()
set_roll()
Description
Sets the roll value for left/right movement (-100 to 100).
Syntax
set_roll(value)
Parameters
- value (integer): Roll value (-100 to 100). Positive = right, Negative = left.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(0)
drone.set_roll(30) # Set right roll
drone.set_throttle(0)
drone.set_yaw(0)
drone.move(2)
drone.land()
drone.close()
set_throttle()
Description
Sets the throttle value for up/down movement (-100 to 100).
Syntax
set_throttle(value)
Parameters
- value (integer): Throttle value (-100 to 100). Positive = up, Negative = down.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(0)
drone.set_roll(0)
drone.set_throttle(30) # Set upward throttle
drone.set_yaw(0)
drone.move(2)
drone.land()
drone.close()
set_yaw()
Description
Sets the yaw value for rotation (-100 to 100).
Syntax
set_yaw(value)
Parameters
- value (integer): Yaw value (-100 to 100). Positive = rotate right, Negative = rotate left.
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_pitch(0)
drone.set_roll(0)
drone.set_throttle(0)
drone.set_yaw(30) # Set right rotation
drone.move(2)
drone.land()
drone.close()
controller_LED_off()
Description
Turns off the controller LED.
Syntax
controller_LED_off()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.set_controller_LED(255, 0, 0, 100) # Red LED
time.sleep(2)
drone.controller_LED_off() # Turn off LED
drone.close()
drone_LED_off()
Description
Turns off the drone LED.
Syntax
drone_LED_off()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.set_drone_LED(0, 255, 0, 100) # Green LED
time.sleep(2)
drone.drone_LED_off() # Turn off LED
drone.close()
set_controller_LED()
Description
Sets the controller LED color using RGB values and brightness.
Syntax
set_controller_LED(r, g, b, brightness)
Parameters
- r (integer): Red value (0-255)
- g (integer): Green value (0-255)
- b (integer): Blue value (0-255)
- brightness (integer): Brightness level (0-100)
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
# Set controller LED to red at 100% brightness
drone.set_controller_LED(255, 0, 0, 100)
time.sleep(2)
# Set controller LED to blue at 50% brightness
drone.set_controller_LED(0, 0, 255, 50)
drone.close()
Sensors - Pressure Sensor
set_drone_LED()
Description
Sets the drone LED color using RGB values and brightness.
Syntax
set_drone_LED(r, g, b, brightness)
Parameters
- r (integer): Red value (0-255)
- g (integer): Green value (0-255)
- b (integer): Blue value (0-255)
- brightness (integer): Brightness level (0-100)
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
# Set drone LED to green at 100% brightness
drone.set_drone_LED(0, 255, 0, 100)
time.sleep(2)
drone.land()
drone.close()
set_controller_LED_mode()
Description
Sets the controller LED mode (solid, blink, etc.).
Syntax
set_controller_LED_mode(mode)
Parameters
- mode (integer): LED mode value
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.set_controller_LED(255, 0, 0, 100)
drone.set_controller_LED_mode(1) # Set to blink mode
drone.close()
set_drone_LED_mode()
Description
Sets the drone LED mode (solid, blink, etc.).
Syntax
set_drone_LED_mode(mode)
Parameters
- mode (integer): LED mode value
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.set_drone_LED(0, 255, 0, 100)
drone.set_drone_LED_mode(1) # Set to blink mode
drone.land()
drone.close()
Sensors - Color Sensor
controller_buzzer()
Description
Plays a buzzer sound on the controller for a specified duration and frequency.
Syntax
controller_buzzer(frequency, duration)
Parameters
- frequency (integer): Frequency in Hz
- duration (integer): Duration in milliseconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.controller_buzzer(440, 500) # Play 440Hz for 500ms
drone.close()
drone_buzzer()
Description
Plays a buzzer sound on the drone for a specified duration and frequency.
Syntax
drone_buzzer(frequency, duration)
Parameters
- frequency (integer): Frequency in Hz
- duration (integer): Duration in milliseconds
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.drone_buzzer(440, 500) # Play 440Hz for 500ms
drone.land()
drone.close()
start_drone_buzzer()
Description
Starts the drone buzzer continuously.
Syntax
start_drone_buzzer(frequency)
Parameters
- frequency (integer): Frequency in Hz
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.start_drone_buzzer(440) # Start continuous buzzer
time.sleep(2)
drone.stop_drone_buzzer() # Stop buzzer
drone.land()
drone.close()
stop_drone_buzzer()
Description
Stops the drone buzzer.
Syntax
stop_drone_buzzer()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.start_drone_buzzer(440)
time.sleep(2)
drone.stop_drone_buzzer() # Stop buzzer
drone.land()
drone.close()
start_controller_buzzer()
Description
Starts the controller buzzer continuously.
Syntax
start_controller_buzzer(frequency)
Parameters
- frequency (integer): Frequency in Hz
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.start_controller_buzzer(440) # Start continuous buzzer
time.sleep(2)
drone.stop_controller_buzzer() # Stop buzzer
drone.close()
Sensors - State Data
stop_controller_buzzer()
Description
Stops the controller buzzer.
Syntax
stop_controller_buzzer()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.start_controller_buzzer(440)
time.sleep(2)
drone.stop_controller_buzzer() # Stop buzzer
drone.close()
drone_buzzer_sequence()
Description
Plays a sequence of buzzer tones on the drone.
Syntax
drone_buzzer_sequence(sequence)
Parameters
- sequence (list): List of tuples containing (frequency, duration) pairs
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
# Play a sequence of notes
sequence = [(440, 200), (494, 200), (523, 200)]
drone.drone_buzzer_sequence(sequence)
drone.close()
Controller Functions
controller_buzzer_sequence()
Description
Plays a sequence of buzzer tones on the controller.
Syntax
controller_buzzer_sequence(sequence)
Parameters
- sequence (list): List of tuples containing (frequency, duration) pairs
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
# Play a sequence of notes
sequence = [(440, 200), (494, 200), (523, 200)]
drone.controller_buzzer_sequence(sequence)
drone.close()
ping()
Description
Plays a ping sound on the controller.
Syntax
ping()
Parameters
None
Returns
None
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.ping() # Play ping sound
drone.close()
detect_wall()
Description
Detects if there is a wall in front of the drone within a specified distance.
Syntax
detect_wall(distance=70)
Parameters
- distance (integer, optional): Distance threshold in centimeters. Default is 70cm.
Returns
boolean: True if wall detected, False otherwise
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
if drone.detect_wall(50): # Check if wall within 50cm
print("Wall detected!")
drone.turn_right(50, 1)
drone.land()
drone.close()
get_bottom_range()
Description
Gets the distance reading from the bottom range sensor in centimeters.
Syntax
get_bottom_range()
Parameters
None
Returns
float: Distance in centimeters (0-100cm range)
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
distance = drone.get_bottom_range()
print(f"Bottom range: {distance} cm")
drone.land()
drone.close()
get_front_range()
Description
Gets the distance reading from the front range sensor in centimeters.
Syntax
get_front_range()
Parameters
None
Returns
float: Distance in centimeters (0-100cm range)
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
distance = drone.get_front_range()
print(f"Front range: {distance} cm")
drone.land()
drone.close()
get_height()
Description
Gets the height of the drone using the bottom range sensor.
Syntax
get_height()
Parameters
None
Returns
float: Height in centimeters
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
height = drone.get_height()
print(f"Height: {height} cm")
drone.land()
drone.close()
get_pos_x()
Description
Gets the X position from the optical flow sensor.
Syntax
get_pos_x()
Parameters
None
Returns
float: X position value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
x_pos = drone.get_pos_x()
print(f"X position: {x_pos}")
drone.close()
get_pos_y()
Description
Gets the Y position from the optical flow sensor.
Syntax
get_pos_y()
Parameters
None
Returns
float: Y position value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
y_pos = drone.get_pos_y()
print(f"Y position: {y_pos}")
drone.close()
get_pos_z()
Description
Gets the Z position (height) from the optical flow sensor.
Syntax
get_pos_z()
Parameters
None
Returns
float: Z position (height) value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
z_pos = drone.get_pos_z()
print(f"Z position: {z_pos}")
drone.close()
Screen Functions
get_flow_velocity_x()
Description
Gets the X velocity from the optical flow sensor.
Syntax
get_flow_velocity_x()
Parameters
None
Returns
float: X velocity value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
velocity_x = drone.get_flow_velocity_x()
print(f"X velocity: {velocity_x}")
drone.close()
get_flow_velocity_y()
Description
Gets the Y velocity from the optical flow sensor.
Syntax
get_flow_velocity_y()
Parameters
None
Returns
float: Y velocity value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
velocity_y = drone.get_flow_velocity_y()
print(f"Y velocity: {velocity_y}")
drone.close()
get_flow_x()
Description
Gets the X flow value from the optical flow sensor.
Syntax
get_flow_x()
Parameters
None
Returns
float: X flow value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
flow_x = drone.get_flow_x()
print(f"X flow: {flow_x}")
drone.close()
get_flow_y()
Description
Gets the Y flow value from the optical flow sensor.
Syntax
get_flow_y()
Parameters
None
Returns
float: Y flow value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
flow_y = drone.get_flow_y()
print(f"Y flow: {flow_y}")
drone.close()
get_position_data()
Description
Gets all position data from the optical flow sensor.
Syntax
get_position_data()
Parameters
None
Returns
dict: Dictionary containing position data (x, y, z, velocity_x, velocity_y, etc.)
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
data = drone.get_position_data()
print(f"Position data: {data}")
drone.close()
get_accel_x()
Description
Gets the X-axis acceleration from the gyroscope sensor.
Syntax
get_accel_x()
Parameters
None
Returns
float: X-axis acceleration value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
accel_x = drone.get_accel_x()
print(f"X acceleration: {accel_x}")
drone.close()
get_accel_y()
Description
Gets the Y-axis acceleration from the gyroscope sensor.
Syntax
get_accel_y()
Parameters
None
Returns
float: Y-axis acceleration value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
accel_y = drone.get_accel_y()
print(f"Y acceleration: {accel_y}")
drone.close()
get_accel_z()
Description
Gets the Z-axis acceleration from the gyroscope sensor.
Syntax
get_accel_z()
Parameters
None
Returns
float: Z-axis acceleration value
Example Code
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
accel_z = drone.get_accel_z()
print(f"Z acceleration: {accel_z}")
drone.close()
Best Practices
This section covers essential methods and practices for coding drones effectively. Follow these guidelines to write safe, reliable, and maintainable drone code.
1. Connection and Setup Best Practices
Proper connection handling is crucial for reliable drone operations. Always follow these practices:
Always Use Try-Except Blocks
Wrap connection and flight operations in try-except blocks to handle errors gracefully:
from codrone_edu.drone import *
import time
drone = Drone()
try:
# Attempt to pair with the drone
drone.pair()
print("Successfully paired with drone")
# Your flight code here
drone.takeoff()
drone.hover(2)
drone.land()
except Exception as e:
print(f"Error occurred: {e}")
finally:
# Always close the connection, even if an error occurred
try:
drone.close()
print("Connection closed")
except:
pass
Verify Connection Before Flight
Always check that the connection is established before attempting flight operations:
from codrone_edu.drone import *
drone = Drone()
# Pair with specific port for reliability
try:
drone.pair()
# Check battery level as a connection verification
battery = drone.get_battery()
if battery < 20:
print(f"Warning: Low battery ({battery}%)")
# Consider not flying if battery is too low
else:
print(f"Battery level: {battery}% - Ready to fly")
drone.takeoff()
except Exception as e:
print(f"Connection failed: {e}")
finally:
drone.close()
Task:
Create a function that safely connects to a drone and checks the battery level before allowing flight operations.
Requirements:
- Use try-except-finally blocks
- Check battery level and only allow flight if battery is above 30%
- Print appropriate messages for each step
- Always close the connection in the finally block
Solution Template:
def safe_connect(drone):
# Your code here
pass
2. Flight Control Best Practices
Proper flight control ensures safe and predictable drone behavior:
Always Include Hover Between Commands
Add hover time between flight commands to allow the drone to stabilize:
from codrone_edu.drone import *
import time
drone = Drone()
drone.pair()
drone.takeoff()
# Always hover after takeoff to stabilize
drone.hover(1)
# Move forward
drone.go("forward", 50, 2)
# Hover to stabilize before next command
drone.hover(0.5)
# Turn right
drone.turn("right", 90, 50)
drone.hover(0.5)
# Always hover before landing
drone.hover(1)
drone.land()
drone.close()
Use Appropriate Power Levels
Start with lower power levels (30-50%) for safer flights, especially when learning:
from codrone_edu.drone import *
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(1)
# Use moderate power for safer, more controlled flight
POWER_LEVEL = 40 # 40% power - good for indoor/learning
drone.go("forward", POWER_LEVEL, 1)
drone.hover(0.5)
drone.go("backward", POWER_LEVEL, 1)
drone.hover(1)
drone.land()
drone.close()
Task:
Create a function that makes the drone fly in a square pattern with proper hover times between each movement.
Requirements:
- Use a power level between 30-50%
- Include 0.5 second hover between each movement
- Fly forward, right, backward, left to complete a square
- Always hover before landing
Solution Template:
def fly_square(drone, side_length, power=40):
# Your code here
pass
3. Sensor Usage Best Practices
Proper sensor usage enables autonomous and safe flight operations:
Read Sensors Multiple Times for Accuracy
Sensor readings can vary; take multiple readings and average them for more reliable data:
from codrone_edu.drone import *
import time
def get_average_range(drone, num_readings=5):
"""Get average front range sensor reading for better accuracy"""
readings = []
for _ in range(num_readings):
readings.append(drone.get_front_range())
time.sleep(0.1) # Small delay between readings
return sum(readings) / len(readings)
drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(1)
# Get average distance reading
distance = get_average_range(drone)
print(f"Average distance: {distance:.2f} cm")
# Use sensor data for decision making
if distance < 50:
print("Object detected! Turning right...")
drone.turn("right", 90, 50)
else:
print("Path clear, moving forward...")
drone.go("forward", 40, 1)
drone.hover(1)
drone.land()
drone.close()
Use Sensor Thresholds for Decision Making
Define clear thresholds for sensor-based decisions to avoid erratic behavior:
from codrone_edu.drone import *
import time
# Define sensor thresholds as constants
WALL_DETECTION_DISTANCE = 50 # cm - distance to detect wall
SAFE_DISTANCE = 70 # cm - safe distance to maintain
LOW_BATTERY_THRESHOLD = 20 # % - battery level to trigger landing
drone = Drone()
drone.pair()
# Check battery before flight
battery = drone.get_battery()
if battery < LOW_BATTERY_THRESHOLD:
print(f"Battery too low: {battery}%. Cannot fly.")
drone.close()
exit()
drone.takeoff()
drone.hover(1)
# Use sensor-based obstacle avoidance
for i in range(10): # Try 10 times
distance = drone.get_front_range()
if distance < WALL_DETECTION_DISTANCE:
print(f"Wall detected at {distance}cm. Turning...")
drone.turn("right", 90, 50)
drone.hover(0.5)
elif distance >= SAFE_DISTANCE:
drone.go("forward", 40, 0.5)
drone.hover(0.3)
# Check battery during flight
battery = drone.get_battery()
if battery < LOW_BATTERY_THRESHOLD:
print("Low battery detected. Landing...")
break
drone.hover(1)
drone.land()
drone.close()
Task:
Create an obstacle avoidance function that uses the front range sensor to navigate around obstacles.
Requirements:
- Use sensor thresholds (wall detection at 50cm, safe distance at 70cm)
- Take multiple sensor readings and average them
- Turn right when obstacle detected, move forward when path is clear
- Include battery check and emergency landing if battery drops below 20%
Solution Template:
def obstacle_avoidance(drone, duration=30):
# Your code here
pass
4. Error Handling Best Practices
Robust error handling ensures your drone code can recover from unexpected situations:
Implement Emergency Stop Function
Always have an emergency stop mechanism available:
from codrone_edu.drone import *
import time
import signal
import sys
drone = Drone()
def emergency_landing(signal=None, frame=None):
"""Emergency landing function - can be called on Ctrl+C or error"""
print("\n⚠️ EMERGENCY LANDING INITIATED")
try:
drone.hover(0.5)
drone.land()
drone.close()
except:
pass
sys.exit(0)
# Register signal handler for Ctrl+C
signal.signal(signal.SIGINT, emergency_landing)
try:
drone.pair()
drone.takeoff()
drone.hover(1)
# Your flight code here
# If something goes wrong, emergency_landing() will be called
drone.hover(1)
drone.land()
except KeyboardInterrupt:
emergency_landing()
except Exception as e:
print(f"Error: {e}")
emergency_landing()
finally:
try:
drone.close()
except:
pass
Validate Sensor Data Before Use
Always validate sensor readings to ensure they're within expected ranges:
from codrone_edu.drone import *
def get_valid_range(drone, max_attempts=5):
"""Get a valid range sensor reading (0-100cm)"""
for attempt in range(max_attempts):
try:
distance = drone.get_front_range()
# Validate reading is within sensor range (0-100cm)
if 0 <= distance <= 100:
return distance
else:
print(f"Invalid reading: {distance}. Retrying...")
except Exception as e:
print(f"Error reading sensor: {e}")
# If all attempts failed, return a safe default
print("Warning: Could not get valid sensor reading. Using default.")
return 100 # Safe default - assume no obstacle
drone = Drone()
drone.pair()
# Use validated sensor reading
distance = get_valid_range(drone)
print(f"Validated distance: {distance} cm")
drone.close()
Task:
Create a robust flight function with comprehensive error handling including emergency landing, sensor validation, and battery monitoring.
Requirements:
- Implement emergency landing function that can be triggered by Ctrl+C
- Validate all sensor readings before using them
- Monitor battery level and land if it drops below 20%
- Use try-except-finally blocks for all critical operations
Solution Template:
def safe_flight_sequence(drone):
# Your code here with error handling
pass
5. Code Organization Best Practices
Well-organized code is easier to maintain, debug, and extend:
Use Functions to Organize Code
Break your code into logical functions for better organization:
from codrone_edu.drone import *
import time
# Configuration constants
POWER_LEVEL = 40
HOVER_TIME = 1
SAFE_DISTANCE = 50
def initialize_drone():
"""Initialize and pair with the drone"""
drone = Drone()
drone.pair()
return drone
def check_preflight(drone):
"""Check if drone is ready for flight"""
battery = drone.get_battery()
if battery < 30:
return False, f"Battery too low: {battery}%"
return True, f"Ready to fly. Battery: {battery}%"
def fly_pattern(drone):
"""Execute a flight pattern"""
drone.takeoff()
drone.hover(HOVER_TIME)
# Square pattern
for direction in ["forward", "right", "backward", "left"]:
drone.go(direction, POWER_LEVEL, 1)
drone.hover(0.5)
drone.hover(HOVER_TIME)
drone.land()
def main():
"""Main program entry point"""
drone = None
try:
drone = initialize_drone()
ready, message = check_preflight(drone)
print(message)
if ready:
fly_pattern(drone)
except Exception as e:
print(f"Error: {e}")
finally:
if drone:
drone.close()
if __name__ == "__main__":
main()
Use Constants for Configuration
Define constants at the top of your file for easy configuration:
from codrone_edu.drone import *
# ===== CONFIGURATION CONSTANTS =====
# Flight Parameters
DEFAULT_POWER = 40 # Power level (0-100)
DEFAULT_HOVER_TIME = 1 # Seconds to hover between commands
MOVEMENT_DURATION = 1 # Seconds for movement commands
# Sensor Thresholds
WALL_DETECTION_DISTANCE = 50 # cm
SAFE_DISTANCE = 70 # cm
SENSOR_READINGS = 5 # Number of readings to average
# Safety Thresholds
MIN_BATTERY_LEVEL = 30 # Minimum battery % to fly
EMERGENCY_BATTERY = 20 # Battery % to trigger emergency landing
# Connection
PAIR_TIMEOUT = 10 # Seconds to wait for pairing
# Use constants throughout your code
drone = Drone()
drone.pair()
battery = drone.get_battery()
if battery >= MIN_BATTERY_LEVEL:
drone.takeoff()
drone.hover(DEFAULT_HOVER_TIME)
drone.go("forward", DEFAULT_POWER, MOVEMENT_DURATION)
drone.hover(DEFAULT_HOVER_TIME)
drone.land()
drone.close()
Task:
Refactor a simple flight program into well-organized functions with proper constants and error handling.
Requirements:
- Create separate functions for initialization, preflight checks, flight pattern, and cleanup
- Define all configuration values as constants at the top
- Use a main() function as the entry point
- Include proper error handling in each function
Solution Template:
# Constants
# ... your constants here ...
# Functions
# ... your functions here ...
# Main program
if __name__ == "__main__":
# ... your main code here ...
6. Safety Best Practices
Safety should always be the top priority when programming drones:
Always Check Battery Before Flight
Never fly with low battery - it can cause unexpected behavior:
from codrone_edu.drone import *
def safe_takeoff(drone, min_battery=30):
"""Safely take off only if battery is sufficient"""
battery = drone.get_battery()
if battery < min_battery:
print(f"⚠️ Battery too low: {battery}%. Minimum required: {min_battery}%")
return False
print(f"✅ Battery OK: {battery}%. Taking off...")
drone.takeoff()
drone.hover(1)
return True
drone = Drone()
drone.pair()
if safe_takeoff(drone):
# Your flight code here
drone.hover(1)
drone.land()
else:
print("Flight cancelled due to low battery")
drone.close()
Test in Safe Environment First
Always test your code in a safe, controlled environment before attempting complex maneuvers:
from codrone_edu.drone import *
def test_flight(drone):
"""Simple test flight to verify drone is working correctly"""
print("Starting test flight...")
# Take off and hover - verify stability
drone.takeoff()
drone.hover(2)
print("✅ Hover test passed")
# Test basic movement - low power, short duration
drone.go("forward", 30, 0.5)
drone.hover(1)
print("✅ Movement test passed")
# Test landing
drone.hover(1)
drone.land()
print("✅ Landing test passed")
print("✅ All tests passed - drone is ready for complex maneuvers")
drone = Drone()
drone.pair()
# Always run test flight first
test_flight(drone)
# Only proceed with complex code if test passes
# ... your complex flight code here ...
drone.close()
Task:
Create a comprehensive safety checklist function that validates all conditions before allowing flight.
Requirements:
- Check battery level (must be > 30%)
- Verify connection is established
- Test basic hover before complex maneuvers
- Include emergency stop capability
- Return True only if all checks pass
Solution Template:
def safety_checklist(drone):
# Your safety checks here
return True # or False
Summary
Following these best practices will help you write safer, more reliable, and maintainable drone code:
- Connection: Always use try-except-finally blocks and verify connections
- Flight Control: Include hover times between commands and use appropriate power levels
- Sensors: Take multiple readings, validate data, and use clear thresholds
- Error Handling: Implement emergency stops and validate all inputs
- Code Organization: Use functions and constants for better maintainability
- Safety: Always check battery, test in safe environments, and have emergency procedures
Remember: Safety first! Always test your code in a controlled environment before attempting complex maneuvers.