CoDrone EDU Python Function Documentation

Version: 2.6 | Last Updated: 2024

Source: Robolink Documentation

📚 Best Practices Guide | ⚙️ Configuration Practices Guide | 📅 Upcoming Events

Table of Contents

  1. Getting Started
  2. Connection Functions
  3. Flight Commands
  4. Flight Sequences
  5. Flight Variables
  6. LED Functions
  7. Sound Functions
  8. Sensors - Range Sensor
  9. Sensors - Optical Flow Sensor
  10. Sensors - Gyroscope Sensor
  11. Sensors - Pressure Sensor
  12. Sensors - Color Sensor
  13. Sensors - State Data
  14. Controller Functions
  15. Screen Functions
  16. Best Practices
  17. 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() or time.sleep() before land() 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() or time.sleep() between takeoff() and land(), 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() or time.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() or time.sleep() before land() or emergency_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()

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()
📝 Practice Assignment: Connection Handling
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()
📝 Practice Assignment: Flight Pattern
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()
📝 Practice Assignment: Obstacle Avoidance
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()
📝 Practice Assignment: Error Handling
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()
📝 Practice Assignment: Code Organization
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()
📝 Practice Assignment: Safety Checklist
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.


Practice Questions

Test your understanding of CoDrone EDU programming with these 35 practice questions. Click on each question to expand and see the answer. Try to answer each question before checking the solution!

Q1 What is the first function you should call after creating a Drone object?

Answer: The pair() function should be called first to establish a connection between your program and the drone controller.

Example:

drone = Drone()
drone.pair()  # First function to call
Q2 Why should you always call close() at the end of your program?

Answer: The close() function properly disconnects the connection between your program and the controller. It ensures proper cleanup and prevents connection issues in future runs.

Q3 What happens if you call land() immediately after takeoff() without any delay?

Answer: The drone may miss the land() command because it needs time to stabilize after takeoff. Always include hover() or time.sleep() between takeoff() and land().

Q4 What is the default takeoff height for the CoDrone EDU?

Answer: The default takeoff height is approximately 80 centimeters. This height cannot be modified.

Q5 What is the difference between go() and move_forward()?

Answer: go() is a beginner-friendly function that accepts a direction string ("forward", "backward", etc.), power, and duration. move_forward() is more specific and only moves forward with power and duration parameters.

Q6 What power level range should you use for safe indoor flights?

Answer: For safe indoor flights, use power levels between 30-50%. Higher power levels (70-100%) are better suited for outdoor flights with more space.

Q7 How do you make the drone hover indefinitely?

Answer: Call hover() without any parameters. The drone will hover until it receives the next command.

Example:

drone.hover()  # Hovers indefinitely
Q8 What is the purpose of the avoid_wall() function?

Answer: avoid_wall() makes the drone fly forward until it reaches a specified distance from an object (detected by the front range sensor). It's useful for obstacle avoidance.

Q9 What is the range of the front range sensor?

Answer: The front range sensor has a range of 0-100 centimeters.

Q10 How do you check the battery level of the drone?

Answer: Use the get_battery() function, which returns a value from 0-100 representing the battery percentage.

Example:

battery = drone.get_battery()
print(f"Battery: {battery}%")
Q11 What is the difference between turn() and turn_degree()?

Answer: turn() requires a direction string ("left" or "right") and turns for a specified duration. turn_degree() uses the gyroscope for more accurate turning and accepts positive (right) or negative (left) degree values.

Q12 How do you set the LED color on the drone?

Answer: Use set_drone_LED(r, g, b, brightness) where r, g, b are RGB values (0-255) and brightness is 0-100.

Example:

drone.set_drone_LED(255, 0, 0, 100)  # Red LED at 100% brightness
Q13 What does emergency_stop() do?

Answer: emergency_stop() immediately stops all commands and motors, causing the drone to drop. It should only be used in emergency situations. It also resets all flight motion variables to 0.

Q14 How do you get the current height of the drone?

Answer: Use get_height() which uses the bottom range sensor to return the height in centimeters.

