Webots实现大疆Mavic2pro无人机定点飞行

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、将无人机当成一个对象
    • 1.1定义无人机相关属性
    • 1.2定义用于控制无人机运动的代码
    • 1.3主函数实现无人机的点位固定和飞行检测
  • 二、用键盘控制测试代码
  • 三、效果展示
  • 四、注意点


前言

由于项目要求,现在需要做一个能够实现无人机根据事先给定的点位实现定点飞行,这里由于webots的跨平台性,考虑使用webots进行仿真

一、将无人机当成一个对象

1.1定义无人机相关属性

由于无人机有pitch、yaw、roll三个属性,分别对应前后运动、左右偏航和左右横滚、这里定义相关的所有属性用于控制。
同时定义相应的用于控制运动的函数

1.2定义用于控制无人机运动的代码

import math
import time
from controller import Robot, Camera, Compass, GPS, Gyro, InertialUnit, Keyboard, LED, Motor# 自定义无人机类,继承机器人父类
class UAV(Robot):timestep = 0# Constants, empirically found.k_vertical_thrust = 68.5  # with this thrust, the drone lifts.k_vertical_offset = 0.6   # Vertical offset where the robot actually targets to stabilize itself.k_vertical_p = 3.0        # P constant of the vertical PID.k_roll_p = 50.0           # P constant of the roll PID.k_pitch_p = 30.0          # P constant of the pitch PID.# 初始化变量def __init__(self):# Get and enable devices.self.camera = Camera("camera")self.camera.enable(timestep)self.front_left_led = LED("front left led")self.front_right_led = LED("front right led")self.imu = InertialUnit("inertial unit")self.imu.enable(timestep)self.gps = GPS("gps")self.gps.enable(timestep)self.compass = Compass("compass")self.compass.enable(timestep)# 检测角速度self.gyro = Gyro("gyro")self.gyro.enable(timestep)# keyboard = Keyboard()# keyboard.enable(timestep)# 横滚检测器self.camera_roll_motor = Motor("camera roll")# 前后俯仰检测器self.camera_pitch_motor = Motor("camera pitch")# 用于控制无人机平稳飞行的变量self.roll_disturbance = 0.0self.pitch_disturbance = 0.0self.yaw_disturbance = 0.0# 设置初始目标噶度self.target_altitude = 10.0# Get propeller motors and set them to velocity mode.self.front_left_motor = Motor("front left propeller")self.front_right_motor = Motor("front right propeller")self.rear_left_motor = Motor("rear left propeller")self.rear_right_motor = Motor("rear right propeller")# 将所有的驱动器保存到一个数组中self.motors = [self.front_left_motor, self.front_right_motor, self.rear_left_motor, self.rear_right_motor]# 前进def forward():self.pitch_disturbance = 2.0# 后退def backward():self.pitch_disturbance = -2.0# 向右运动def right():self.yaw_disturbance = 1.3# 向左运动def left():self.yaw_disturbance = -1.3# 向右横滚def roll_right():self.roll_disturbance = -1.0# 向左横滚def roll_left():self.roll_disturbance = 1.0# 上升def up():self.target_altitude += 0.05print("target altitude:", target_altitude, "[m]")# 下降def down():self.target_altitude -= 0.05print("target altitude:", target_altitude, "[m]")# 获取无人机当前位置def getPosition():self.roll = self.imu.getRollPitchYaw()[0] + math.pi / 2.0self.pitch = self.imu.getRollPitchYaw()[1]self.altitude = self.gps.getValues()[1]# 获取角速度self.roll_acceleration = self.gyro.getValues()[0]self.pitch_acceleration = self.gyro.getValues()[1]# Blink the front LEDs alternatively with a 1 second rate.self.led_state = int(time) % 2self.front_left_led.set(led_state)self.front_right_led.set(1 - led_state)# 根据相关参数进行运动控制def Move():# Stabilize the Camera by actuating the camera motors according to the gyro feedback.self.camera_roll_motor.setPosition(-0.115 * self.roll_acceleration)self.camera_pitch_motor.setPosition(-0.1 * self.pitch_acceleration)# Compute the roll, pitch, and yaw errors.roll_input = self.k_roll_p * CLAMP(self.roll, -1.0, 1.0) + self.roll_acceleration + self.roll_disturbancepitch_input = self.k_pitch_p * CLAMP(self.pitch, -1.0, 1.0) - self.pitch_acceleration + self.pitch_disturbanceyaw_input = self.yaw_disturbanceclamped_difference_altitude = CLAMP(self.target_altitude - self.altitude + self.k_vertical_offset, -1.0, 1.0)vertical_input = self.k_vertical_p * pow(clamped_difference_altitude, 3.0)# Accute the motor taking into consideration all the computed inputs.front_left_motor_input = self.k_vertical_thrust + vertical_input - roll_input - pitch_input + yaw_inputfront_right_motor_input = self.k_vertical_thrust + vertical_input + roll_input - pitch_input - yaw_inputrear_left_motor_input = self.k_vertical_thrust + vertical_input - roll_input + pitch_input - yaw_inputrear_right_motor_input = self.k_vertical_thrust + vertical_input + roll_input + pitch_input + yaw_inputself.front_left_motor.setVelocity(front_left_motor_input)self.front_right_motor.setVelocity(-front_right_motor_input)self.rear_left_motor.setVelocity(-rear_left_motor_input)self.rear_right_motor.setVelocity(rear_right_motor_input)# 辅助函数
def CLAMP(value, low, high):return max(low, min(value, high))

