AR.Drone2.0: нет четкого движения при выполнении команд перемещения.Python

Программы на Python
Ответить
Anonymous
 AR.Drone2.0: нет четкого движения при выполнении команд перемещения.

Сообщение Anonymous »

Сейчас я работаю над дипломной работой. Поскольку программирование аппаратного обеспечения не является основным направлением моих исследований, я, возможно, упускаю важный момент, и мне нужен опыт сообщества, который поможет решить эту проблему.
Я использую AR .Drone2.0 и написали следующий код для управления его движениями. Однако, несмотря на подачу различных команд движения, дрон не демонстрирует каких-либо определенных движений. Я подозреваю, что может быть проблема с отправкой команд или временем между основным потоком и командным потоком.
Я пробовал взлетать и приземляться, и эти команды обычно работают. Однако иногда скрипт пропускает команду приземления и завершает работу, даже не приземлившись, что странно, но не главная проблема.
Дрон имеет тенденцию зависать, когда я отправляю команду перемещения с помощью Флаг наведения установлен в значение false. Я ожидал, что дрон будет гораздо более устойчивым, но он довольно много перемещается.
Настоящая проблема возникает, когда я отправляю команду движения. При этом дрон иногда движется, но движение кажется неопределенным и неточным. На каждую единицу движения в заданном направлении он отображает одну единицу движения в двух ложных направлениях, которые я пока не понимаю и не могу решить самостоятельно.
Мы очень ценим вашу поддержку.
Вот соответствующий код:
class Drone:
def __init__(self, ip: str, ports: dict) -> None:
self.ip = ip # IP address of the drone
self.com_port = ports['com-port']
self.nav_port = ports['nav-port']
self.crit_port = ports['crit-port']

# Setting up sockets
self.com_socket = self.setup_socket() #socket to send command
self.nav_socket = self.setup_socket() #socket to receive navdata

# Set up NavData listening in a separate thread
self.nav_queue = queue.Queue()
self.navdata_thread = threading.Thread(target=self.receive_navdata)
self.navdata_thread.daemon = True # Allow thread to exit when main program exits

# Set up NavData processing in a separate thread
self.decoded_nav_queue = queue.Queue()
self.decode_navdata_thread = threading.Thread(target=self.decode_navdata)
self.decode_navdata_thread.daemon = True # Allow thread to exit when main program exits
self.navdata_log: pd.DataFrame = pd.DataFrame()

# Set up Commands in a separate thread
self.command_queue = queue.Queue()
self.command_counter = 1
self.command_thread = threading.Thread(target=self.send_command)
self.command_thread.daemon = True # Allow thread to exit when main program exits

#start the threads
self.decode_navdata_thread.start()
self.navdata_thread.start()
self.command_thread.start()

def send_command(self):
"""Send control commands to the drone."""
while True:
if not self.command_queue.empty():
command = self.command_queue.get()
command = command.replace('#COMID#', str(self.command_counter))
self.command_counter += 1
else:
command = 'AT*COMWDG\r'
self.com_socket.sendto(command.encode(), (self.ip, self.com_port))
print()
print()
print(f"Sent control command: {command}")
print()
print()
time.sleep(0.03)

# Takeoff and landing is described in the documentation of the drone page 35.
#
def takeoff(self) -> None:
order = str(int('00010001010101000000001000000000',2))
command = f'AT*REF=#COMID#,{order}\r'
self.command_queue.put(command)

def land(self) -> None:
order = str(int('00010001010101000000000000000000',2))
command = f'AT*REF=#COMID#,{order}\r'
self.command_queue.put(command)

def move(self, hover: bool, lr_tilt: float, fb_tilt: float, vert_speed: float, yaw_speed: float) -> None:
"""
Controls the drone's movement by adjusting its tilt and speed.

Parameters:
hover (bool): A flag indicating whether the drone should hover in place.
If True, the drone will maintain its current position and
orientation without any lateral, longitudinal, or vertical
movement. This is useful for stabilizing the drone in air.
If False, the drone will move according to the provided
tilt and speed parameters.

lr_tilt (float): The lateral or left-right tilt of the drone.
Positive values tilt the drone to the right,
while negative values tilt it to the left.
Range: -1.0 to 1.0.

fb_tilt (float): The longitudinal or forward-backward tilt of the drone.
Positive values tilt the drone forward, facilitating
forward movement, whereas negative values tilt it backward.
Range: -1.0 to 1.0.

vert_speed (float): The vertical speed of the drone, dictating its
ascent or descent. Positive values increase the
altitude, while negative values decrease it.
Range: -1.0 to 1.0.

yaw_speed (float): The rotational speed of the drone around its vertical
axis. Positive values rotate the drone clockwise, and
negative values rotate it counterclockwise.
Range: -1.0 to 1.0.
"""
if hover == True:
flag = 0
else:
flag = 1

lr_tilt = int(lr_tilt * 1000.0)
fb_tilt = int(fb_tilt * 1000.0)
vert_speed = int(vert_speed * 1000.0)
yaw_speed = int(yaw_speed * 1000.0)
command = f'AT*PCMD=#COMID#,{flag},{lr_tilt},{fb_tilt},{vert_speed},{yaw_speed}\r'
self.command_queue.put(command)

if __name__ == "__main__":
ports = {'com-port': 5556, 'nav-port': 5554, 'crit-port': 5559}
drone_ = Drone(ip="192.168.1.1", ports=ports)

# Send the command to start NavData stream
Drone.start_navdata_stream(self= drone_)

#Example: Send a takeoff and land command
drone_.takeoff()
time.sleep(6)

for _ in range(100):
drone_.move(True, 0.0, 0.0, 0.0, 0.0)
for _ in range(100):
drone_.move(False, 0.0, -1.0, 0.0, 0.0)
time.sleep(6)
drone_.land()
time.sleep(3)


Подробнее здесь: https://stackoverflow.com/questions/792 ... e-commands
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»