Q15 What is the purpose of trim values?

Answer: Trim values (pitch, roll, yaw) help adjust the drone's balance and stability. They compensate for any physical imbalances in the drone.

Q16 How do you make the drone fly in a circle?

Answer: Use the circle(radius, power, duration) function. Specify the radius in centimeters, power level, and duration in seconds.

Q17 What sensor would you use to detect colors?

Answer: Use the color sensor functions: get_front_color() or get_back_color() to get RGB values, or use predict_colors() with a trained classifier.

Q18 Why should you take multiple sensor readings and average them?

Answer: Sensor readings can vary slightly. Taking multiple readings and averaging them provides more accurate and reliable data for decision-making.

Q19 What is the minimum battery level you should check before flying?

Answer: You should check that the battery is at least 30% before flying. If it's below 20%, you should not fly and charge the battery instead.

Q20 How do you use try-except blocks for error handling?

Answer: Wrap your drone code in try-except blocks to catch and handle errors gracefully. Always use a finally block to ensure close() is called even if an error occurs.

Example:

try:
    drone.pair()
    drone.takeoff()
except Exception as e:
    print(f"Error: {e}")
finally:
    drone.close()
Q21 What does keep_distance() do differently from avoid_wall()?

Answer: keep_distance() not only reaches a desired distance but also maintains that distance continuously. avoid_wall() just stops when it reaches the distance. Also, keep_distance() has a longer sensor range (up to 150cm).

Q22 How do you get the gyroscope angle values?

Answer: Use get_angle_x(), get_angle_y(), or get_angle_z() to get the angle in degrees for each axis. The Z-axis represents yaw (rotation).

Q23 What is the purpose of reset_gyro()?

Answer: reset_gyro() resets all gyroscope sensor values to zero. This is useful when you want to start measuring angles from the current position as the reference point.

Q24 How do you make the drone perform a flip?

Answer: Use flip(direction) where direction can be "forward", "backward", "left", or "right". Make sure the drone has adequate height before performing flips.

Q25 What is the difference between move() and go()?

Answer: go() is a simple function that moves in a direction with power and duration. move() uses pre-set movement values from set_pitch(), set_roll(), set_throttle(), and set_yaw() for more precise control.

Q26 How do you get the position data from the optical flow sensor?

Answer: Use get_pos_x(), get_pos_y(), and get_pos_z() for individual coordinates, or get_position_data() to get all position data at once.

Q27 What does set_initial_pressure() do?

Answer: set_initial_pressure() sets the current pressure reading as a reference point. This allows height calculations to be relative to that starting point.

Q28 How do you check if a button on the controller is pressed?

Answer: Use button-specific functions like h_pressed(), p_pressed(), s_pressed(), or up_arrow_pressed(). These return True if the button is pressed, False otherwise.

Q29 What is the purpose of using constants for configuration values?

Answer: Using constants (like POWER_LEVEL = 40) makes code easier to maintain and modify. You can change values in one place instead of searching through the entire code.

Q30 How do you make the drone fly in a square pattern?

Answer: You can use the built-in square(side_length, power) function, or manually use go() four times with directions "forward", "right", "backward", and "left", with hover times between each movement.

Q31 What should you do if sensor readings seem inconsistent?

Answer: Take multiple readings (5-10) and average them. Also, add small delays between readings using time.sleep(0.1) to allow the sensor to stabilize.

Q32 How do you create a color classifier for the color sensor?

Answer: First, use new_color_data() to start a new dataset. Then use append_color_data(color_name, r, g, b) multiple times to add training data. Finally, train and save the classifier.

Q33 What is the recommended hover time between flight commands?

Answer: It's recommended to use 0.5-1 second of hover time between flight commands to allow the drone to stabilize before the next movement.

Q34 How do you get joystick input from the controller?

Answer: Use functions like get_left_joystick_x(), get_left_joystick_y(), get_right_joystick_x(), and get_right_joystick_y(). These return values from -100 to 100.

Q35 What is the best practice for organizing your drone code?