1.3主函数实现无人机的点位固定和飞行检测

将主函数声明成控制器就可以了

from Uav import Uav
def main():uav = Uav()timestep = int(uav.getBasicTimeStep())uav.timestep = timestepkeyboard = Keyboard()keyboard.enable(timestep)while uav.step(timestep) != -1:key = keyboard.getKey()uav.roll_disturbance = 0.0uav.pitch_disturbance = 0.0uav.yaw_disturbance = 0.0while key > 0:# 上升函数if key == Keyboard.UP:uav.forward()elif key == Keyboard.DOWN:uav.backward()elif key == Keyboard.RIGHT:uav.right()elif key == Keyboard.LEFT:uav.left()elif key == (Keyboard.SHIFT + Keyboard.RIGHT):uav.roll_right()elif key == (Keyboard.SHIFT + Keyboard.LEFT):uav.roll_left()elif key == (Keyboard.SHIFT + Keyboard.UP):uav.up()elif key == (Keyboard.SHIFT + Keyboard.DOWN):uav.down()key = keyboard.getKey()uav.getPosition()uav.Move()wb_robot_cleanup();if __name__ == "__main__" :main()

二、用键盘控制测试代码

由于webots默认给的是通过C++代码实现键盘对无人机进行控制,然而开发使用的多是python,这里给出根据原本C++代码改写的python控制代码,直接新建成一个控制器然后在webots中选择这个.py文件作为控制器就可以了,记得放到controler文件夹中。

import math
import time
from controller import Robot, Camera, Compass, GPS, Gyro, InertialUnit, Keyboard, LED, Motordef CLAMP(value, low, high):return max(low, min(value, high))def main():# 创建一个机器人对象robot = Robot()# 每个物理动作的持续时间timestep = int(robot.getBasicTimeStep())# Get and enable devices.camera = Camera("camera")camera.enable(timestep)front_left_led = LED("front left led")front_right_led = LED("front right led")imu = InertialUnit("inertial unit")imu.enable(timestep)gps = GPS("gps")gps.enable(timestep)compass = Compass("compass")compass.enable(timestep)# 检测角速度gyro = Gyro("gyro")gyro.enable(timestep)keyboard = Keyboard()keyboard.enable(timestep)# 横滚检测器camera_roll_motor = Motor("camera roll")# 前后俯仰检测器camera_pitch_motor = Motor("camera pitch")# Get propeller motors and set them to velocity mode.front_left_motor = Motor("front left propeller")front_right_motor = Motor("front right propeller")rear_left_motor = Motor("rear left propeller")rear_right_motor = Motor("rear right propeller")motors = [front_left_motor, front_right_motor, rear_left_motor, rear_right_motor]for motor in motors:# 初始化无限旋转的运动motor.setPosition(float('inf'))# 启动!motor.setVelocity(1.0)# Display the welcome message.print("Start the drone...")# Wait one second.while robot.step(timestep) != -1:if robot.getTime() > 1.0:break# Display manual control message.print("You can control the drone with your computer keyboard:")print("- 'up': move forward.")print("- 'down': move backward.")print("- 'right': turn right.")print("- 'left': turn left.")print("- 'shift + up': increase the target altitude.")print("- 'shift + down': decrease the target altitude.")print("- 'shift + right': strafe right.")print("- 'shift + left': strafe left.")# Constants, empirically found.k_vertical_thrust = 68.5  # with this thrust, the drone lifts.k_vertical_offset = 0.6   # Vertical offset where the robot actually targets to stabilize itself.k_vertical_p = 3.0        # P constant of the vertical PID.k_roll_p = 50.0           # P constant of the roll PID.k_pitch_p = 30.0          # P constant of the pitch PID.# Variables.# 设置初始高度target_altitude = 1.0  # The target altitude. Can be changed by the user.# Main loop# - perform simulation steps until Webots is stopping the controllerwhile robot.step(timestep) != -1:time = robot.getTime()# Retrieve robot position using the sensors.roll = imu.getRollPitchYaw()[0] + math.pi / 2.0pitch = imu.getRollPitchYaw()[1]altitude = gps.getValues()[1]# 获取角速度roll_acceleration = gyro.getValues()[0]pitch_acceleration = gyro.getValues()[1]# Blink the front LEDs alternatively with a 1 second rate.led_state = int(time) % 2front_left_led.set(led_state)front_right_led.set(1 - led_state)# Stabilize the Camera by actuating the camera motors according to the gyro feedback.camera_roll_motor.setPosition(-0.115 * roll_acceleration)camera_pitch_motor.setPosition(-0.1 * pitch_acceleration)# Transform the keyboard input to disturbances on the stabilization algorithm.roll_disturbance = 0.0pitch_disturbance = 0.0yaw_disturbance = 0.0key = keyboard.getKey()while key > 0:# 上升函数if key == Keyboard.UP:pitch_disturbance = 2.0elif key == Keyboard.DOWN:pitch_disturbance = -2.0elif key == Keyboard.RIGHT:yaw_disturbance = 1.3elif key == Keyboard.LEFT:yaw_disturbance = -1.3elif key == (Keyboard.SHIFT + Keyboard.RIGHT):roll_disturbance = -1.0elif key == (Keyboard.SHIFT + Keyboard.LEFT):roll_disturbance = 1.0elif key == (Keyboard.SHIFT + Keyboard.UP):target_altitude += 0.05print("target altitude:", target_altitude, "[m]")elif key == (Keyboard.SHIFT + Keyboard.DOWN):target_altitude -= 0.05print("target altitude:", target_altitude, "[m]")key = keyboard.getKey()# Compute the roll, pitch, and yaw errors.roll_input = k_roll_p * CLAMP(roll, -1.0, 1.0) + roll_acceleration + roll_disturbancepitch_input = k_pitch_p * CLAMP(pitch, -1.0, 1.0) - pitch_acceleration + pitch_disturbanceyaw_input = yaw_disturbanceclamped_difference_altitude = CLAMP(target_altitude - altitude + k_vertical_offset, -1.0, 1.0)vertical_input = k_vertical_p * pow(clamped_difference_altitude, 3.0)# Accute the motor taking into consideration all the computed inputs.front_left_motor_input = k_vertical_thrust + vertical_input - roll_input - pitch_input + yaw_inputfront_right_motor_input = k_vertical_thrust + vertical_input + roll_input - pitch_input - yaw_inputrear_left_motor_input = k_vertical_thrust + vertical_input - roll_input + pitch_input - yaw_inputrear_right_motor_input = k_vertical_thrust + vertical_input + roll_input + pitch_input + yaw_inputfront_left_motor.setVelocity(front_left_motor_input)front_right_motor.setVelocity(-front_right_motor_input)rear_left_motor.setVelocity(-rear_left_motor_input)rear_right_motor.setVelocity(rear_right_motor_input)wb_robot_cleanup()if __name__ == "__main__":main()

三、效果展示

用python控制器实现键盘控制无人机运动

四、注意点

  1. Webots中不支持到其他库,所以理论上应该都写在一个文件夹中,如果想要写在不用的文件夹中,需要
  2. 改变控制器以后记得重新保存一份世界文件。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/433819.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C++专题】static_cast, dynamic_cast, const_cast探讨

首先回顾一下C类型转换:C类型转换分为:隐式类型转换和显式类型转换 第1部分. 隐式类型转换 又称为“标准转换”,包括以下几种情况:1) 算术转换(Arithmetic conversion) : 在混合类型的 算术表达式中, 最宽的数据类型成为目标转换…

浅谈程序员的职业规划

不知不觉参加工作成为程序员已经4年多,记得上高中的时候,从网络上知道了很多IT精英创业成功的例子,如没有读过大学的“汽车之家”创始人李想、facebook创始人马克扎克伯格,让我觉得互联网是个充满梦想的舞台,只要有想法…

python调用数据库数据创建函数_Pyhton应用程序数据库函数封装

1.函数2.迭代器3.递归4.数据库函数5.fetchall函数1.函数:实现指定功能代码的集合def 函数名( ) :2.在python中没有括号,函数体以缩进的方式进行展示快捷键:tab实现了函数的缩进,shifttab实现前移3.调用:函数名( )作用&…

电子计算机和多媒体教材分析,人教新课标:电子计算机与多媒体教材分析

电子计算机与多媒体(4篇)主要内容:本文简要地介绍了电子计算机的发明到多媒体的运用的基本情况,展示了电子计算机的飞速发展和灿烂前景。课文从美国史密森博物馆里存放的世界上第一台电子计算机写起,先概括地交代了电子计算机的飞速发展和它在…

安卓工控主板运行时会自动重启_工控主板在工业自动化中的应用

原标题:工控主板在工业自动化中的应用大家都知道随着科技的发展对于工控主板的用途和应用大大超出了工业自动化的范围,而对于本文联智通达小编将仅坚持工业自动化范围内的应用。首先跟随联智通达小编看一下制造以及工业PC的应用以及如何使该领域的工业自…

am335x gpio驱动

任务: GPIO0_19(带下拉)作为中断, GPIO0_20(带上拉)和GPIO1_14作为输出管脚,GPIO0_11(带下拉)和 GPIO1_15(带上拉)。并编写驱动程序。

海量小文件存储

海量小文件存储 [转自:http://www.fuchaoqun.com/2009/04/deal-with-tons-of-small-files/] Web2.0网站,数据内容以几何级数增长,尤其是那些小文件,几K~几百K不等,数量巨多,传统的文件系统处理起来很是吃力…

与0xf2值相等的是python_腾讯笔试题涵盖的基础知识

1.下列减少内存碎片的方法有哪些是正确的?增加实际申请和释放的次数频繁调用的子函数尽量使用栈内存系统申请一大块内存,自己实现内存分配和释放,定时清理内存降低虚拟内存的大小解答:答案2,3是正确的。属于操作系统中内存管理的问…

重庆大学 计算机组成原理,重庆大学计算机组成原理集(含部分)解决方案.doc

《计算机组成原理》试题集一、选择题在每小题列出的四个备选项中只有一个是符合题目要求的,请将其代码填写在题后的括号内。1.反映计算机基本功能的是( )A)操作系统 B)系统软件 C)指令系统 D)数据库系统2.若二进制数为1111.101,则…

diff算法_vue源码解读 diff算法

导语 最近碰到部分业务场景,代码逻辑需要了解"数组变更后,具体变更了哪一些元素,以及变更的位置.."。于是仔细研究并覆写了一遍针对数组变化的diff算法,在这里做下diff算法的逻辑分享&&源码解读一.介绍前的准备…

Linux驱动模块编译进内核中

BQ27501驱动编译进内核 一、 驱动程序编译进内核的步骤 在 linux 内核中增加程序需要完成以下三项工作: 1. 将编写的源代码复制到 Linux 内核源代码的相应目录; 2. 在目录的 Kconfig 文件中增加新源代码对应项目的编译配置选项; 3. 在…

oracle 的进程

W000: Wnnn命名为W000,W001,W002.....,由smcO动态产生执行上述相关任务。 Pmon: Pmon后台进程负责一下的工作:进程异常终止,会话被杀掉,事务超过空闲时间,网络连接超时,将实例信息注册到监听器上,手工注册 altersystem register; Pmon进程的清…

请简述计算机硬件系统的运行过程,操作系统简述题

✔什么是操作系统?它的功能?操作系统是控制和管理计算机硬件和软件资源,合理地组织计算机工作流程以及方便用户使用计算机系统的程序的集合。功能:处理机管理,存储器管理,I/O设备管理和文件管理以及作为操作…

python闭环最短路径_最短路径算法的实现(dijskstra):Python

dijskstra最短路径算法步骤:输入:图G(V(G),E(G))有一个源顶点S和一个汇顶点t,以及对所有的边ij属于E(G)的非负边长出cij。输出:G从s到t的最短路径的长度。第0步:从对每个顶点做临时标记L开始,做法如下&…

黑群晖二合一安装不了套件_玩PT还是得安装transmission,星际蜗牛安装黑群晖制作家用NAS...

原文作者:pt老萌新To小白:黑群晖docker安装PT神器transmission——星际蜗牛安装黑群晖制作家用NAS的折腾日记写在前面:里面的技术方法不是我原创的,都是网上找的,侵删。折腾的过程记录是原创的(好像没啥原创的了)&…

Know more about Cache Buffer Handle

在之前的文章《latch free:cache buffer handles造成的SQL性能问题》中我介绍了cache buffer handle latch的一些知识,在这里我们复习一下: "当会话需要pin住buffer header时它首先要获去buffer handle,得到buffer handle的过程中首先要…

spring boot web项目_阿里技术专家带你使用Spring框架快速搭建Web工程项目

点击上方 "程序员小乐"关注, 星标或置顶一起成长 第一时间与你相约 每日英文 We all have a past. It’s how you deal with it. 每个人都有过去,只是取决于你怎么去处理。 每日掏心话 人不都是这样吗,安慰别人的时候头头是道,自己…

MySQL执行外部sql脚本文件的命令

sql脚本是包含一到多个sql命令的sql语句,我们可以将这些sql脚本放在一个文本文件中(我们称之为“sql脚本文件”),然后通过相关的命令执行这个sql脚本文件。基本步骤如下:1、创建包含sql命令的sql脚本文件 文件中包含一…

全国计算机水平考试技巧,全国计算机等级考试上机考试应试技巧

掌握好上机考试的应试技巧,可以使考生的实际水平在考试时得到充分发挥,从而取得较为理想的成绩。历次考试均有考生因为忽略了这一点,加之较为紧张的考场气氛影响了水平的发挥,致使考试成绩大大低于实际水平。因此每个考生在应试前…

git 代码回滚_能提交到远程的Git回滚

很多情况下我们需要回滚代码,最容易想到的就是git reset。但是git reset有个弱点,它是一个彻底的回滚,不能再提交给远程了,因为在提交记录里回滚点之后的记录都不见了。做一下试验,一个文件我们提交了三次之后回滚#往前…