Question

In: Computer Science

hello, I need a python program for a drone to follow keyboard commands - Create a...

hello, I need a python program for a drone to follow keyboard commands

- Create a simple single obstacle environment and program the drone to navigate through it

- Create a more advanced obstacle environment (3+ obstacles) and program the drone to navigate through it

Solutions

Expert Solution

PYTHON PROGRAM FOR DRONE TO FOLOW KEYWORD COMMANDS:

DroneKit and the vehicle should be set up as described in Installing DroneKit.

Once you’ve done that:

  1. Install the gpsd service (as shown for Ubuntu Linux below):

                sudo apt-get install gpsd gpsd-clients
    

    You can then plug in a USB GPS and run the “xgps” client to confirm that it is working.

  2. Get the DroneKit-Python example source code onto your local machine. The easiest way to do this is to clone the dronekit-python repository from Github. On the command prompt enter:

                 git clone http://github.com/dronekit/dronekit-python.git
  3. Install the gpsd service sudo apt-get install gpsd gpsd-clients You can then plug in a USB GPS and run the “xgps” client to confirm that it is working.

  4. Get the DroneKit-Python example source code onto your local machine. The easiest way to do this is to clone the dronekit-python repository from Github. On the command prompt enter:

               git clone http://github.com/dronekit/dronekit-python.git
    
  5. Navigate to the example folder as

  6. cd dronekit-python/examples/follow_me/

  7. You can run the example against a simulator (DroneKit-SITL) by specifying the Python script without any arguments. The example will download SITL binaries (if needed), start the simulator, and then connect to it:

    python follow_me.py
    

    On the command prompt you should see (something like):

    Starting copter simulator (SITL)
    SITL already Downloaded.
    Connecting to vehicle on: tcp:127.0.0.1:5760
    >>> APM:Copter V3.4-dev (e0810c2e)
    >>> Frame: QUAD
    Link timeout, no heartbeat in last 5 seconds
    Basic pre-arm checks
    Waiting for GPS...: None
    ...
    Waiting for GPS...: None
    Taking off!
     Altitude:  0.019999999553
     ...
     Altitude:  4.76000022888
    Reached target altitude
    Going to: Location:lat=50.616468333,lon=7.131903333,alt=30,is_relative=True
    ...
    Going to: Location:lat=50.616468333,lon=7.131903333,alt=30,is_relative=True
    Going to: Location:lat=50.616468333,lon=7.131903333,alt=30,is_relative=True
    User has changed flight modes - aborting follow-me
    Close vehicle object
    Completed
    
  8. You can run the example against a specific connection (simulated or otherwise) by passing the connection string for your vehicle in the --connect parameter.

    For example, to connect to SITL running on UDP port 14550 on your local computer:

    python follow_me.py --connect 127.0.0.1:14550
    

How does it work?

Most of the example should be fairly familiar as it uses the same code as other examples for connecting to the vehicle, taking off, and closing the vehicle object.

The example-specific code is shown below. All this does is attempt to get a gps socket and read the location in a two second loop. If it is successful it reports the value and uses Vehicle.simple_goto to move to the new position. The loop exits when the mode is changed.

import gps
import socket

...

try:
    # Use the python gps package to access the laptop GPS
    gpsd = gps.gps(mode=gps.WATCH_ENABLE)

    #Arm and take off to an altitude of 5 meters
    arm_and_takeoff(5)

    while True:

        if vehicle.mode.name != "GUIDED":
            print "User has changed flight modes - aborting follow-me"
            break

        # Read the GPS state from the laptop
        gpsd.next()

        # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around
        if (gpsd.valid & gps.LATLON_SET) != 0:
            altitude = 30  # in meters
            dest = LocationGlobalRelative(gpsd.fix.latitude, gpsd.fix.longitude, altitude)
            print "Going to: %s" % dest

            # A better implementation would only send new waypoints if the position had changed significantly
            vehicle.simple_goto(dest)

            # Send a new target every two seconds
            # For a complete implementation of follow me you'd want adjust this delay
            time.sleep(2)

except socket.error:
    print "Error: gpsd service does not seem to be running, plug in USB GPS or run run-fake-gps.sh"
    sys.exit(1)

Source code

The full source code at documentation build-time is listed below (current version on github):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
© Copyright 2015-2016, 3D Robotics.
followme - Tracks GPS position of your computer (Linux only).

This example uses the python gps package to read positions from a GPS attached to your 
laptop and sends a new vehicle.simple_goto command every two seconds to move the
vehicle to the current point.

When you want to stop follow-me, either change vehicle modes or type Ctrl+C to exit the script.

Example documentation: http://python.dronekit.io/examples/follow_me.html
"""
from __future__ import print_function

from dronekit import connect, VehicleMode, LocationGlobalRelative
import gps
import socket
import time
import sys

#Set up option parsing to get connection string
import argparse  
parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only).')
parser.add_argument('--connect', 
                   help="vehicle connection target string. If not specified, SITL automatically started and used.")
args = parser.parse_args()

connection_string = args.connect
sitl = None


#Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl
    sitl = dronekit_sitl.start_default()
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print('Connecting to vehicle on: %s' % connection_string)
vehicle = connect(connection_string, wait_ready=True, timeout=300)



def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """

    print("Basic pre-arm checks")
    # Don't let the user try to arm until autopilot is ready
    while not vehicle.is_armable:
        print(" Waiting for vehicle to initialise...")
        time.sleep(1)

        
    print("Arming motors")
    # Copter should arm in GUIDED mode
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.armed = True    

    while not vehicle.armed:      
        print(" Waiting for arming...")
        time.sleep(1)

    print("Taking off!")
    vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude

    # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command 
    #  after Vehicle.simple_takeoff will execute immediately).
    while True:
        print(" Altitude: ", vehicle.location.global_relative_frame.alt)      
        if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt.
            print("Reached target altitude")
            break
        time.sleep(1)