Answer: Organize code into functions (initialization, preflight checks, flight patterns, cleanup), use constants for configuration values, implement error handling with try-except-finally blocks, and always include safety checks like battery monitoring.

Q36 Write code to make the drone take off, hover for 2 seconds, move forward 50cm, then land.

Answer:

from codrone_edu.drone import *

drone = Drone()
drone.pair()
drone.takeoff()
drone.hover(2)
drone.move_distance("forward", 50, 40)
drone.hover(1)
drone.land()
drone.close()
Q37 Write a function that checks battery level and only allows takeoff if battery is above 30%.

Answer:

def safe_takeoff(drone):
    battery = drone.get_battery()
    if battery > 30:
        drone.takeoff()
        return True
    else:
        print(f"Battery too low: {battery}%")
        return False
Q38 Write code to make the drone fly in a triangle pattern using go() function.

Answer:

drone.takeoff()
drone.hover(1)
for i in range(3):
    drone.go("forward", 40, 1)
    drone.hover(0.5)
    drone.turn("right", 120, 50)
    drone.hover(0.5)
drone.hover(1)
drone.land()
Q39 Write a function that uses the front range sensor to detect obstacles and turn right if an obstacle is within 50cm.

Answer:

def avoid_obstacle(drone):
    distance = drone.get_front_range()
    if distance < 50:
        drone.turn("right", 90, 50)
        drone.hover(0.5)
        return True
    return False
Q40 Write code to set the drone LED to red, then green, then blue, with 1 second delay between each.

Answer:

import time

drone.takeoff()
drone.set_drone_LED(255, 0, 0, 100)  # Red
time.sleep(1)
drone.set_drone_LED(0, 255, 0, 100)  # Green
time.sleep(1)
drone.set_drone_LED(0, 0, 255, 100)  # Blue
time.sleep(1)
drone.land()
Q41 Write a loop that makes the drone move forward until it detects a wall within 40cm using the front range sensor.

Answer:

distance = drone.get_front_range()
while distance > 40:
    drone.go("forward", 30, 0.5)
    drone.hover(0.3)
    distance = drone.get_front_range()
print("Wall detected!")
Q42 Write code to check battery level every 5 seconds during flight and land if it drops below 25%.

Answer:

import time

battery = drone.get_battery()
while battery > 25:
    # Your flight code here
    time.sleep(5)
    battery = drone.get_battery()
if battery <= 25:
    drone.land()
Q43 Write a function that makes the drone fly in a figure-8 pattern.

Answer:

def figure_eight(drone):
    for i in range(2):
        drone.circle(50, 40, 3)
        drone.hover(1)
        drone.turn("right", 180, 50)
        drone.hover(1)
Q44 Write code to get average sensor reading from 10 measurements of the front range sensor.

Answer:

readings = []
for i in range(10):
    readings.append(drone.get_front_range())
    time.sleep(0.1)
average = sum(readings) / len(readings)
Q45 Write a function that uses color sensor to detect red and turn right, detect blue and turn left.

Answer:

r, g, b = drone.get_front_color()
if r > 200 and g < 100 and b < 100:
    drone.turn("right", 90, 50)
elif r < 100 and g < 100 and b > 200:
    drone.turn("left", 90, 50)

Q48 Write code to make the drone perform a forward flip, then hover for 2 seconds.

Answer:

drone.takeoff()
drone.hover(2)  # Ensure adequate height
drone.flip("forward")
drone.hover(2)
drone.land()
Q49 Write a function that returns True if battery is above 30%, False otherwise.

Answer:

def check_battery(drone):
    battery = drone.get_battery()
    return battery > 30
Q50 Write code to use keep_distance() to maintain 60cm from an object for 15 seconds.

Answer:

drone.takeoff()
drone.hover(1)
drone.keep_distance(15, 60)  # timeout, distance
drone.hover(1)
drone.land()
Q51 Write a function that gets the average of 5 gyroscope angle readings.

Answer:

def get_avg_angle(drone):
    angles = []
    for i in range(5):
        angles.append(drone.get_angle_z())
        time.sleep(0.1)
    return sum(angles) / len(angles)
Q52 Write code to make the drone move forward, backward, left, and right in sequence with hover between each.

Answer:

drone.takeoff()
drone.hover(1)
for direction in ["forward", "backward", "left", "right"]:
    drone.go(direction, 40, 1)
    drone.hover(0.5)
drone.hover(1)
drone.land()
Q53 Write a function that uses set_pitch(), set_roll(), set_throttle(), and move() to fly forward and up simultaneously.

Answer:

def fly_forward_up(drone, duration):
    drone.set_pitch(30)
    drone.set_roll(0)
    drone.set_throttle(20)
    drone.set_yaw(0)
    drone.move(duration)
Q54 Write code to check if the H button is pressed and take off if it is.

Answer:

if drone.h_pressed():
    drone.takeoff()
    drone.hover(2)
    drone.land()
Q55 Write a function that resets all movement values using reset_move_values().

Answer:

def stop_movement(drone):
    drone.reset_move_values()
    drone.hover(0.5)
Q56 Write code to get the current position using optical flow sensor (x, y, z).

Answer:

x = drone.get_pos_x()
y = drone.get_pos_y()
z = drone.get_pos_z()
print(f"Position: ({x}, {y}, {z})")
Q57 Write a function that uses avoid_wall() with a timeout of 10 seconds and distance of 50cm.

Answer:

def wall_avoidance(drone):
    drone.takeoff()
    drone.hover(1)
    drone.avoid_wall(10, 50)
    drone.land()
Q58 Write code to set trim values to compensate for drift (pitch: 5, roll: -3, yaw: 0).

Answer:

drone.set_trim(5, -3, 0)  # pitch, roll, yaw
Q59 Write a function that plays a sequence of buzzer tones on the drone.

Answer:

def play_melody(drone):
    sequence = [(440, 200), (494, 200), (523, 200), (587, 200)]
    drone.drone_buzzer_sequence(sequence)
Q60 Write code to get both front and back color sensor readings.

Answer:

colors = drone.get_colors()
front_r, front_g, front_b = colors['front']
back_r, back_g, back_b = colors['back']
Q61 Write a function that uses get_height() to maintain a specific altitude.

Answer:

def maintain_height(drone, target_height):
    current = drone.get_height()
    if current < target_height - 5:
        drone.go("up", 30, 0.5)
    elif current > target_height + 5:
        drone.go("down", 30, 0.5)
Q62 Write code to use turn_degree() to turn exactly 90 degrees right, then 180 degrees left.

Answer:

drone.turn_degree(90, 50)   # Right 90 degrees
drone.hover(0.5)
drone.turn_degree(-180, 50)  # Left 180 degrees
Q63 Write a function that uses get_flow_velocity_x() and get_flow_velocity_y() to detect movement.

Answer:

def detect_movement(drone):
    vx = drone.get_flow_velocity_x()
    vy = drone.get_flow_velocity_y()
    if abs(vx) > 10 or abs(vy) > 10:
        return True
    return False
Q64 Write code to use send_absolute_position() to move to coordinates (100, 50, 80).

Answer:

drone.takeoff()
drone.hover(1)
drone.send_absolute_position(100, 50, 80, 40)
drone.hover(1)
drone.land()
Q65 Write a function that uses get_accel_x(), get_accel_y(), get_accel_z() to detect if drone is level.

Answer:

def is_level(drone):
    ax = abs(drone.get_accel_x())
    ay = abs(drone.get_accel_y())
    return ax < 50 and ay < 50
Q66 Write code to reset the gyroscope before starting a flight sequence.

Answer:

drone.pair()
drone.reset_gyro()
drone.takeoff()
Q67 Write a function that uses get_joystick_data() to control drone movement with controller.

Answer:

def joystick_control(drone):
    data = drone.get_joystick_data()
    left_x = data['left_x']
    left_y = data['left_y']
    # Use values to control drone
Q68 Write code to use square() function to fly in a 100cm square pattern.

Answer:

drone.takeoff()
drone.hover(1)
drone.square(100, 40)
drone.hover(1)
drone.land()
Q69 Write a function that uses get_sensor_data() to get all sensor readings.

Answer:

def get_all_sensors(drone):
    data = drone.get_sensor_data()
    return data
Q70 Write code to use triangle() function to fly in a 80cm triangle pattern.

Answer:

drone.takeoff()
drone.hover(1)
drone.triangle(80, 40)
drone.hover(1)
drone.land()
Q71 Write a function that uses get_pressure() and height_from_pressure() to calculate altitude.

Answer:

def get_altitude(drone):
    pressure = drone.get_pressure()
    height = drone.height_from_pressure()
    return height
Q72 Write code to use sway() function to sway left and right 40cm for 5 seconds.

Answer:

drone.takeoff()
drone.hover(1)
drone.sway("left", 40, 40, 5)
drone.hover(1)
drone.land()
Q73 Write a function that checks if the drone is flying using get_flight_state().

Answer:

def is_flying(drone):
    state = drone.get_flight_state()
    return state == "flying"
Q74 Write code to use move_distance() to move forward 75cm, then backward 75cm.

Answer:

drone.takeoff()
drone.hover(1)
drone.move_distance("forward", 75, 40)
drone.hover(0.5)
drone.move_distance("backward", 75, 40)
drone.hover(1)
drone.land()
Q75 Write a function that uses get_angular_speed_z() to detect rotation speed.

Answer:

def get_rotation_speed(drone):
    speed = drone.get_angular_speed_z()
    return speed
Q76 Write code to use reset_sensor() to reset all sensor values before flight.

Answer:

drone.pair()
drone.reset_sensor()
drone.takeoff()
Q77 Write a function that uses get_temperature() to check if drone is overheating (>40°C).

Answer:

def check_overheating(drone):
    temp = drone.get_temperature()
    return temp > 40
Q78 Write code to use get_elevation() to get current elevation from pressure sensor.

Answer:

elevation = drone.get_elevation()
print(f"Elevation: {elevation}")
Q79 Write a function that uses get_error_data() to check for errors.

Answer:

def check_errors(drone):
    errors = drone.get_error_data()
    if errors:
        print(f"Errors detected: {errors}")
        return True
    return False
Q80 Write code to use move_left() and move_right() to create a zigzag pattern.

Answer:

for i in range(5):
    drone.move_left(40, 1)
    drone.hover(0.3)
    drone.move_right(40, 1)
    drone.hover(0.3)
Q81 Write a function that uses get_movement_state() to check current movement.

Answer:

def get_movement(drone):
    state = drone.get_movement_state()
    return state
Q82 Write code to use controller_buzzer() to play a 440Hz tone for 500ms.

Answer:

drone.controller_buzzer(440, 500)
Q83 Write a function that uses set_initial_pressure() before takeoff for accurate height measurement.

Answer:

def setup_pressure_reference(drone):
    drone.pair()
    drone.set_initial_pressure()
    drone.takeoff()
Q84 Write code to use get_left_joystick_x() and get_left_joystick_y() for manual control.

Answer:

x = drone.get_left_joystick_x()
y = drone.get_left_joystick_y()
# Use x and y values to control drone
Q85 Write a complete program with error handling that takes off, flies a square, and lands safely.

Answer:

from codrone_edu.drone import *
import time

drone = Drone()
try:
    drone.pair()
    battery = drone.get_battery()
    if battery < 30:
        print("Battery too low")
    else:
        drone.takeoff()
        drone.hover(1)
        drone.square(100, 40)
        drone.hover(1)
        drone.land()
except Exception as e:
    print(f"Error: {e}")
finally:
    drone.close()

  • Official Documentation: Robolink CoDrone EDU Docs
  • Getting Started Guide: Check the official Robolink documentation for installation and setup instructions
  • Examples: Visit the Robolink website for more example code and tutorials

  • Notes


    Documentation Version: 2.6
    Last Updated: 2024
    Source: Based on Robolink CoDrone EDU Documentation