Changing mode causes the fall and take off from script not working

Hi to all,
I’m trying to make the copter fly indoor with a rangefinder and a Pix4Flow. The same copter flies correctly outdoor with GPS.
Indoor I’m using this script to take off:

def arm_and_takeoffNoGPS(Target, vehicle):

#Arm the vehicle
print 'ENTERING LOITER MODE'
while not vehicle.mode == 'LOITER':
    vehicle.mode = VehicleMode("LOITER")
    time.sleep(0.05)
print 'LOITER MODE SET'


vehicle.armed = True
while not vehicle.armed:
    time.sleep(1) #Waiting for armed

#Take Off
thrust = 0.8
while True:
    current_altitude = vehicle.location.global_relative_frame.alt
    print('Vehicle current altitude is: %f', current_altitude)
    if current_altitude >= Target * 0.95:
        break
    elif current_altitude >= Target * 0.6:
        thrust = 0.8
    set_attitude(vehicle, thrust=thrust)
    time.sleep(0.05)

In this way the copter reaches the right altitude but when I change the flight mode to loiter in order to stabilize the copter in its current position the drone instantaneously falls down.

In alternative to this approach I tried to use the dronekit simple_takeoff function:

def arm_and_simple_takeoff(Target, vehicle):

#my_location_alt = vehicle.location.global_frame
#my_location_alt.alt = 0
#vehicle.home_location = my_location_alt

print 'ENTERING LOITER MODE'
while not vehicle.mode == 'LOITER':
    vehicle.mode = VehicleMode("LOITER")
    time.sleep(0.05)
print 'LOITER MODE SET'

vehicle.armed = True
vehicle.flush()

while not vehicle.armed:
    time.sleep(1)  # Waiting for armed

vehicle.simple_takeoff(Target)

# 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
    # Break and return from function just below target altitude.
    if vehicle.location.global_relative_frame.alt >= Target * 0.95:
        print "Reached target altitude"
        break
    time.sleep(1)

In this case the motors rotate for a few seconds and after that the copter turns disarmed.
I attach my parameters configuration if it could help.
param.param (13.5 KB)

Thank you in advance.

Francesco

Hello,

Loiter is a manual mode, so it expect radio input from a rc radio or rc_override ! That why it fall down when you switch mode ! As you don’t send anything on throttle, it think that it got throttle = 0 and then stop motor and fall.

Thank you for the answer! I tried also the guided no gps mode and the motors do not rotate at all in this case.
My doubt is that by giving the command from the mission planner the Copter takes off correctly.
Which is the correct mode to take off and then keep the attitude?