try:
    # Use the python gps package to access the laptop GPS
    gpsd = gps.gps(mode=gps.WATCH_ENABLE)

    #Arm and take off to altitude of 5 meters
    arm_and_takeoff(5)

    while True:
    
        if vehicle.mode.name != "GUIDED":
            print("User has changed flight modes - aborting follow-me")
            break    
            
        # Read the GPS state from the laptop
        next(gpsd)

        # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around
        if (gpsd.valid & gps.LATLON_SET) != 0:
            altitude = 30  # in meters
            dest = LocationGlobalRelative(gpsd.fix.latitude, gpsd.fix.longitude, altitude)
            print("Going to: %s" % dest)

            # A better implementation would only send new waypoints if the position had changed significantly
            vehicle.simple_goto(dest)

            # Send a new target every two seconds
            # For a complete implementation of follow me you'd want adjust this delay
            time.sleep(2)
            
except socket.error:
    print("Error: gpsd service does not seem to be running, plug in USB GPS or run run-fake-gps.sh")
    sys.exit(1)

#Close vehicle object before exiting script
print("Close vehicle object")
vehicle.close()

# Shut down simulator if it was started.
if sitl is not None:
    sitl.stop()
print("Completed")

Related Solutions

I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
Hello I need a small fix in my program. I need to display the youngest student...
Hello I need a small fix in my program. I need to display the youngest student and the average age of all of the students. It is not working Thanks. #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <algorithm> using namespace std; struct Student { string firstName; char middleName; string lastName; char collegeCode; int locCode; int seqCode; int age; }; struct sort_by_age { inline bool operator() (const Student& s1, const Student& s2) { return (s1.age < s2.age); // sort...
Write a python program that will allow a user to draw by inputting commands. The program...
Write a python program that will allow a user to draw by inputting commands. The program will load all of the commands first (until it reaches command "exit" or "done"), and then create the drawing. Must include the following: change attributes: color [red | green | blue] width [value] heading [value] position [xval] [yval] drawing: draw_axes draw_tri [x1] [y1] [x2] [y2] [x3] [y3 draw_rect [x] [y] [b] [h] draw_poly [x] [y] [n] [s] draw_path [path] random random [color | width...
I need to write a program in python for a restaurant. The program should let the...
I need to write a program in python for a restaurant. The program should let the user enter a meal number, then it should display the meal name, meal price, and meal calories. Also, needs the appropriate output if the user enters an invalid meal number. I am supposed to use a dictionary, but my problem is it keeps giving me an error and telling me my menu is not defined. Not sure what I am doing wrong. print ("Welcome...
Hello, I need some assistance on completing this program in Pseudocode and in C++ Program 2:...
Hello, I need some assistance on completing this program in Pseudocode and in C++ Program 2: Buh-RING IT! For this assignment, you’re going to simulate a text-based Role-Playing Game (RPG). Design (pseudocode) and implement (source) for a program that reads in 1) the hero’s Hit Points (HP – or health), 2) the maximum damage the hero does per attack, 3) the monster’s HP and 4) the maximum monster’s damage per attack. When the player attacks, it will pick a random...
I need someone to create a program for me: Create a program that takes as input...
I need someone to create a program for me: Create a program that takes as input an employee's salary and a rating of the employee's performance and computes the raise for the employee. The performance rating here is being entered as a String — the three possible ratings are "Outstanding", "Acceptable", and " Needs Improvement ". An employee who is rated outstanding will receive a 10.2 % raise, one rated acceptable will receive a 7 % raise, and one rated...
I need to create a program that will simulate an ATM. The program has to be...
I need to create a program that will simulate an ATM. The program has to be written in JAVA that uses JOptionaPane to pop up the messages. It will need to simulate to get ** balance **withdraw **Deposit **exit the atm ** need to have a method that shows a receipt of everything that was done during the transaction
Code in python Hello I want a program to read only the price of each line...
Code in python Hello I want a program to read only the price of each line in a txt file in python. The price is present right after the 2nd comma within the txt file. The output that I want is also printed at the bottom. Inside the txt file: 2019-08-01 00:08:39,BTC/USD,10128.08 2019-08-01 00:08:21,BTC/USD,10117.54 2019-08-01 00:08:20,BTC/USD,10120.51 2019-08-01 00:08:19,BTC/USD,10118.13 2019-08-01 00:08:18,BTC/USD,10120.74 Python file output: Price 1: 10128.08 Price 2: 10117.54 Price 3: 10120.51 Price 4: 10118.13 Price 5: 10120.74
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need...
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need to make sure I did it correctly. I'm not sure if my formula is correct. I appreciate any help, thank you! TASK: Write a program that will calculate the final balance in an investment account. The user will supply the initial deposit, the annual interest rate, and the number of years invested. Solution Description: Write a program that calculates the final balance in an...
I need to update this program to follow the these requirements please and thank you :...
I need to update this program to follow the these requirements please and thank you : Do not use packages Every class but the main routine class must have a toString method . The toString method for Quadrilateral should display its fields: 4 Points. All instance variables should be declared explicitly private . Area incorrect : enter points no: 1 1 3 enter points no: 2 6 3 enter points no: 3 0 0 enter points no: 4 5 0...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT