scieee AI-readable full text Open interactive document viewer

Repositorio Institucional de Documentos

Abstract

Este proyecto se centra en el desarrollo de un cuadricóptero y su control integrado en el entorno de ROS. ROS (Robotic Operating System) es un pseudo sistema operativo orientado a plataformas robóticas. El trabajo desarrollado cubre desde el manejo del sistema operativo en distintas plataformas robóticas o el estudio de las diversas formas de programación en ROS hasta la evaluación de alternativas de construcción, desarrollo de la interfaz con ROS o ensayos prácticos con la plataforma construida. En primer lugar, se ha realizado un estudio de las posibilidades de ROS aplicadas a robots voladores, las alternativas de desarrollo y su viabilidad de integración. Entre estas aplicaciones cabe destacar las de SLAM (Localización y Mapeo Simultáneos) y navegación autonoma. Tras la evaluación de las distintas alternativas considerando funcionalidad, autonomía y precio, la plataforma de desarrollo se ha basado en ArduCopter. Aunque existen algunos ejemplos de vehículos aéreos no tripulados en ROS, no hay soporte para este sistema, por lo cual se ha desarrollado el trabajo necesario para hacer estas dos plataformas compatibles. El hardware ha sido montado sobre una plataforma de fabricación propia, realizada mediante impresión 3D, y se ha evaluado su funcionamiento en entornos reales. También se ha valorado y ensayado una plataforma de aluminio, con resultados menos satisfactorios. Para el correcto funcionamiento del conjunto se ha tenido que conseguir una conexión entre el cuadricóptero y la estación de tierra. En este caso, se han diseñado alternativas de conexión entre ordenadores (para el caso de que se monte un ordenador en la aeronave) o conexión entre ordenador y ArduCopter (para el caso de que no haya ordenador de a bordo). También se ha implementado una serie de algoritmos para llevar a cabo el control del cuadricóptero de manera autónoma: navegación de puntos vía, control de la rotación y control de altitud. Estos módulos funcionan bajo el sistema ROS y operan en remoto desde la estación de tierra. Finalmente, se ha desarrollado un módulo de lectura para una unidad de medida inercial actualmente en desarrollo por la universidad de Luleå (KFly). Este dispositivo sólo se ha probado en entornos controlados y aún no ha pasado a formar parte del cuadricóptero, aunque en un futuro próximo se espera que sirva de reemplazo al ordenador de a bordo. Monzón Catalán, Iván; Nikolakopoulos, Georgios

Full text

Proyecto Fin de Carrera Ingeniería Industrial Automatización Industrial y Robótica Desarrollo de un cuadricóptero operado por ROS Iván Monzón Catalán Director: Georgios Nikolakopoulos Ponente: Ana Cristina Murillo Arnal Departamento de Informática e Ingeniería de Sistemas Escuela de Ingeniería y Arquitectura Universidad de Zaragoza Control Engineering Group Department of Computer Science, Electrical and Space Engineering Luleå University of Technology Septiembre 2013 RESUMEN Este proyecto se centra en el desarrollo de un cuadricóptero y su control integrado en el entorno de ROS. ROS (Robotic Operating System) es un pseudo sistema operativo orientado a plataformas robóticas. El trabajo desarrollado cubre desde el manejo del sistema operativo en distintas plataformas robóticas o el estudio de las diversas formas de programación en ROS hasta la evaluación de alternativas de construcción, desarrollo de la interfaz con ROS o ensayos prácticos con la plataforma construida. En primer lugar, se ha realizado un estudio de las posibilidades de ROS aplicadas a robots voladores, las alternativas de desarrollo y su viabilidad de integración. Entre estas aplicaciones cabe destacar las de SLAM (Localización y Mapeo Simultáneos) y navegación autonoma. Tras la evaluación de las distintas alternativas considerando funcionalidad, autonomía y precio, la plataforma de desarrollo se ha basado en ArduCopter. Aunque existen algunos ejemplos de vehículos aéreos no tripulados en ROS, no hay soporte para este sistema, por lo cual se ha desarrollado el trabajo necesario para hacer estas dos plataformas compatibles. El hardware ha sido montado sobre una plataforma de fabricación propia, realizada mediante impresión 3D, y se ha evaluado su funcionamiento en entornos reales. También se ha valorado y ensayado una plataforma de aluminio, con resultados menos satisfactorios. Para el correcto funcionamiento del conjunto se ha tenido que conseguir una conexión entre el cuadricóptero y la estación de tierra. En este caso, se han diseñado alternativas de conexión entre ordenadores (para el caso de que se monte un ordenador en la aeronave) o conexión entre ordenador y ArduCopter (para el caso de que no haya ordenador de a bordo). También se ha implementado una serie de algoritmos para llevar a cabo el control del cuadricóptero de manera autónoma: navegación de puntos vía, control de la rotación y control de altitud. Estos módulos funcionan bajo el sistema ROS y operan en remoto desde la estación de tierra. Finalmente, se ha desarrollado un módulo de lectura para una unidad de medida inercial actualmente en desarrollo por la universidad de Luleå (KFly). Este dispositivo sólo se ha probado en entornos controlados y aún no ha pasado a formar parte del cuadricóptero, aunque en un futuro próximo se espera que sirva de reemplazo al ordenador de a bordo. III PRÓLOGO Este trabajo se ha realizado como un Proyecto de Fin de Carrera para completar mis estudios en Ingeniería Industrial, con especialidad en Automatización Industrial y Robótica, en la Universidad de Zaragoza (España). El proyecto ha sido desarrollado y presentado en la Universidad Técnica de Luleå (Suecia) con el equipo del Departamento de Informática, Ingeniería Eléctrica y del Espacio; a quienes agradezco enormemente su apoyo y colaboración. Me gustaría agradecer al Programa Erasmus por darme la oportunidad de ir a esta maravillosa ciudad sueca, Luleå. A Georgios Nikolakopoulos, mi supervisor en esta empresa, por su apoyo y optimismo. Y a Ana Cristina Murillo, quien me ha ayudado en todas las fases españolas. Fue un duro y largo viaje de más de seis meses, lleno de retrasos y problemas. Pero ahora puedo decir que el viaje valió la pena. V ÍNDICE GENERAL CAPÍTULO 1 – INTRODUCCIÓN 1 1.1. Motivación y trabajo relacionado . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2. Objetivosdelproyecto .............................. 3 1.3. Entornodetrabajo................................. 4 1.4. UAVs (Vehículos aéreos no tripulados) . . . . . . . . . . . . . . . . . . . . . . 5 1.4.1. Cuadricópteros.............................. 7 1.5. Contenidodelamemoria............................. 8 CAPÍTULO 2 – DISEÑO Y CONSTRUCCIÓN 9 2.1. Estructurayfijaciones............................... 9 2.1.1. Impresión3D............................... 10 2.2. Hardware ..................................... 11 2.2.1. Arducopter ................................ 11 2.2.2. Sensores ................................. 15 2.3. Plataformas de seguridad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 CAPÍTULO 3 – PROGRAMACIÓN Y DESARROLLO 19 3.1. ROS: Sistema Operativo para Robots . . . . . . . . . . . . . . . . . . . . . . . 19 3.1.1. Definición................................. 19 3.1.2. Uso de la plataforma y primeros ensayos . . . . . . . . . . . . . . . . 20 3.2. Arquitectura del sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2.1. IMU: Unidad de medición inercial . . . . . . . . . . . . . . . . . . . . 25 3.2.2. Módulo de interfaz con RosCopter . . . . . . . . . . . . . . . . . . . . 28 3.2.3. Módulos de simulación . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.2.4. Módulo para control del vuelo . . . . . . . . . . . . . . . . . . . . . . 31 3.3. Evaluación del Algoritmo de Control . . . . . . . . . . . . . . . . . . . . . . . 32 CAPÍTULO 4 – CONCLUSIONES Y TRABAJO FUTURO 37 4.1. Conclusiones ................................... 37 4.2. TrabajoFuturo .................................. 38 APÉNDICE A – CÓDIGO FUENTE DE LOS MÓDULOS DESARROLLADOS 39 A.1.Analizadorsintáctico ............................... 41 A.2.RosCopter..................................... 45 A.3.Simulación .................................... 48 1.3.1. Simulación ................................ 48 1.3.2. Simulación con entrada real . . . . . . . . . . . . . . . . . . . . . . . 51 A.4.ProgramadeControl ............................... 55 1.4.1. Go..................................... 55 1.4.2. Landing.................................. 59 APÉNDICE B – IMÁGENES Y PLANOS 61 B.1.Impresora3D ................................... 63 B.2. Planos de la impresión 3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 B.3.Montaje...................................... 67 APÉNDICE C – DIAGRAMA DE GANTT 69 MEMORIA EN INGLÉS 73 CONTENTS ....................................... 81 CHAPTER 1–INTRODUCTION ............................. 83 CHAPTER 2–ROS................................... 93 CHAPTER 3–BUILDING THE QUADROTOR .....................109 CHAPTER 4–FUTURE WORK .............................123 CHAPTER 5–CONCLUSION ..............................125 GLOSARIO 127 BIBLIOGRAFÍA 129 VIII CAPÍTULO 1 Introducción 1.1. Motivación y trabajo relacionado Este proyecto de investigación se enmarca en la creciente necesidad de construir un vehículo volador, ágil y rápido, con la suficiente flexibilidad en software para poder considerarlo una aeronave de desarrollo. Para ello, se consideró un cuadricóptero (helicóptero de cuatro rotores, como el ejemplo de la Figura 1.1) como plataforma y ROS1como sistema operativo. El primero, se eligió por su habilidad para mantener una posición estable en el aire y su capacidad para hacer maniobras complejas, y el segundo, por su fundamento modular, que permite programar tareas de forma independiente del robot que las vaya a ejecutar; esto permite la creación de una gran comunidad de desarrollo que ayuda a acelerar enormemente las investigaciones. En este contexto se inicia un proyecto desde cero en la Universidad de Luleå para construir y poner en marcha este UAV2. La fase de documentación y aprendizaje de las plataformas se ha realizado, en una gran mayoría, haciendo uso de comunidades y manuales online; por lo que el trabajo de las universidades y laboratorios que están actualmente inmersos en ello ha sido de gran ayuda. En particular se han estudiado trabajos de las siguientes cinco universidades. Por un lado, el CCNY Robotics Lab de New York está desarrollando, en cooperación con AscTec, el Pelican y el Hummingbird, cuyos paquetes de software están completamente recogidos en los repositorios de ROS. La Universidad de Pennsylvania tiene una larga lista de experimentos con Penn Quadrotors, incluyendo vuelos acrobáticos o juegos de luces con cuadricópteros cooperativos. El Cheetah BRAVO (Figura 1.1) de PixHawk está siendo desarrollado por la ETH de Zurich, y usa un sistema de cámaras estéreo para llevar a cabo la navegación en interiores. El Autonomy Lab, en la Universidad Simon Fraser de Canadá, está desarrollando un controlador basado en ROS para el Parrot AR.Drone (Figura 1.2), uno de los pocos cuadricópteros comerciales. Y por úl1Robotic Operating Sistem (Sistema Operativo para Robots), es un pseudo sistema operativo que usado en plataformas robóticas acelera y facilita el desarrollo, permitiendo el uso de módulos ya desarrollados y con varios lenguajes de programación. 2Unmanned Aerial Vehicle (Vehículo Aéreo no Tripulado) 1 8 INTRODUCCIÓN Figura 1.6: Cuadricóptero 1.5. Contenido de la memoria En este Capítulo 1 de la memoria se han resumido la motivación y los objetivos y se detalla el trabajo relacionado con vehículos aéreos no tripulados (UAVs) (Sección 1.4) y más concretamente con cuadricópteros (Sección 1.4.1). En el Capítulo 2 se habla de la estructura del cuadricóptero (Sección 2.1) comentando los distintos procesos de fabricación y del hardware que monta la aeronave (Sección 2.2). También se hace un repaso por las plataformas de seguridad empleadas (Sección 2.3). En el Capítulo 3 se repasa el software desarrollado. Enmarcado en este capítulo es donde se desarrollan la mayor parte de la documentación y las tareas de aprendizaje de uso de las plataformas (Sección 3.1). Posteriormente, el informe entra de lleno en la arquitectura de código (Sección 3.2), donde se repasan los módulos desarrollados de interfaz, simulación y control de vuelo. La Sección 3.3 presenta el control utilizado en las secciones anteriores. En el Capítulo 4 se exponen las conclusiones y las posibles vías de trabajo futuro. También se incluye el Apéndice A con los módulos de software desarrollados; el Apéndice B con los planos de la impresión 3D, fotografías de la impresora y del cuadricóptero montado; el Apéndice C con el diagrama de Gantt del proyecto; y el Apéndice D con la memoria original en inglés. CAPÍTULO 2 Diseño y construcción 2.1. Estructura y fijaciones El diseño y la estructura de un cuadricóptero es una parte fundamental para el buen funcionamiento del mismo. A pesar de ello, la realimentación de los motores (se utilizan los sensores para reajustar la velocidad de cada rotor) hace que la aeronave pueda volar en cualquier configuración e incluso después de perder alguno de los propulsores [13]. Pero esto no quita para que una buena estructura beneficie, y mucho, al correcto funcionamiento del mismo. (a) Brazo de aluminio (b) Brazo de plástico ABS Figura 2.1: Elementos estructurales usados en el cuadricóptero Es necesaria una estructura rígida para prevenir la rotura ante un posible accidente, pero también para conseguir las mínimas vibraciones, tanto en funcionamiento, como en el momento del despegue. No sólo la entrada en resonancia del cuadricóptero podría llegar a ser crítica, 9 10 HARDWARE: DISEÑO Y CONSTRUCCIÓN sino también una ligera vibración, ya que en el cuadricóptero va montada una serie de sensores y procesadores, y estas vibraciones pueden inducirlos a mediciones incorrectas o incluso a la larga, a roturas. El peso también es un atributo a tener en cuenta, ya que la autonomía y la agilidad se consideran dos de las características más importantes del helicóptero. Un peso bajo en el marco va a suponer un menor consumo y unas menores inercias. De este modo, en un primer momento se consideró el uso de un marco de aluminio (Figura 2.1a). Era ligero y, al no ser muy flexible, casi no transmitía las vibraciones desde los motores al núcleo central. Pero era ligero por ser una viga tubular con un espesor mínimo. Esto significa que la rigidez del mismo era también mínima. Al apreciar problemas ante las primeras caídas del cuadricóptero, que aunque desde poca altura, conseguían doblar las barras, se tomó la decisión de reemplazar esta estructura por cuatro brazos en celosía impresos en ABS1con una impresora 3D (Figura 2.1b), cuyo proceso de construcción se detalla a continuación. 2.1.1. Impresión 3D Figura 2.2: Impresora 3D usada en el proyecto Figura 2.3: Montaje del cuadricóptero para el prototipo impreso Una impresora 3D (en la Figura 2.2 se muestra la utilizada, a tamaño completo en el Apéndice B.1) es una máquina capaz de realizar “impresiones” de diseños en 3D, creando piezas o maquetas volumétricas a partir de un diseño hecho por ordenador. Surgen con la idea de convertir archivos CAD en prototipos reales. La impresión 3D está abriendo la puerta a un gigantesco mundo de posibilidades. Se pueden 1Acrilonitrilo Butadieno Estireno, es un plástico muy resistente al impacto (golpes) muy utilizado en automoción y otros usos tanto industriales como domésticos. Es un termoplástico amorfo. 2.2. HARDWARE 11 conseguir estructuras complejas, resistentes, ligeras y flexibles, con un presupuesto contenido. Para nuestro diseño, se ha optado por una celosía plana (como se puede ver en los brazos de la Figura 2.3) impresa en ABS. La flexibilidad de esta construcción junto con su resistencia la hacen perfecta para esta tarea. Figura 2.4: Plano de los platos de soporte usados en prototipo impreso De la misma manera se han impreso los platos de soporte (Figura 2.4) que unirán la estructura y servirán de apoyo para la electrónica de la aeronave. Aprovechando las posibilidades brindadas por la impresión 3D se han dejado las plataformas preparadas para distintos soportes de hardware, realizando agujeros que puedan servir para otras plantillas. De esta forma podremos adaptar la estructura a diferentes configuraciones, a la vez que reduciremos el peso. Más detalles de las piezas impresas y la impresora 3D utilizada en el Apéndice B. 2.2. Hardware Una vez descrita la estructura de base del cuadricoptero, esta sección describe el hardware y componentes electrónicos del prototipo. 2.2.1. Arducopter Nuestro diseño (presentado en la Figura 2.5 y en el Apéndice B.3) parte de la plataforma ArduCopter. ArduCopter es una plataforma comercial que sirve de base para construir helicópteros multirotor y otros muchos robots. ArduCopter es basicamente una placa de Arduino2[14] modificada (ArduPilot Mega, en adelante APM) unida a una placa de sensores. Gracias a Arduino y a la gran comunidad que ambos tienen es posible encontrar una gran cantidad de modificaciones para la plataforma Ar2Arduino es una plataforma de hardware libre, basada en una placa con un microcontrolador y un entorno de desarrollo, diseñada para facilitar el uso de la electrónica en proyectos multidisciplinares. 12 HARDWARE: DISEÑO Y CONSTRUCCIÓN Figura 2.5: Cuadricóptero de fabricación propia duCopter con las cuales puede ser facilmente adaptado a aplicaciones específicas. Este sistema contiene una IMU (unidad de sensores inerciales), que proporciona magnitudes de medida para tres direcciones tanto en el caso del acelerómetro como en el del giróscopo, también incluye un magnetómetro de tres grados de libertad y una unidad de XBee [15] para comunicaciones inalámbricas. Además, esta placa proporciona un sistema de cuaternios [16] con el cual se puede calcular el sistema de ángulos de Euler [17] y medir cómo el cuadricóptero está posicionado. Un GPS conectado a la placa del APM se usa para estimar la posición tridimensional del aparato. Por último, hay una placa de distribución de potencia controlada por el APM, esta placa controla los ESC (Electronic Speed Controller, o en español, Controlador Electrónico de Velocidad) de los motores. En la Figura 2.6 se muestra un esquema de las partes. El kit ArduCopter también puede incluir otro componente muy importante del cuadricoptero, las hélices. Es un componente clave, ya que de sus características y de cómo están montadas va a depender que pueda lograr la sustentación requerida para volar. La estabilización en vuelo en este tipo de máquinas voladoras se logra gracias a dos fuerzas opuestas [18]. La fuerza que empuja el UAV hacia abajo es la gravedad, por ello, se necesita crear una fuerza opuesta de la misma magnitud para conseguir mantener el vehículo en el aire. Esta fuerza es generada por las hélices, que crean un área de baja presión sobre las superficies superiores de las mismas. 2.2. HARDWARE 13 Figura 2.6: Componentes del kit ArduCopter Estas hélices son capaces de cambiar los ángulos del cuadricóptero. En la Figura 2.7 (a), en negro, se presenta la estructura del cuadricóptero. Los ejes del cuerpo rígido se muestran en verde, mientras que en azul se representa la velocidad angular de las hélices. La posición relativa del cuadricóptero es representada mediante los giros Roll-Pitch-Yaw: El giro Roll es proporcionado por el incremento (o decremento) en la velocidad de la hélice izquierda y por el decremento (o incremento) en la derecha. Esto genera un momento con respecto al eje XBque hace girar al cuadricóptero. La Figura 2.7 (b) muestra el giro Roll en el esquema del cuadricóptero. Figura 2.7: a) Esquema de motores simplificado de un cuadricóptero en posición de estabilidad y b) Movimiento Roll, giro en torno al eje X 14 HARDWARE: DISEÑO Y CONSTRUCCIÓN El Pitch es muy similar al Roll y es proporcionado por el incremento (o decremento) en la velocidad de la hélice trasera y por el decremento (o incremento) en la delantera. En este caso, se genera un momento con respecto al eje YBque de nuevo hace girar el cuadricóptero. La Figura 2.8 (a) muestra el giro de Pitch en el esquema. Figura 2.8: a) Movimiento Pitch, o giro en torno al eje Y y b) Movimiento Yaw, o rotación en torno al eje Z El Yaw es creado por el incremento (o decremento) de las velocidades de las hélices delantera y trasera y por el decremento (o incremento) de las velocidades en las hélices laterales. Esto crea un momento con respecto al eje ZBque hace al cuadricóptero rotar. El movimiento de Yaw es generado gracias al hecho de que las hélices laterales giran en sentido horario, mientras que la delantera y la trasera lo hacen en antihorario. De este modo, cuando el momento del conjunto está desequilibrado, el helicóptero gira en torno aZB. La Figura 2.8 (b) muestra un esquema con el movimiento de Yaw. [19] Gracias a todo esto, un cuadricóptero se convierte en una aeronave estable que, por lo tanto, puede ser usada en interiores, pero puede también ser una máquina peligrosa, ya que es rápida y capaz de girar y cambiar de dirección en poco tiempo. En consecuencia, perder el control del cuadricóptero puede suponer su destrucción o la de su entorno, e incluso ocasionar daños personales, por lo cual es necesario utilizar plataformas de seguridad como las descritas en la Sección 2.3. Conexión remota con ArduCopter En este proyecto se usará un cuadricóptero estándar ArduCopter que será conectado con una estación de tierra mediante un XBee [15]. La conexión de serie MAVlink3[21] proveerá datos sobre attitude (pose - orientación y velocidad en los ángulos de Euler), vfr_hub (velocidad del suelo y del aire, altitud y tasa de subida), GPS y RC (el valor de los 8 canales de frecuencia de radio). Esta conexión de serie también proporcionará heartbeat (latido del corazón - los sistemas pueden usar este mensaje 3MAVlink es un ligero protocolo de comunicación mediante mensajes con cabecera ampliamente usado en ROS. 2.2. HARDWARE 15 Figura 2.9: Conexión MAVlink entre máquinas voladoras y una estación de tierra. Las lineas de puntos representan conexiones p2p MAVlink [20] para monitorizar si el sistema está operativo); navigation controller output (registro del control de navegación - con información sobre objetivos y errores); hardware status (estatus del hardware - voltaje de la placa); raw IMU (valores sin procesar de la IMU - valores de aceleración, giróscopo y brújula); pressure (presión); y algunos parámetros más de los que no se dará uso en este sistema, mientras que esta misma conexión será usada para enviar la velocidad y los ángulos de Euler requeridos. En la Figura 2.9 se muestra una configuración de red típica entre varios robots aéreos y una estación de tierra usando dispositivos XBee. 2.2.2. Sensores Los datos enviados por el protocolo MAVlink son generados por una serie de sensores de a bordo, mencionados anteriormente. Esta sección detalla los sensores utilizados. Una IMU (cuyo funcionamiento, por ser parte básica del kit ArduCopter, se ha detallado en parte en la Sección 2.2.1 y se acabará de ahondar en ello en la Sección 3.2.1); el módulo de GPS de MTek ((a) en la Figura 2.10) que nos permine controlar el cuadricóptero en exteriores con una precisión de unos 3 metros y con una buena estabilidad; un barómetro, que usa la presión atmosférica para conocer la altitud; y un módulo de ultrasonidos LV-EZ0 que permite afinar hasta pocos centímetros la posición relativa con el suelo. Tanto el módulo de GPS y de ultrasonidos como el barómetro son elementros recomendados para ArduCopter, sin ser piezas estándar. Para envíos y recepción de datos se utiliza un adaptador de conexión de serie XBee Explorer Regulated ((e) en la Figura 2.10) conectado a través del puerto UART0 del APM. A éste se le conectará un módulo XBee Pro 60mW Wire Antenna - Series 1 (802.15.4) de Digi International ((c) en la Figura 2.10), el cual hace uso de la tecnología ZigBee para mantener una buena 16 HARDWARE: DISEÑO Y CONSTRUCCIÓN Figura 2.10: Sensores utilizados en la construcción del cuadricóptero comunicación con la estación de tierra manteniendo bajo el consumo. Este dispositivo permite también rangos de transmisión de incluso más de 1 kilómetro en campo abierto. En el caso de usarse un ordenador, el adaptador a usar será el XBee Explorer Dongle, (d) en la Figura 2.10. También está disponible un control remoto Futaba para ser usado en casos de emergencia. Si algo sucede y el cuadricóptero pierde el control, el operador es capaz de cambiar a modo de control manual únicamente pulsando un interruptor en el mando. Usando otro modo, con este mismo interruptor, también es posible llevar a cabo un aterrizaje de emergencia (el módulo de código está disponible en el Apéndice 1.4.2). Registrando la altura específica desde la que comienza la maniobra, el cuadricóptero puede alcanzar la altura cero, reduciendo progresivamente la potencia en los motores y usando alturas intermedias para estabilizarse. Se puede encontrar más información sobre los sensores utilizados en el Apéndice D en Section 3.1. 2.3. Plataformas de seguridad La posibilidad de hacer uso de esta aeronave en interiores junto con su capacidad para cambiar de dirección rápidamente, su agilidad y su velocidad, la convierten (ante un posible fallo) en una máquina peligrosa. En consecuencia, perder el control del cuadricóptero puede llevarlo a destruirse a sí mismo o a su entorno, así como a dañar a alguien. En nuestro laboratorio, y para ensayar el módulo de código en un entorno seguro, se ha construido una plataforma de seguridad consistente en un cable vertical con amortiguadores (en Figura 2.11). El cuadricóptero está anclado a él y puede rotar y elevarse. Hay también una red de seguridad entre el cuadricóptero y los operadores. Para las pruebas en exteriores (Figura 2.12) se ha considerado suficiente el uso de un cable 2.3. PLATAFORMAS DE SEGURIDAD 17 Figura 2.11: Laboratorio de la LTU con un sistema de seguridad para cuadricópteros de 10 metros al que se ha fijado el cuadricóptero en los momentos de ensayo. Este cable está anclado a una fijación en un patio interior al que se veta la entrada durante los ensayos. El cable cumple el cometido de impedir que el helicóptero salga de la zona de seguridad o impacte contra paredes o personas. Figura 2.12: Área de pruebas exteriores para cuadricópteros de la LTU 24 SOFTWARE: PROGRAMACIÓN Y DESARROLLO la variable tolerance a usar la variable tolerance2. Figura 3.4: Simulación de un cuadricóptero Hector Este controlador puede mover el cuadricóptero en las direcciónes X, Y y Z. También puede ser controlada la orientación para mantenerse siempre estable y dirección Norte. El código completo de esta simulación se ha incluido en el Apéndice 1.3.1. En la Figura 3.4, se muestra el cuadricóptero simulado siguiendo un casi perfecto cubo (la línea roja representa la ruta seguida). En el siguiente ensayo de simulación se ha probado a controlar el movimiento con un cuadricóptero real para analizar una verdadera interoperabilidad entre plataformas y redes. Este simulador toma la lectura de los ángulos de Euler directamente desde la plataforma experimental del cuadricóptero para mostrar ese mismo movimiento en el cuadricóptero virtual. El eje Z puede ser rotado para rotar en la simulación, el eje X para avanzar en dirección Y y el eje Y para avanzar en dirección X, tal y como sería el movimiento si los motores del cuadricóptero lo hicieran inclinarse en Roll, Pitch o Yaw. Para lograr esto se ha necesitado usar un controlador para mover el cuadricóptero virtual desde la posición original (la virtual) hasta la posición objetivo (la real) de forma similar al código anterior. Para estos ensayos, se ha utilizado el marco experimental (Figura 3.5) y una IMU, el KFly, ambos diseñados por Emil Fresk. Esta estructura ha sido impresa en las instalaciones de la LTU con una impresora 3D hecha a mano, y ha sido ensayada su resistencia a axial y cortante. El código completo, en este caso, se incluye en el Apéndice 1.3.2. Se puede encontrar más información sobre Hector en el Apéndice D en Section 2.3. 3.2. ARQUITECTURA DEL SISTEMA 25 Figura 3.5: Prototipo de la estructura del cuadricóptero 3.2. Arquitectura del sistema En el diagrama de bloques de la Figura 3.6 se representa una visión general de la arquitectura del sistema de desarrollo. En el primer módulo, en rojo (y a la izquierda), se muestra esquematizada la organización de ROS. En este módulo, las elipses son programas (o nodos) y los rectángulos son temas (o topics). Los programas utilizan la información proporcionada por los temas para llevar a cabo su tarea y vuelven a volcar ahí sus resultados. El programa de interfaz /RosCopter sirve de traductor y puente entre esos temas y la información enviada desde Arduino. En el módulo central, en amarillo, se representa el envío de información a través de XBee. Los mensajes son enviados mediante un protocolo estándar llamado MAVlink. En el tercer módulo, en verde (y a la derecha), se sitúa el sistema ArduCopter. Tiene un módulo APM, que es el dispositivo inteligente de a bordo. Puede procesar tareas simples de control, lee los sensores de medida y controla el movimiento de los motores. Recibe información de los registros del módulo de GPS y de la unidad de medida inercial (IMU). La IMU lee el magnetómetro y el sónar externos. Por último, el sistema ArduCopter incluye una placa de distribución controlada por el APM que manda las señales de control a los ESC. 3.2.1. IMU: Unidad de medición inercial Una unidad de medición inercial, o IMU, es un sistema para la medida del movimiento de un objeto en espacio libre relativo a un marco inercial. Los sensores usados para la medida inercial son fundamentalmente acelerómetros y giróscopos. Un acelerómetro triaxial puede medir tres grados de libertad. Si puede asumirse que un objeto 26 SOFTWARE: PROGRAMACIÓN Y DESARROLLO System ArduCopter XBee ROS Programa 3 /roscopter MAVlink mag GPS IMU Autopilot ESC motors Power distribution Topics Programa 1 Programa 4 Programa 2 Programa 5 sonar Figura 3.6: Diagrama de Nodos únicamente tiene o translaciones o rotaciones, entonces un acelerómetro triaxial es suficiente para medirlas. En la tierra, siempre hay presente una fuerza gravitacional de 1G. Asumiendo rotación sin translación, un acelerómetro triaxial puede ser usado para medir la inclinación utilizando la orientación de este vector gravitatorio de 1G. Si los datos del sensor muestran una aceleración constante de 1G en una orientación fija por un tiempo determinado, entonces uno puede adivinar que el sujeto está en una postura estática. Para distinguir entre rotación y translación, con frecuencia se hace uso de giróscopos. Un giróscopo tradicional consiste en un rotor con giro libre para mantener el momento angular y por lo tanto su orientación original. Hoy en día, giróscopos de estructura vibrante reemplazan los rotores por masas de prueba que vibran. Éstas también tienen el efecto de mantener la orientación original pero pueden fabricarse en tamaños más pequeños y, por consiguiente, pueden ser más económicos. La desviación de la orientación original puede ser medida para obtener la rotación en términos de ángulo y velocidad angular. Después de cancelar la proyección de la rotación en tres ejes, la aceleración lineal remanente puede ser interpretada como translación. Sin embargo, los giróscopos también tienen sus problemas. Cada giróscopo está limitado por la velocidad angular máxima que puede tolerar antes de que la orientación original del rotor o de la estructura vibrante cambien. Otro problema es el consumo relativamente alto comparado con los acelerómetros. [28] La IMU que se va a utilizar, como se ha comentado anteriormente, ha sido diseñada y ensamblada en los laboratorios de la Universidad Técnica de Luleå por E. Fresk [1] (Figura 3.7). En dicha IMU, a estos dos sensores se les añade un magnetómetro para registrar las direcciones y magnitudes del campo magnético en los tres ejes. Un magnetómetro es un instrumento de medida usado para determinar la fuerza en una dirección concreta del campo magnético. Si este sensor es puesto en una localización donde las propiedades del campo magnético de la tierra son conocidas, puede determinarse la orientación del vehículo. Sin embargo, no se puede ob- 3.2. ARQUITECTURA DEL SISTEMA 27 tener una completa estimación de la postura, ya que no se pueden detectar las rotaciones sobre el vector del campo magnético. Para solucionar esto, se puede hacer uso de una estimación indirecta de la medida con los acelerómetros de la IMU. Figura 3.7: Módulo de medición inercial Parser (Analizador sintáctico) Para interactuar con este dispositivo, se ha desarrollado un analizador sintáctico que, leyendo el puerto de serie al que está conectado el dispositivo, puede extraer e interpretar las medidas de los sensores. El código, después de inicializar las variables, puertos y parámetros adecuados, comienza una lectura inicial del puerto de serie para sincronizar la lectura con la escritura. Lee lo que hay almacenado en ese puerto (vaciándolo), proceso que se repite hasta conseguir una cadena completa. Sabremos que esta cadena es completa porque el byte dos del vector leído nos indicará la longitud y, a su vez, sabremos que la cadena empieza en el lugar adecuado por que las cadenas siembre empiezan con el valor hexadecimal 0xa6. Una vez que se ha hecho la sincronización, se entra en un bucle infinito (que no se corta a no ser que ROS se detenga). De la cadena de datos se pueden sacar los valores detallados en la siguiente Tabla 3.1. Nombre SYNC CMD SIZE CRC8 DATA CRC-16-CCITT SYNC CMD SIZE CRC8 Tamaño 1 byte 1 byte 1 byte 1 byte 0 - 255 bytes 2 byte 1 byte 1 byte 1 byte 1 byte Valor 0xa6 0x19 0x22 0x31 - - - - - - Tabla 3.1: Estructura del paquete de datos de la unidad de medida KFly 28 SOFTWARE: PROGRAMACIÓN Y DESARROLLO En esta tabla el bloque DATA corresponde a 4 bytes para cada una de las cuatro componentes de cuaternio5(qi) y 2 bytes para cada una de las componentes de la aceleración lineal (ai), la angular (wi) y el campo magnético (mi). Este programa también transforma los valores del cuaternio en los ángulos de Euler (Roll, Pitch y Yaw), aun cuando estos valores no se pasarán al mensaje de ROS. Con eso ya se puede crear el mensaje para ROS y almacenar en él todos los parámetros considerados necesarios. El código completo se encuentra en el Apéndice A.1. Conclusión Pese a haber conseguido traducir estos datos a variables sensibles de ser usadas, se ha considerado desestimar esta vía de trabajo para la construcción del primer prototipo por varios motivos. En primer lugar, al no ser el protocolo de datos usado por KFly un protocolo estándar, no daba pie al uso de los paquetes AutoPilot que actualmente hay en los repositorios de ROS. En el caso de ser usados, conllevaría una enorme cantidad de tiempo la modificación de estos para su uso con la nueva estructura de datos. En segundo lugar, el uso en una primera instancia de KFly requería un ordenador de a bordo, el cual aumentaba el peso por encima de valores recomendables. En las fases finales de trabajo se empezó a adaptar esta unidad para su uso junto con una unidad de XBee para enviar los datos a la estación de tierra sin necesidad de ordenador de a bordo. Además, el módulo de código final constituye por sí solo un AutoPilot, por lo que también sufraga el otro problema para futuras versiones del prototipo. 3.2.2. Módulo de interfaz con RosCopter La interfaz que se ha adaptado entre ArduCopter y ROS es un código en Python que conecta la máquina de la estación de tierra con ArduCopter usando XBee y creando temas y servicios para establecer una buena comunicación. El código, adaptación de RosCopter [30], se puede encontrar en el Apéndice A.2 En este módulo se crea una conexión entre el XBee en ArduCopter y el XBee en la estación de tierra usando el protocolo MAVlink. Arranca los editores (publishers) para GPS, RC (señal del control de radio), state (armado, GPS disponible y actual modo), vfr_hub (velocidad del viento, velocidad del suelo, orientación, velocidad, altitud y tasa de subida), attitude (ángulos y velocidades de Euler) y raw_IMU. También arranca los subscriptores (subscribers) para send_rc (será el tema usado para enviar comandos) y los servicios para armar y desarmar el cuadricóptero. Ahora, en el cuerpo principal del módulo se crea el nodo (“roscopter”) y se almacena el mensaje enviado desde ArduCopter con la función recv_match. El mensaje 5Extensión de los números reales, similar a la de los números complejos. Mientras que los números complejos son una extensión de los reales por la adición de la unidad imaginaria i, tal que i2=−1, los cuaternios son una extensión generada de manera análoga añadiendo las unidades imaginarias: i,jyka los números reales y tal que i2=j2=k2=i jk =−1. En este caso se utiliza para representar la matriz de rotación de Euler. [29] 3.2. ARQUITECTURA DEL SISTEMA 29 es comprobado y se publica en el tema correspondiente dependiendo del tipo de mensaje. Por otro lado, cada vez que un mensaje es enviado a send_rc, se lanza un callback6para enviar los datos a ArduCopter. 3.2.3. Módulos de simulación En la Figura 3.8 se presenta el diagrama de bloques utilizado para pruebas en simulación. Éste representa una vista general de la simulación que combina el cuadricóptero virtual con el real, situación descrita en la Sección 3.1.2. El diagrama de simulación pura sólo incluiría el bloque ROS (a la izquierda); de este bloque habría que eliminar también el tema “/attitude” y el nodo “/roscopter”. En este caso, el control es gestionado por el paquete pr2_teleop. Este paquete usa las interrupciones de teclado para modificar el tema cmd_vel, el cual controla la velocidad en la gran mayoría de robots ROS. System ArduCopter XBee ROS Simulation /roscopter /simulate /attitude MAVlink Hector /poseupdate Gazebo /cmd_vel /hector_maping /initial_pose /map /gazebo mag GPS IMU Autopilot ESC motors Power distribution sonar Figura 3.8: Arquitectura del sistema usado para simulación El módulo ROS, en azul (y a la izquierda), emplea tres programas básicos para llevar a cabo su tarea. En el área central, Simulation, el nodo “/simulate” es el responsable de realizar el control. Éste lee los datos de ArduCopter (a través del nodo “/roscopter”) y del bloque Hector y actúa en el comando de velocidad del cuadricóptero (velocidades de Roll, Pitch y Yaw). En la parte superior, Hector, el nodo “/hector_maping” crea el mundo y gestiona el mapa de SLAM que el UAV está viendo. Utiliza parámetros físicos para dar forma al robot y situarlo en Gazebo.Hector usa el tema /poseupdate para compartir la posición en los tres ejes y el 6Un callback es una función “A” que se usa como argumento de otra función “B”. Cuando se llama a “B”, ésta ejecuta “A”. Para conseguirlo, usualmente lo que se pasa a “B” es el puntero a “A”. 30 SOFTWARE: PROGRAMACIÓN Y DESARROLLO cuaternio. Gazebo yhector_maping están también conectados con el tema /scan (omitido en la imagen para mejorar su comprensión). Con este tema, Hector sabe cómo es el mundo para poder dibujar su mapa de SLAM. Hector también necesita una posición inicial (/initial_pose). Esto permite la utilización de cualquier tipo de mapa sin problemas. Esta posición inicial tiene que ser una posición despejada, sin otros objetos. Por otra lado, en la parte inferior, Gazebo gestiona la física (con los parámetros provistos por Hector) en la simulación y crea las visualizaciones del cuadricóptero en un mapa tridimensional. El módulo de código completo utilizado en las simulaciones puede encontrarse en el Apéndice 1.3.2. En este programa, todas las partes activas están en los callbacks. De los cuales hay dos. El primero se ejecuta cuando hay una actualización en el tema “attitude” que almacena los ángulos de Euler y sus velocidades. El segundo se lanza cuando la actualización ocurre en el tema “poseupdate” que almacena la simulación del cuaternio. El callback “poseupdate” transforma el cuaternio a los ángulos de Euler Roll, Pitch y Yaw y los almacena en variables globales. El callback “attitude” se encarga del control. Figura 3.9: Respuesta de la rotación manual en la simulación En la Figura 3.9 se aprecia cómo, en el cuadricóptero virtual, el ángulo Yaw cambia cuando el ángulo en el cuadricóptero real cambia. Con esta prueba se pretende estudiar el seguimiento que el simulador es capaz de hacer a los sensores reales, el retraso que sufre debido a la lectura y envío de datos, y la sobreoscilación que pudiera tener. Pese a no ser una prueba perfecta que 3.2. ARQUITECTURA DEL SISTEMA 31 pueda representar el funcionamiento del control de posición implementado en el simulador, ya que la señal de entrada no es del todo estable (el objetivo se establece a mano), puede verse una rápida respuesta y un perfecto seguimiento. No se aprecia nada de sobreoscilación y el tiempo de respuesta podría establecerse en torno a los dos segundos; retraso debido al envío de datos mediante XBee y a la física propia del cuadricóptero en el simulador. Esta prueba ha sido repetida con iguales resultados en dos ocasiones más, considerando válido el experimento. 3.2.4. Módulo para control del vuelo Se han desarrollado diferentes programas para mover el cuadricóptero y todos ellos pueden ser llamados desde distintos parámetros en la función go, cuyo módulo de código (en Python) está disponible en el Apéndice 1.4.1). De este modo, es posible navegar con puntos vía, rotar a un ángulo concreto o ir a una altitud específica. Hay también un programa de seguridad para despegue o aterrizaje del cuadricóptero. En la Figura 3.10 se representa el diagrama de trabajo del cuadricóptero. Consiste en tres módulos. El primero, rojo en la figura (izquierda), es el sistema ROS que tiene las mediciones de los sensores (posición global, ángulos de Euler, canales RC o estado del cuadricóptero) y puede actuar en los ángulos Roll y Pitch y en la velocidad de cambio del ángulo Yaw a través de los parámetros del control remoto. Usa dos programas para llevar a cabo su tarea: el principal, /go; y la interfaz, /roscopter. El programa principal es usado para cerrar el bucle de control. Los otros dos bloques ya han sido explicados en la introducción de esta sección. System ArduCopter XBee ROS /go /roscopter MAVlink mag GPS IMU Autopilot ESC motors Power distribution /send_rc /attitude /gps /rc /vfr_hub sonar Figura 3.10: Diagrama de nodos del control de vuelo 32 SOFTWARE: PROGRAMACIÓN Y DESARROLLO 3.3. Evaluación del Algoritmo de Control Se usará la plataforma ROS para realizar el control, ya que temas y nodos son buenas herramientas para hacer un control discreto. No es necesario crear bucles periódicos ni una discretización porque los datos son enviados periódicamente desde ArduPilot al sistema ROS a través de MAVlink. Esto significa que el programa de ROS ejecutará la actualización de temas periódicamente, cuando aparezca un nuevo mensaje en el tema. Figura 3.11: Respuesta al escalón en rotación en el rango de ángulos [90o,-90o] Se han ensayado varios controles para conseguir una rápida respuesta, evitando todo lo que sea posible la sobreoscilación, y logrando una rápida estabilización. Control Proporcional En un primer intento se usó un control proporcional para probar las similitudes entre el rendimiento del cuadricóptero real y el de la simulación. Para este experimento, y con el cuadricóptero fijado al cable de seguridad (limitando sus movimientos en el plano horizontal) volando a una altura constante de 1,5my partiendo desde la orientación 0◦, se lanzó un comando de rotación vía terminal de comandos desde el entorno de ROS a +90◦, pasados 35 segundos se 3.3. EVALUACIÓN DEL ALGORITMO DE CONTROL 33 modificó la referencia a -90◦. Los resultados de la prueba mostraron una ganancia no unitaria y un desplazamiento en la respuesta tal y como puede verse en la Figura 3.11. Esto es debido a la aparición de perturbaciones externas y al umbral de arranque de los motores. Aquí, puede verse tanto que el ángulo nunca alcanza el valor deseado, como que los motores no tienen suficiente velocidad al empezar el movimiento. También es posible ver un error mayor en la zona positiva causado por un pequeño desequilibrio en la velocidad cero. Figura 3.12: Respuesta al escalón en rotación en el rango de ángulos [90◦,-90◦] con una constante proporcional mayor Control Proporcional con alta ganancia Con la misma configuración del experimento anterior, aunque en este caso realizando un giro a -90◦seguido de otro a +90◦30 segundos después, y admitiendo una ligera sobreoscilación, con algunos ajustes más en la constante del proporcional es posible solucionar la mayoría del umbral de arranque de los motores. Con este tipo de controlador, y aumentando la constante proporcional, se puede lograr amplificar la lectura del error, consiguiendo así corregir hasta errores pequeños. El problema es que también se crea un sistema más nervioso, propenso a la sobreoscilación, y que ante un cambio de entrada grande puede llegar incluso a inestabilizar el sistema. De esta forma, y aunque se pueden minimizar los errores, es imposible conseguir una ganancia unitaria (Figura 3.12) y, por lo tanto, se aplicará un controlador PID. A.1. ANALIZADOR SINTÁCTICO 41 A.1. Analizador sintáctico 1# include < ros / ros .h > # include < se nsor _msg s / Imu .h > 3# include <stdio.h> /* Standard input / output defini tions */ # include < string .h > /* String function definitions */ 5# include < unistd .h > /* UNIX standard function definitions */ # include <fcntl.h> /* File control definitions */ 7# include <errno.h> /* Error number definitions */ # include < te rmi os .h > /* POSIX terminal control definitions */ 9# include <iostream > 11 #define PI 3.14159 13 struct imu { 15 struct orientation { 17 float x; float y; 19 float z; float w; 21 } ; struct angular_velocity 23 { float x; 25 float y; float z; 27 } ; struct linear_acceleration 29 { float x; 31 float y; float z; 33 } ; } ; 35 struct euler 37 { float roll; 39 float pitch; float yaw ; 41 } ; 43 float toDegrees(float radians ) { 45 return radians *180/ PI ; 47 } euler Quater nionToRo ll ( float x , float y, float z , float w) 49 { float test=x*y+z*w; 51 float roll , pitch , yaw ; euler solution ; 53 if ( test > 0.499) { // singularity at north pole pitch = (2 * atan2 (x, w)); 55 yaw = (PI / 2); roll = 0; 57 so lut ion . roll = toDegrees ( roll ); solution . pitch = toDegrees ( pitch ); 59 so lution . yaw = to Degr ees ( yaw ) ; return solution; 42 APÉNDICE A 61 } if ( test < -0.499) { // singularity at south pole 63 pitch = ( -2 * atan2 (x, w)); yaw = (-PI / 2) ; 65 roll = 0; so lut ion . roll = toDegrees ( roll ); 67 solution . pitch = toDegrees ( pitch ); so lution . yaw = to Degr ees ( yaw ) ; 69 return solution; } 71 float sqx = x * x; float sqy = y * y; 73 float sqz = z * z; pitch = atan2 (2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz ); 75 yaw = asin (2 * test); roll = atan2 (2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); 77 so lut ion . roll = toDegrees ( roll ); solution . pitch = toDegrees ( pitch ); 79 so lution . yaw = to Degr ees ( yaw ) ; return solution; 81 } 83 float FourIntsToInt ( unsigned char buffer [34] , int i) 85 { unsigned long Hex Number_aux = buffer [i +0]|( buffer [ i+1] < <8) |( buffer [i +2] < <16) |( buffer [i +3] < <24); 87 union u { unsigned long HexNumber_aux2; float solution; }; 89 float solution = u{ HexNumber_aux }. solution ; 91 return solution; 93 } 95 float TwoIntsToInt(unsigned char buffer [34] , int i) { 97 unsigned long Hex Number_aux = buffer [i +0]|( buffer [ i+1] < <8) ; 99 union u { unsigned long HexNumber_aux2; float solution; }; float solution = u{ HexNumber_aux }. solution ; 101 103 return solution; } 105 int main(int argc , char * argv []) 107 { 109 ros :: init ( argc , argv , "telemetry"); 111 ros :: NodeHandle nh ; 113 ros :: Publi sher imu Data _pub = nh . adve rtise < se nsor _msg s :: Imu >( " imuData ", 1000); 115 ros :: Rate l oop_ra te (10) ; 117 float q0 , q1 , q2 , q3 ; float ax , ay , az , wx , wy , wz , mx , my , mz ; 119 euler euler_angles; 121 // Open buffer_file int buffer_file ; A.1. ANALIZADOR SINTÁCTICO 43 123 open("/ as cte c_a utopilot - RelW it hD ebInfo @a sctec _a ut opilot / src / i muDat a . data " , O_CREAT ,( mode_t )0600); buffe r_fi le = open ("/ asct ec_autop ilo t - R el WithD eb In fo @asct ec _a utopi lo t / src / imuDa ta . data " , O_WRONLY); 125 int nw ; 127 // Initialize port int fd = open ( "/ dev / ttyACM0 " , O_RDONLY | O_NOCTTY); 129 if (fd == -1) /* Could not open the port . */ ROS_INFO(" open_port : Unable to open / dev /ttyACM0 - " ); 131 else ROS_INFO(" All right " ); 133 // Read serial port 135 unsigned char buffer [128] = { 0}; int n = read ( fd , buffer , sizeof( buffer )); 137 // We only want full chains 139 while (( buffer [0] == 0) || (n != buffer [2] + 6) || ( buffer [0] != 0 xa6 )) { 141 for (int i = 0; i < n; i ++) buffer [ i] = 0; 143 while (( buffer [0] == 0) || (n < 4) ) { 145 n = read (fd , buffer , sizeof( buffer ) ); } 147 } 149 unsigned char recievedData [ buffer [2]]; 151 while ( ros :: ok () ) 153 { 155 // Look for the first sync byte // This test is always successful if ( buffer [0] != 0 xa6 ) 157 { // sleep (0.02) ; 159 n = 0; for (int i = 0; i < n; i ++) 161 buffer [ i] = 0; while (( buffer [0] = 0) || ( n != buffer [2] + 6) ) 163 { for (int i = 0; i < n; i ++) 165 buffer [ i] = 0; n = read (fd , buffer , sizeof( buffer ) ); 167 while (( buffer [0] = 0) || ( n < 4)) { 169 n = read (fd , buffer , sizeof( buffer ) ); } 171 } } 173 // Store data values 175 for (int i = 4; i < ( buffer [2] + 4); i ++) if (i < n) 177 recievedData [i - 4] = buffer [i]; 179 q0 = FourIntsToInt ( recievedData , 0); q1 = FourIntsToInt ( recievedData , 4); 181 q2 = FourIntsToInt ( recievedData , 8); q3 = F ou rI ntsT oI nt ( re cie ved Data , 12) ; 183 ax = T wo Ints To Int ( r eci evedData , 16) ; 44 APÉNDICE A ay = T wo Ints To Int ( r eci evedData , 18) ; 185 az = T wo Ints To Int ( r eci evedData , 20) ; wx = T wo Ints To Int ( r eci evedData , 22) ; 187 wy = T wo Ints To Int ( r eci evedData , 24) ; wz = T wo Ints To Int ( r eci evedData , 26) ; 189 mx = T wo Ints To Int ( r eci evedData , 28) ; my = T wo Ints To Int ( r eci evedData , 30) ; 191 mz = T wo Ints To Int ( r eci evedData , 32) ; 193 euler_angles = QuaternionToRoll (q0 ,q1 , q2 ,q3 ) ; char data [128]= "Hi nikhil , How are u?"; 195 nw = write ( buffer_file , data ,128) ; 197 senso r_msgs :: Imu imuMsg ; imuMsg . header . frame_id = " imu " ; 199 imuMsg . header . stamp = ros :: Time :: now () ; imuMsg . header . seq ++; 201 imuMsg . orientation .x = q0; imuMsg . orientation .y = q1; 203 imuMsg . orientation .z = q2; imuMsg . orientation .w = q3; 205 imuMsg . angular_velocity .x = wx; imuMsg . angular_velocity .y = wy; 207 imuMsg . angular_velocity .z = wz; imuMsg . linear_acceleration . x = ax ; 209 imuMsg . linear_acceleration . y = ay ; imuMsg . linear_acceleration . z = az ; 211 n = 0; 213 for (int i = 0; i < n; i ++) buffer [ i] = 0; 215 while (( buffer [0] = 0) || ( n != buffer [2] + 6) ) { 217 for (int i = 0; i < n; i ++) buffer [ i] = 0; 219 n = read (fd , buffer , sizeof( buffer ) ); while (( buffer [0] = 0) || ( n < 4)) 221 { n = read (fd , buffer , sizeof( buffer ) ); 223 } } 225 imuDa ta_pub . publish ( imuMsg ) ; 227 ros :: spinOnce (); 229 } 231 return 0; } A.2. ROSCOPTER 45 A.2. RosCopter # !/ usr / bin / env python 2import roslib ; roslib . load_manifes t (’roscopter’) import rospy 4from std_msgs.msg import String , Header from std_srvs.srv import * 6from senso r_ msgs . msg import NavSatFix , NavSatStatus , Imu import roscopter.msg 8import sys , struct , time , os 10 sys . path . insert (0 , os . path . join ( os . path . dirname ( os . path . realpat h ( __fi le__ ) ), ’../ mavlink / pymavlink’)) 12 from optparse import OptionParser 14 parser = OptionParser (" roscopter . py [ options ]") 16 parser . add_option ("--baudrate", dest = "baudrate", type = ’int ’ , help=" master port baud rate " , default=57600) 18 parser . add_option (" -- device " , dest = " device ", default="/ dev / t tyU SB0 " , help = "serial device") parser . add_option (" -- rate " , dest =" rate " , default =10 , type = ’int ’, help =" requeste d stream rate " ) 20 parser . add_option (" -- source - system " , dest = ’ SOU RCE_ SY STEM ’ , type = ’int ’ , de fault =255 , help = ’ MA VLi nk source s yst em for this GCS ’) 22 parser . add_option (" --enable - control " ,dest ="enable_control", default = False , hel p ="Enable listning to control messages") 24 ( opts , args ) = pa rser . par se_args () 26 import mavutil 28 # create a mavlink serial instance master = mavutil . m avlin k_con necti on ( opts . device , baud = opts . baudrat e ) 30 if opts . de vice is None: 32 print(" You must specify a serial d evice " ) sys . exit (1) 34 def wait_heartbeat(m): 36 ’’ ’ wa it for a h eart beat so we know the target sy ste m IDs ’ ’’ print(" Waiting for APM heartbeat ") 38 m.wait_heartbeat() print(" Heartbeat from APM ( system %u component %u)" % (m. target_system , m. target_system )) 40 42 # This does not work yet because APM does not have it implemented # def mav _con trol ( data ): 44 # ’’’ # Set roll , pi tch and yaw . 46 # roll : Desired roll angle in radians ( float ) # pitch : Desired pitch angle in radians ( float ) 48 # yaw : Desired yaw angle in radians ( float ) # thrust : Collective thrust , normalized to 0 .. 1 ( float) 50 # ’’’ # master . mav . se t_rol l_pitc h_yaw _thrus t_sen d ( master . target_system , master . target_component , 52 # data . roll , data . pitch , data . yaw , data . thrust ) # 54 # prin t (" s end ing c ontrol : %s" % data ) 56 def send_ rc ( data ): 46 APÉNDICE A 58 master . mav . r c_cha nnels _override_ send ( master . target_system , master . target_component , data . chan nel [0] , data . c hanne l [1] , data . ch ann el [2] , data . c han nel [3] , data . cha nnel [4] , data . chan nel [5] , data . c hanne l [6] , data . ch ann el [7]) print (" sending rc : %s" %data ) 60 62 # service callbacks #def set_mode(mav_mode): 64 # master . se t_mode_ auto () 66 def s et_ arm ( req ) : master.arducopter_arm() 68 return True 70 def s et_d isar m ( req ) : master.arducopter_disarm() 72 return True 74 pub_gps = rospy . Publisher ( ’gps ’, NavSatFix) # pub_imu = rospy . Publisher (’ imu ’, Imu) 76 pub_rc = rospy . Publisher ( ’rc ’ , r oscopt er . msg . RC ) pub_state = rospy.Publisher(’state’, roscopter . msg . State ) 78 pub_vfr_hud = rospy . Publisher (’vfr_hud’, roscopter . msg . VFR_HUD ) pub_attitude = rospy . Publisher ( ’attitude’, roscopter . msg . Attitude ) 80 pub_raw_imu = rospy . Publisher ( ’raw_imu’, roscopter . msg . Mavlink_RAW_IMU ) if opts.enable_control: 82 # rospy . Su bscrib er (" control " , roscopter . msg . Control , mav_control ) rospy . Subscriber (" send_rc " , r oscopt er . msg . RC , se nd_ rc ) 84 # define service callbacks 86 arm_s ervice = rospy . Service ( ’arm ’,Empty , set_arm ) disarm_service = rospy . Service (’ disarm ’,Empty , set_disarm ) 88 90 #state gps_msg = NavSatFix () 92 94 def mainloop(): 96 rospy . init_node ( ’roscopter’) while not rospy . is_shutd own () : 98 rospy . sleep (0.001) msg = master . r ecv_ma tch ( blocking = False ) 100 if not msg : continue 102 # prin t msg . g et_typ e () if msg . g et_t ype () == "BAD_DATA": 104 if mavu til . a ll_p rint able ( msg . data ) : sys . s tdout . write ( msg . data ) 106 sys . s tdout . flush () else: 108 msg_type = msg.get_type() if msg_type == " RC_CHANNELS_RAW " : 110 pub_rc . pu blish ([ msg . chan1_raw , msg . chan2_raw , msg . chan3_raw , msg . chan4_raw , msg . chan5_raw , msg . ch an 6_ra w , msg . chan7_raw , msg . cha n8_raw ]) if msg_type == "HEARTBEAT": 112 pub_state . publish ( msg . base_mode & mavutil . mavlink . MAV _MODE_FLAG_SAFET Y_ARMED , msg . base_mode & mavutil . mavlink . MAV_MODE_FLAG_GUI DED_ENA BLED , 114 ma vut il . m ode_ st ri ng_v 10 ( msg ) ) if msg_type == " VFR_HUD ": A.2. ROSCOPTER 47 116 pub _vfr _hud . pub lis h ( msg . airspeed , msg . groundspeed , msg . heading , msg . throttle , msg . alt , msg . climb ) 118 if msg_type == " GPS_RAW_INT " : fix = NavSatStatus . STATUS_NO_FIX 120 if msg . f ix_typ e >=3: fix = NavSatStatus . STATUS_FIX 122 pub_gps . publish ( NavSatFix ( latitude = msg . lat /1 e07 , lo ngit ude = msg . lon /1 e07 , 124 al titude = msg . alt /1 e03 , status = NavSatStatus ( status = fix , service = NavSatStatus.SERVICE_GPS) 126 )) # pub . pu bli sh ( S tri ng (" MSG : %s" % msg ) ) 128 if msg_type == "ATTITUDE" : pub _att it ude . p ublish ( msg . roll , msg . pitch , msg . yaw , msg . roll spee d , msg . pitchspeed , msg . yawspeed ) 130 132 if msg_type == "LOCAL_POSITION_NED" : print " Local Pos : ( %f %f %f) , ( %f %f %f)" %( msg .x , msg .y , msg .z , msg .vx , msg . vy , msg . vz ) 134 if msg_type == " RAW_IMU " : 136 pub _raw _imu . pub lis h ( He ader () , msg . time_us ec , msg . xacc , msg . yacc , msg . zacc , 138 msg . xgyro , msg . ygyro , msg . zgyro , msg . xmag , msg . ymag , msg . z mag ) 140 142 144 # wait for the heartbeat msg to find the system ID wait_heartbeat(master) 146 148 # waiting for 10 seconds for the system to be ready print(" Sleeping for 10 seconds to allow system , to be ready ") 150 rospy.sleep(10) print(" Sending all stream request for rate %u" % opts.rate) 152 # for i in range (0 , 3) : 154 master . mav . r eques t_dat a_str eam_s end ( master . target_system , master . target_component , mavutil . mavlink . MAV_DATA_STREAM_ALL , opts .rate , 1) 156 # master . mav . set_mod e_send ( master . target_system , 158 if __name__ == ’__main__’: try : 160 mainloop() except rospy.ROSInterruptException: pass 48 APÉNDICE A A.3. Simulación 1.3.1. Simulación 1# include < ros / ros .h > # include < geometr y_msgs / Twist .h > 3# include < g eo metr y_ms gs / P os eW it hC ov ar ia nceSt am pe d .h > 5float goal[6][3]={{0,0,0},{1,1,0},{-1,1,0},{-1,-1,0},{1,-1,0},{1,1,0}}; float tolerance = 0.05; 7 double kp = 0.5; 9double ki = 0.0002; double kd = 0.00005; 11 float w; 13 float error_x = 0; 15 float error_y = 0; float error_z = 0; 17 float error_w = 0; float prev_error_x = 0; 19 float prev_error_y = 0; float prev_error_z = 0; 21 float prev_error_w = 0; float rise = 1; 23 float nonstop = true; 25 float proportional_x = 0; float proportional_y = 0; 27 float proportional_z = 0; float proportional_w = 0; 29 float integral_x = 0; float integral_y = 0; 31 float integral_z = 0; float integral_w = 0; 33 float derivative_x = 0; float derivative_y = 0; 35 float derivative_z = 0; float derivative_w = 0; 37 float action_x = 0; float action_y = 0; 39 float action_z = 0; float action_w = 0; 41 geomet ry_m sgs :: Point real ; 43 geometry_msg s :: Twist twist ; 45 bool must_exit = false; int waypoint_number = 0; 47 void odoCa llback ( const ge om etry _m sgs :: P oseWi th Co va ri an ce St am pe d :: C onstPtr & msg ) 49 { real .x=msg -> pose . pose . positio n .x ; 51 real .y=msg -> pose . pose . positio n .y ; real .z=msg -> pose . pose . positio n .z ; 53 w=msg -> pose . pose . ori enta tion .z; 55 prev_error_x = error_x ; prev_error_y = error_y ; 57 prev_error_z = error_z ; A.3. SIMULACIÓN 49 prev_error_w = error_w ; 59 er ror_x = goal [ w aypoi nt_n umber ][0] - real . x; er ror_y = goal [ w aypoi nt_n umber ][1] - real . y; 61 er ror_z = ( goal [ wayp oint _numb er ][2] + 0.001 * rise ) - real .z ; error_w = 0 - w; 63 proportional_x = kp * error_x ; 65 proportional_y = kp * error_y ; proportional_z = kp * error_z ; 67 proportional_w = kp * error_w ; integral_x += ki * error_x ; 69 integral_y += ki * error_y ; integral_z += ki * error_z ; 71 integral_w += ki * error_w ; derivative_x = kd * (error_x - prev_error_x); 73 derivative_y = kd * (error_y - prev_error_y); derivative_z = kd * (error_z - prev_error_z); 75 derivative_w = kd * (error_w - prev_error_w); 77 action_x = proportional_x + integral_x + derivative_x ; action_y = proportional_y + integral_y + derivative_y ; 79 action_z = proportional_z + integral_z + derivative_z ; action_w = 10 * proportional_w + integral_w + derivative_w ; 81 twist . linear .x = action_x ; 83 twist . linear .y = action_y ; twist . linear .z = action_z ; 85 twist . angular .z = action_w ; 87 ROS_INFO(" Error X: %0.2 f \n", error_x ); ROS_INFO(" Error Y: %0.2 f \n", error_y ); 89 ROS_INFO(" Error Z: %0.2 f \n", error_y ); ROS_INFO("W: %0.2 f \n", w); 91 ROS_INFO(" Action X: %0.2 f \ n" , action_x); ROS_INFO(" Action Y: %0.2 f \ n" , action_y); 93 ROS_INFO(" Action Z: %0.2 f \ n" , action_y); ROS_INFO(" Action W: %0.2 f \ n" , action_y); 95 ROS_INFO(" Voy hacie el objet ivo %d \n" , w aypo in t_ nu mber +1) ; 97 if (( fabs ( error_x ) < tolerance ) && ( fabs ( error_y ) < tolerance )) { 99 if (must_exit == true) { 101 twist . linear .x = 0; twist . linear .y = 0; 103 twist . linear .z = 0; twist . angular .z = 0; 105 exit (0) ; } 107 else { 109 waypoint_number += 1; rise += 1; 111 } } 113 if ( way poin t_nu mber == ( sizeof( goal )/ sizeof(goal[0]))) 115 { if ( nonstop ) 117 { waypoint_number = 1; 119 } else 56 APÉNDICE A channel = [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0] 59 pub_rc . publish ( channel ) elif (1200 < sec urity < 1700) : 61 for iin range ( channel [2] -5 , channel [2]+5) : channel_sec [2] = i 63 pub_rc . publish ( channel_sec ) elif ( securit y > 1700) : 65 landing ( throttle ) os . _exit (1) 67 else: for iin range (990 , 1010) : 69 channel = [0 ,0 ,i ,0 ,0 ,0 ,0 ,0] pub_rc . publish ( channel ) 71 73 if opts.mode == "waypoints": def gps ( data ): 75 global error_x global error_y 77 global error_z global Integral_x 79 global Integral_y global Integral_z 81 x = data .x 83 y = data .y z = data .z 85 prev_error_x = error_x 87 prev_error_y = error_y prev_error_z = error_z 89 error_x = opts . goal_waypoints [3* waypoint_number +0] - x error_y = opts . goal_waypoints [3* waypoint_number +1] - y 91 error_z = opts . goal_waypoints [3* waypoint_number +2] - z 93 action_x = kp * error_x action_y = kp * error_y 95 action_z = kp * error_z 97 position = {’x’:x , ’y’:y , ’z’:z} goal = {’gx ’: opts . goa l_wa ypoi nts [3* i+0] , ’gy ’: opts . goal _way poin ts [3* i +1] , ’ gz ’: opts . goal_waypoints[3*i+2]} 99 error = {’ex ’:error_x , ’ey ’:error_y , ’ ez ’:error_z} action = { ’ax ’:action_x , ’ ay ’:action_y , ’az ’:action_z} 101 print (" Posit ion : %(x) .0.4f , %( y) .0.4 f , %(z) .0.4 f" % position) 103 print (" Goal : %( gx ) .0.4 f, %( gy ) .0.4f , %( gz ) .0.4 f " % goal ) print (" Error X , Y , Z: %( ex ) .0.4 f, %(ey ) .0.4 f , %(ez ) .0.4 f " % error) 105 print (" Actions X , Y , Z : %( ax ) .0.4 f, %( ay ) .0.4 f, %( az ) .0.4 f" % action) 107 Proportional_x = kp * error_x Proportional_y = kp * error_y 109 Proportional_z = kp * error_z Integral_x += ki * error_x 111 Integral_y += ki * error_y Integral_z += ki * error_z 113 Derivative_x = kd * (error_x - prev_error_x) Derivative_y = kd * (error_y - prev_error_y) 115 Derivative_z = kd * (error_z - prev_error_z) 117 action_x = Proportional_x + Integral_x + Derivative_x action_y = Proportional_y + Integral_y + Derivative_y 119 action_z = Proportional_z + Integral_z + Derivative_z A.4. PROGRAMA DE CONTROL 57 121 rc_action_roll = 1500 + action_y rc_action_pitch = 1500 + action_x 123 rc_action_throttle = 1000 + action_z channel = [ rc_action_roll , rc_action_pitch , rc_action_throttle ,0 ,0 ,0 ,0 ,0] 125 security_vel ( channel ) 127 global waypoint_number 129 if error_x < tolerance and error_y < tolerance and error_z < tolerance : if must_exit == 1: 131 landing ( throttle ) os . _exit (1) 133 else waypoint_number += 1 135 if way poin t_num ber == ( len ( opts . goa l_wa ypoi nts ) / 3) : 137 waypoint_number = 0 must_exit = 1 139 kp = 2 141 ki = 0.1 kd = 0.07 143 error = 0 Integral = 0 145 tolerance = 0.1 must_exit = 0 147 gps_sub = rospy . Subscriber (" gps " , NavSatFix , gps ) 149 elif opts.mode == " goup " : def vfr_h ud ( data ): 151 global error global Integral 153 global security 155 al titude = data . alt 157 prev_error = error error = goal - altitude 159 action = kp * error 161 Proportional = kp * error Integral += ki * error 163 Derivative = kd * ( error - prev_error ) 165 action = Proportional + Integral + Derivative 167 rc_action = 1000 + action channel = [0 ,0 , rc_action ,0 ,0 ,0 ,0 ,0] 169 security_vel ( channel ) 171 kp = 2 173 ki = 0.1 kd = 0.07 175 error = 0 Integral = 0 177 goal = opts . altitude vfr_h ud_sub = rospy . Subscribe r ("vfr_hud", rosc opter . msg . VFR_HUD , vfr _hu d ) 179 elif opts.mode == "rotation": 181 def att itu de ( data ) : global error 58 APÉNDICE A 183 global Integral global throttle 185 yaw = data . yaw * 180 / 3.14 187 prev_error = error 189 error = goal - yaw error = ( error + 180) % 360 - 180 # only in yaw 191 Proportional = kp * error print (" Error : %0.4 f" %error) 193 print (" Action : %0.4 f" %Proportional) print (" Yaw : %0.4 f " %yaw ) 195 print (" Security : %0.4 f" %security) 197 Integral += ki * error Derivative = kd * ( error - prev_error ) 199 action = Proportional + Integral + Derivative 201 rc_action = 1480 + action 203 channel = [0 ,0 ,1300 , rc_action ,0 ,0 ,0 ,0] channel = [0 ,0 , security , rc_action ,0 ,0 ,0 ,0] 205 security_vel ( channel ) 207 f = open ( ’yaw_data’,’a’) 209 ticks = time . time () to_file = {’time ’: ticks , ’yaw ’: yaw , ’ goal ’: goal , ’error’: error , ’prev_error’: prev_error , ’Proportional’: Proportional , ’Integral’: Integral , ’Derivative’: Derivative} 211 f. write ( " %( time ) d %( yaw ) 0.4 f %( goal ) 0.4 f %( er ror ) 0.4 f %( p rev_er ror ) 0.4 f %( Pro po rtio nal ) 0.4 f %( In tegral ) 0.4 f %( Der ivat ive ) 0.4 f \ n" %to_file) 213 kp = 2 # 1.75 ki = 0.1 215 kd = 0.07 error = 0 217 Integral = 0 goal = opts . goal_deg #in rads 219 attitude_sub = rospy . Subscriber ("attitude", r osco pter . msg . Attitude , a tti tude ) 221 security = 0 pub_rc = rospy . Publisher ( ’ se nd_ rc ’ , r osc opte r . msg . RC ) 223 rc_sub = rospy . Subscriber ("rc", rosco pter . msg .RC , rc ) 225 def mainloop(): 227 pub = rospy . Publisher ( ’rolling_demo’, String ) rospy . init_node ( ’rolling_demo’) 229 while not rospy . is_shutd own () : 231 rospy . sleep (0.001) 233 if __name__ == ’__main__’: try : 235 mainloop() except rospy.ROSInterruptException: pass A.4. PROGRAMA DE CONTROL 59 1.4.2. Landing # !/ usr / bin / env python 2from __future__ import print_function import roslib ; roslib . load_manifes t (’roscopter’) 4import rospy from std_msgs.msg import String 6from senso r_ msgs . msg import NavSatFix , NavSatStatus , Imu import roscopter.msg 8import sys , struct , time , os import time 10 def vfr_h ud ( data ): 12 w = data . he ading 14 al titude = data . alt 16 error = 0 - altitude error_w = 0 - w 18 action = kp * error action_w = kp * error_w 20 Proportional = kp * error 22 Proportional_w = kp * error_w 24 action = Proportional action_w = 10 * Proportional_w 26 rc_action = 1000 + action 28 rc_action_w = 1500 + action_w channel = [0 ,0 , rc_action , rc_action_w ,0 ,0 ,0 ,0] 30 security_vel ( channel ) 32 kp = 0.5 34 vfr_h ud_sub = rospy . Subscribe r (" vfr_hud ", rosc opter . msg . VFR_HUD , vfr _hu d ) 36 security = 0 pub_rc = rospy . Publisher ( ’ se nd_ rc ’ , r osc opte r . msg . RC ) 38 rc_sub = rospy . Subscriber ("rc", rosco pter . msg .RC , rc ) 40 def mainloop(): 42 pub = rospy . Publisher ( ’landing’, String ) rospy . init_node ( ’ land ing ’ ) 44 while not rospy . is_shutd own () : 46 rospy . sleep (0.001) 48 if __name__ == ’__main__’: try : 50 mainloop() except rospy.ROSInterruptException: pass APÉNDICE B Imágenes y Planos 61 B.1. IMPRESORA 3D 63 B.1. Impresora 3D Figura B.1: Impresora 3D usada en el proyecto 64 APÉNDICE B B.2. Planos de la impresión 3D Figura B.2: Plano del ensamblaje del cuadricóptero B.2. PLANOS DE LA IMPRESIÓN 3D 65 Figura B.3: Plano del plato superior del cuadricóptero 73 MEMORIA EN INGLÉS Developing a ROS Enabled Full Autonomous Quadrotor Iv´an Monz´on Lule˚a University of Technology Department of Computer science, Electrical and Space engineering, Control Engineering Group June 2013 ABSTRACT The aim of this Master Thesis focuses on: a) the design and development of a quadrotor and b) on the design and development of a full ROS enabled software environment for controlling the quadrotor. ROS (Robotic Operating System) is a novel operating system, which has been fully oriented to the specific needs of the robotic platforms. The work that has been done covers various software developing aspects, such as: operating system management in different robotic platforms, the study of the various forms of programming in the ROS environment, evaluating building alternatives, the development of the interface with ROS or the practical tests with the developed aerial platform. In more detail, initially in this thesis, a study of the ROS possibilities applied to flying robots, the development alternatives and the feasibility of integration has been done. These applications have included the aerial SLAM implementations (Simultaneous Location and Mapping) and aerial position control. After the evaluation of the alternatives and considering the related functionality, autonomy and price, it has been considered to base the development platform on the ArduCopter platform. Although there are some examples of unmanned aerial vehicles in ROS, there is no support for this system, thus proper design and development work was necessary to make the two platforms compatible as it will be presented. The quadrotor’s hardware has been mounted on an LTU manufactured platform, made through 3D printing, and its functionality has been evaluated in real environments. Although an aluminium platform has been also evaluated and tested with less satisfactory results. For proper operation of the whole system, a connection between the quadrotor and the ground station has been established. In this case, an alternative connection between computers (for the case of an on board computer is mounted on the aircraft) or connection between computer and ArduCopter (for the case of no on board computers) have been designed. A series of algorithms to perform the quadrotor control autonomously has been also implemented: Navigation with way points, rotation control and altitude control. The novelty of the proposed activities is that for the first time all these control modules have been designed and developed under the ROS system and have been operated in a iii networked manned from the ground station. Finally, as it will be presented, a reader module for the adopted inertial measurement unit, currently under development by the University of Lule˚a (KFly), has also been developed. This device, although tested in controlled laboratory environments, has not yet became part of the quadrotor, but in the near future is expected to serve as a replacement to the on board computer. iv PREFACE This project has been done as a degree thesis to finish my studies in Industrial Engineering with a major in Industrial Automation and Robotics by the Zaragoza University (Spain). The project has been developed and presented in the Lule˚a University of Technology with the team of the Department of Computer science, Electrical and Space engineering; whom I thank for their support and collaboration. It was a hard and long journey for almost six month, full of delays and problems. But now I can say it was worth it. Therefore, I would like to thank the Erasmus project to give me the chance to go to this wonderful Swedish city, Lule˚a. Finally, I would like to thank too George Nikolakopoulos, my supervisor in this endeavor, for his support and optimism. v CONTENTS Chapter 1 – Introduction 1 1.1 Robots..................................... 1 1.1.1 History................................. 1 1.1.2 Robots in service of man . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 UAVs (Unmanned Aerial Vehicle) . . . . . . . . . . . . . . . . . . . . . . 4 1.2.1 Types ................................. 5 1.3 Quadrotors .................................. 7 1.4 TheProblem ................................. 8 1.5 Goals...................................... 9 Chapter 2 – ROS 11 2.1 Robot Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.1.1 Definition ............................... 11 2.1.2 Robots running ROS . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.1.3 Nomenclature............................. 14 2.1.4 Applications, sensors and more . . . . . . . . . . . . . . . . . . . 16 2.1.5 Setup ................................. 18 2.2 First tests to understand the platform . . . . . . . . . . . . . . . . . . . 18 2.3 Evaluating ROS: Hector Quadrotor package . . . . . . . . . . . . . . . . 22 Chapter 3 – Building the Quadrotor 27 3.1 Hardware ................................... 27 3.1.1 ArduCopter.............................. 27 3.1.2 XBee.................................. 30 3.1.3 Positioning Systems . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.1.4 RemoteControl............................ 32 3.2 Code Architecture and Evaluations in Real Tests . . . . . . . . . . . . . 32 3.2.1 Interface................................ 32 3.2.2 Simulation............................... 32 3.2.3 Flyingcode .............................. 34 3.3 Controller ................................... 35 Chapter 4 – Future work 41 6 Introduction while the mobility is not too good. They are good for flying from one place to another, but not to much more. Figure 1.6: Types of UAVs [17] Rotorcraft UAVs usually have a higher consumption and complex mechanics but they have higher handling capabilities. They can operate in inhospitable places, in small spaces and complex paths. In this group, the multi rotor helicopter is a special member. It has some problems with the energy consumption as its batteries do not last long, but it outperforms almost every other UAV on manoeuvrability, simplicity of mechanics and even they are easier to drive. From now, we are going to focus in the autonomous and low cost vehicles for its high growth potential and, more specifically, in autonomous multi rotor helicopters. They can make decisions faster than humans and most important, if they lose the ground connection, they can continue working. The evolution continues with the size, with small flying robots, more precise jobs (as in [18]) can be done, go through smaller paths or be more stealth. Also a cooperation robot matrix is possible with small size robots. 1.3. Quadrotors 7 For example, if we consider a SLAM UAV, a smaller one could perform lower flights and could achieve a really good world reconstruction, reconstructions that before you had to make by hand (or terrestrial vehicles) with cameras. In addition, with them, you can have a bigger z-dimension that helps us to reconstruct high buildings, mountains, trees, etc. Nowadays, you can mix an aerial reconstruction with a ground one with the same vehicle, thereby reducing time and money and making it more accurate. Figure 1.7: Quadrotor 1.3 Quadrotors For some years now, one new kind of UAV has begun to have a lot of attention, and well-deserved recognition, the quadrotor. Until that time, UAVs were heavier and not enough agile than it should be (helicopters [19] and [20]). A quadrotor has a really good stability in the air (by assuming on board good sensors). It can keep still in the air as a helicopter, but it also can do sharp turns or fly upside down without any problem, and it is lighter than helicopters and planes. A quadrotor, also called a quadrotor helicopter or quadcopter, is a multicopter that is lifted and propelled by four rotors. As you can see in Figure 1.7, it is small, between 10 cm and 150 cm. The bigger the helicopter is, the more autonomy may have, because if the propeller is bigger it can rotate slower to lift and the efficiency is better, while the smaller the size is, the more agile it is. A quadrotor is a stable aircraft, therefore, it can be used indoors, but it can also be a dangerous machine, because it is fast, and it can turn and change direction quickly. Thus, losing control of the quadrotor can destroy itself or its environment or harm someone. In our lab, and to test the code in a safe environment, a vertical wire with bumpers (in Figure 1.8) has been built. The quadrotor is hooked up on it and it can rotate and 8 Introduction Figure 1.8: LTU lab with a safety system for quadrotors lift. There has been also a safety net between the quadrotor and the operators. 1.4 The Problem The aim of this Master Thesis is to develop a fully ROS enabled quadrotor and experimentally demonstrate the capabilities of the platform on a realistic flight scenarios, such as attitude and altitude stabilisation and position hold. ROS (Robotic Operating System) is an open source distributed robotics platform designed to accelerate robotic research and development by supporting reusable and modular components able to implement a variety of low and high level functionalities, while during the last 3 years it has received significant attention from the scientific community, as the most prestigious research groups in the area of robotics are putting efforts in this field. Currently, there are already some existing ROS enabled software implementations for quadrotors but these software implementations are platform depended and they aim mainly in performing a tele-operation task, which means that a user should always fly the quadrotor from a distance. The results of this Master Thesis will focus in a novel approach, within the ROS field, where the aim is to create a quadrotor being able to perform autonomous tasks, such as: attitude and altitude stabilisation in a fully ROS enabled environment. The performance of the proposed software architecture will be evaluated in both simulations and extended experimental tests. The main contribution of this Thesis will be in the design and implementation of ROS enabled software control modules, while covering various software developing aspects, such as: operating system management, forms of programming in the ROS environment, software building alternatives, ROS interfaces and finally various practical software implementation issues with the developed aerial platform. 1.5. Goals 9 1.5 Goals The general goal for this Mater Thesis is to extend the vast amount of ROS libraries and the novel approach in designing robotic applications, quadrotors in this case, by creating a proper modular software architecture that will allow the autonomous operation of a quadrotor, like attitude and altitude stabilisation, without the need of human interference. The control modules will be based on the classical PID control architecture, but the novelty of the current implementation will be that all these control modules will be developed to be ROS enabled and will be synchronised with the rest of the ROS operating modules for achieving proper flight performance. To achieve the previous goal the current Thesis has been divided in a number of related activities that include the development of the experimental platform, the design and development of the ROS enabled software architecture and the final extended experimental verifications in real environments. To be able to design a full ROS enabled software architecture, a broad knowledge of the ROS software is considered necessary, which should include both the understanding of its performance and handling as well as the knowledge to program in both C++ and Python, and the ability to modify and adapt existing modules, create new ones and synchronise the whole software architecture of the system. More analytically the goals of this Master Thesis will be the following ones: 1. Literature study in the area of ROS enabled robots and on ROS documentation and functionalities, especially for the case of Unmanned Aerial Vehicles (UAV). 2. Experimental quadrotor platform customization and adaptation to ROS needs. 3. Programming and synthesizing ROS functionalities and system architecture for allowing the autonomous flight (such as attitude and altitude stabilisation), including sensor integration and motor control. 4. Developing ROS enabled control modules, such as On/Off, P and PID controllers. 5. Comparison of ROS modules and experimental evaluation of the quadrotor’s flight performance. CHAPTER 2 ROS 2.1 Robot Operating System Since the advent of the Internet, developer communities have become an essential part of scientific discovery. Now, it is not necessary to be a professional researcher to get into fields, until recently restricted to professional areas. Now, just as a hobby, you can learn and research in any imaginable field. Instructables or even Youtube make this task easier. But if we break away from the general services, there is a world of possibilities. And that is where ROS comes in. ROS allows people all over the planet, people with any level of knowledge, to insert into the robotics world. ROS is not just an operating system, is a complete ecosystem, nourished code and tools that help us to give life to our creations. But above all, it is a community. A system such as ROS helps the spread of ideas, the free use of knowledge to achieve faster progress in this technological world. 2.1.1 Definition Robot Operating System, or ROS, as it is known, is an open source (distributed under the terms of the BSD license) software framework for robot software development. It provides libraries and tools to help software developers create robot applications. Moreover, it provides hardware abstraction, device drivers, libraries, visualizers, message-passing, package management, and more functionalities for delivering fast integrated solutions. 11 12 Robot Operating System In general “A system built using ROS consists of a number of processes, potentially on a number of different hosts, connected at runtime in a peer-to-peer topology.” [21] ROS framework is also specifically developed to reuse drivers and code from another robots. This functionality is being achieved by encapsulating the code in standalone libraries that have no dependencies on ROS. In some cases, ROS can be used only to show configuration options and to route data into and out of the respective software, with as little wrapping or patching as possible. At the end of the day, the most important reason for using ROS and not other framework is that it is part of a collaborative environment. Due to the big amount of robots and artificial intelligence software that have been developed, the collaboration between researchers and universities is essential. To support that development ROS provides a package system; the ROS package which is a directory containing an XML file to describe the package and the related dependencies. At the time of writing, several thousand ROS packages exist as open source on the Internet, and more than fifteen hundred are directly exposed in http://www.ros.org/ browse. 2.1.2 Robots running ROS Figure 2.1: Modlab’s CKBots Since 2007, when ROS was initially released, there have been one hundred different ROS enabled robots in the market. This covers a considerable number of types of robots, mobile robots, manipulators, autonomous cars, humanoids, UAVs, AUVs, UWVs and even some uncategorizable robots as CKBot (in Figure 2.1). The complete list of ROS enabled robots can be located here: http://www.ros.org/wiki/Robots (Some of them can be seen in Figure 2.2). 2.1. Robot Operating System 13 This allow us to use this platform for example in a iRoomba or in a Lego NXT without changing nothing in the code, so that you can focus more in new developments, without the need for time-consuming initial settings. Figure 2.2: ROS enable robots In the field of quadrotor there has not been much content in ROS servers with which we could help. Right now, there are 5 universities fully involved in this field, as it will be presented in the sequel. On one hand, the CCNY Robotics Lab in New York is developing along with AscTec the Pelican and the Hummingbird, which includes the complete software packages in the repositories of ROS. The University of Pennsylvania has a long list of experiments with Penn Quadrotors, including aerobatics flights or light performances with quadrotors swarms. Figure 2.3: PixHawk Cheetah BRAVO 14 Robot Operating System PixHawk Cheetah BRAVO (in Figure 2.3) is being developed from the ETH Zurich, it uses a stereo camera system to be able to perform indoor navigation. The Autonomy Lab, at the Simon Fraser University in Canada, is developing a ROS-based driver for the Parrot AR.Drone (in Figure 2.4), one of the few commercial quadrotors. Finally the project STARMAC (in Figure 2.5) by Stanford University aims to explore cooperation in a multi-vehicle system with a multi-agent controller. Figure 2.4: Parrot AR.Drone In every case, except with PixHawk, specific hardware is used, and in some cases hardware built for the experiment, such as low level boards or IMUs. This restricts the ROS utilization in specific hardware, and thus in this thesis a more broader and hardware independent ROS development approach has been investigated. 2.1.3 Nomenclature Everything on the ROS system is based on nodes, messages, topics and services. This allows us to have a simple code structure and to follow a schematic way of work. The nodes The nodes are processes that execute a specific task. It is like a software module, while nodes can use the topics to communicate each other and use the services to do some simple and external operations. The nodes usually manage low complexity tasks. One moves the motors, another does the SLAM, another handles the laser, etc. 2.1. Robot Operating System 15 Figure 2.5: One of the STARMAC vehicles in flight It is possible to see the nodes in a graphical representation easily with the rxplot command, as for example it has been presented in Figure 2.6 for the case of sr hand program, which is used to access and experiment with Shadow Robot’s hardware, where the shadowhand shares data with the logout ROS node (rosout). Figure 2.6: Graphical nodes representation 22 Robot Operating System 2.3 Evaluating ROS: Hector Quadrotor package Hector [23] is a collection of ROS stacks (a stack is a collection of packages that provides a functionality) originally developed by the Technische Universit¨at Darmstadt (Germany). These stacks supply several tools to simulate or to interact with robots. SLAM, location or modelling are some of them. In this collection, the hector quadrotor stack is going to be utilized with that tool, it is going to be able to moderate (with the physical parameters) a 3D quadrotor model (presented in Figure 2.11) in Gazebo and to have a 3D reconstruction of the world with a SLAM tool. Figure 2.11: Hector quadrotor render In Figure 2.12 you can see the Gazebo representation (on the left in the figure), as well as the world representation provides by Rviz (on the right in the figure). Gazebo is a multirobot simulator which generates both realistic sensor feedback and physically plausible interactions between objects (it includes an accurate simulation of rigid-body physics). While Rviz is a 3D visualization environment that is part of the ROS visualization stack. On this figure it has been also presented a vision range representation (the cone on the left). For utilizing the Hector platform, the first thing to do is to start the world. 1roslaunch hector_quadrotor_demo indoor_slam_gazebo . launch Then, and thanks to the easy access and interoperability between nodes, it is possible to use private code to take the control using the topic ”cmd vel” to control the quadrotor speed. 1rosrun hector_quadrotor_controller simulation In a first stage, and through that platform, a simulator has been developed to try the produced controllers and for a better understanding of the quadrotor behaviour. 2.3. Evaluating ROS: Hector Quadrotor package 23 Figure 2.12: Hector quadrotor simulation For this purpose, a control code has been developed to carry out the way point navigation and all the positioning codes. With this code you have to set some goals (as many as are needed), the precision and the speed. You can edit the proportional, integrative and derivative constants too. For the moment, all of these parameters needs to be set in the code file (cpp) and a rosmake needs to be performed. It is also possible to modify every parameter at running time (but then it is not possible to modify the number of goals) when the program is being executed with this structure. 1rosrun package program parameter := new_parameter 24 Robot Operating System Figure 2.13: Hector quadrotor simulation This controller can move the quadrotor in X, Y or Z speed direction, it also controls that orientation to be always stable and North. For performing this simulation, the complete code (in C++) has been included in the Appendix 1.2.1. In Figure 2.13 the simulated quadrotor following an almost perfect cube (the red line is the path followed) is being presented. For this goal, the PID constants to have a stable system have been set as the equation 2.1 shows. κp= 0.5κi= 0.0002 κd= 0.00005 (2.1) The next simulation test was to try to control the simulator movement with the real quadrotor while performing true interoperability between platforms and networks. This simulator took the Euler angle outputs directly from the experimental quadrotor platform to show the same movement in the virtual one. The Z axis can be rotated to rotate in the simulation, the X axis to advance in Y direction or Y axis to advance in X direction. Just as it would move if the quadrotor motors roll, pitch or yaw in these directions. In order to achieve this we need to use a controller to move the virtual quadrotor from the original position (the virtual position) to the goal position (the real position) similar as before. 2.3. Evaluating ROS: Hector Quadrotor package 25 For these tests,the experimental frame has been utilized (in Figure 2.14) and an IMU, the k-Fly, which has been designed and printed by Emil Fresk. This frame has been printed in our lab with a handmade 3D printer, and it has been tested its strength to axial tension and bending. The code (in C++) for this second simulation can be located in Appendix 1.2.2. Figure 2.14: Prototype quadrotor frame CHAPTER 3 Building the Quadrotor 3.1 Hardware 3.1.1 ArduCopter ArduCopter (presented in Figure 3.1) is an easy to setup and easy to fly platform for multirotors and helicopters, it is a basic RC multicopter which can be found in the today market. Thanks to Arduino and the great community that both have it is possible to find lots of modifications to the platform which can be easily adapted to specific applications. Figure 3.1: Arducopter quadrotor ArduCopter is mainly a modified Arduino board (ArduPilot Mega) with an IMU board 27 28 Building the Quadrotor attached. The IMU (inertial measurement unit), that provides 3 accelerometer and 3 gyroscope directions, also has an attached magnetometer (with 3 degrees of freedom) and an XBee unit to support wireless communication. Moreover, this board can provide a quaternion [24] system with which you can calculate an Euler angle [25] system and measure how the quadrotor is positioned. A GPS attached also to the ArduPilot Mega board is used to estimate the 3D position of the quadrotor. Finally, there is a power distribution board controlled by the ArduPilot Mega board, this low level board controls the ESC (Electronic Speed Controller) of the motors. In Figure 3.2 there is a scheme of this parts. Figure 3.2: ArduCopter components One of the most important parts in the quadrotor are the propellers, how they are mounted and how they can give lift to the quadrotor. The flying stabilization in that kind of flying machine is achieved by two opposite forces [26]. The force that pushes the UAVs down is the gravity, an opposite force needs to be created of same magnitude to get hold the vehicle flying. That force is generated by the propellers that create a low pressure area over the top surface of them. These propellers are able to change the quadrotor angles. In Figure 3.3 (a) a sketch of the quadrotor structure is presented in black. The Ω symbol represents the angular speed, and the ∆ symbol represents the increase in speed. ¨ Φ, ¨ Θ and ¨ Ψ represent the angular acceleration created in that moment in X,Yand Zdirections. The fixed- 3.1. Hardware 29 Figure 3.3: a) Simplified quadrotor motor in hovering (left) and b) Roll movement (right) Figure 3.4: a) Pitch movement (left) and b) Yaw movement (right) body B-frame is shown in green and in blue is represented the angular speed of the propellers. Roll movement is provided by increasing (or decreasing) the left propeller speed and by decreasing (or increasing) the right one. It leads to a torque with respect to the XBaxis which makes the quadrotor turn. Figure 3.3 (b) shows the roll movement on a quadrotor sketch. Pitch movement is very similar to the roll and is provided by increasing (or decreasing) the rear propeller speed and by decreasing (or increasing) the front one. It leads to a torque with respect to the YBaxis which makes the quadrotor turn. Figure 3.4 (a) shows the pitch movement on a quadrotor sketch. The Yaw moment is provided by increasing (or decreasing) the front-rear propellers’ speed and by decreasing (or increasing) that of the left-right couple. It leads to a torque with respect to the ZBaxis which makes the quadrotor turn. The yaw movement is generated thanks to the fact that the left-right propellers rotate clockwise, while the front-rear ones rotate counter-clockwise. Hence, when the overall torque is unbalanced, the helicopter turns on itself around ZB. Figure 3.4 (b) shows the yaw movement on a quadrotor sketch. [27] Working with ArduCopter In this thesis we will use a default ArduCopter quadcopter that will be connected with a ground workstation through XBee [28]. The MAVlink [29] serial connection will provide data about attitude (Euler angles and Euler angle speeds), vfr hub (ground speed, air speed, altitude and climb rate), GPS, RC (the values of the 8 radio frequency channels). 30 Building the Quadrotor This serial connection also provides heartbeat (systems can use this message to track if the system is alive); navigation controller output (with information about goals and errors); hardware status (board voltage); raw IMU (acceleration, gyroscope and compass values); pressure; and some more parameters which have not been used in this system, while the same connection will be used to send the required throttle, and the euler angles. In Figure 3.5 it is shown that it is possible to create a network between several aerial robots and ground stations using XBee devices. Figure 3.5: MAVlink connection between flying machines and a ground station [30] 3.1.2 XBee XBee (in Figure 3.6) Digi International radio module is being displayed that uses the ZigBee protocol (it is based on an IEEE 802 standard). For this thesis, it is needed a device with a low consumption. The normal flying time for this kind of UAVs usually is lower than 15 minutes, so any extension in the autonomy is a big improvement as is also needed a long working range. The quadrotor can fly autonomously, but it is usually good to keep the telemetry running to see what happened in the air and to overcome some minor problems. Therefore, an XBee Pro 60mW Wire Antenna - Series 1 (802.15.4) has been selected. It is a cheap (less that $40) and reliable device with more than 1 km connectivity range 3.1. Hardware 31 Figure 3.6: XBee module and a low consumption. Figure 3.7: XBee Explorer For the interface of this XBee with the workstation an XBee Explorer Dongle (in Figure 3.7) has been selected, while for the interface with the ArduCopter the selection has been an XBee Explorer Regulated through the UART0 port. 3.1.3 Positioning Systems Figure 3.8: GPS module 38 Building the Quadrotor Algorithm 1: Control algorithm read data store prev error calculate error: goal - data calculate proportional action: κp* error calculate integral: prev integral + κi* error calculate derivative: κd* (error - prev error) calculate action: Proportional + Integral + Derivative ajust the action to the rc level publish the action In the presented codes, as it has been stated, topic callbacks are used in order to carry out the control instead of loops. So the Algorithm 1 is launched each time that “attitude” callback has an update in its topic. That algorithm uses three correcting terms, whose sum is the control action. The proportional action produces an absolute change in the energy of the system, which modifies the response time. The integral action helps to remove the residual steady-state error. It maintains a count of the cumulative error, and it adds to the action in order that the slightest errors can be eliminated. The derivative action predicts system behavior and thus improves settling time and stability of the system. System go /rc_channel Quadrotor Proportional Derivative Integrative Goal -+ + RosCopter MAVLink ArduPilot /attitude Figure 3.15: Control diagram In the case of the waypoint control, the roll controls the Ycoordinate, the pitch controls the Xcoordinate and the throttle controls the Zcoordinate. The implementation of this 3.3. Controller 39 controller is presented in Figure 3.15. In this representation, the interfaces have been simplified, since the focus has been provided in the control code go. CHAPTER 4 Future work The work you can do in six months is limited, and therefore the work that lies ahead is enormous. After the waypoint navigation codes and, derived from it, paths generated navigation, will allow us to trace routes of action for SLAM. Having ensured the proper operation of navigation codes would have to start working with SLAM tasks. The hardware for this purpose would be a USB camera connected to the onboard computer. By reconstruction software that take advantage of the quadrotor own motion for a stereoscopic image. This reconstruction would also used for route planning and obstacle avoidance. Future research will address how the robot performs its task. While perform its task completely in local (on-board computer without help from the ground station) is the option that seems more complete. Would be equally satisfactory options. One alternative would be the remote processing of data sending the images to the ground station. It would perform the 3D reconstruction and would send the new routes to the quadrotor. The second one would be to record such images for off-line 3D reconstruction for use as a map on other platforms. This two alternatives could help in the quadrotor consumption. In this case, you could avoid the onboard computer. The main problem of this course is that the ground station and the quadrotor would have to have always a stable connection. 41 CHAPTER 5 Conclusion The aim of this Master Thesis was to design and develop a quadrotor that will have the merit to operate under a fully ROS enabled software environment. As it has been presented in the Thesis, based on an existing flying frame, a quadrotor has been designed and integrated, where all the necessary hardware components, including the motor controllers, the IMU, the wireless communication link based on the xBees and the GPS have been properly adjusted and tuned for allowing the proper flight capabilities of the platform. Except from the first necessary stage of developing the flying platform, the main focus has been provided in the design and implementation of the necessary ROS enabled software platform, that would be able to connect all the sub-components and support novel ROS enabled control algorithms for allowing the autonomous or semi-autonomous flying. As it has been indicated in the introduction, there are already some existing ROS enabled software implementations for quadrotors but these software implementations are platform depended and they aim mainly in performing a tele-operation task, which means that a user should always fly the quadrotor from a distance. The results of this thesis have been presented a novel approach where the quadrotor is able to perform autonomous tasks, such as: attitude and altitude stabilisation in a fully ROS enabled environment. The results have been performed in both simulation and extended experimental studies. The software developments that have been performed have covered various software developing aspects, such as: operating system management in different robotic platforms, the study of the various forms of programming in the ROS environment, the evaluation of software building alternatives, the development of the ROS interface and finally various practical software implementation issues with the developed aerial platform. Upon completion of this project, two different configurations (aluminium and plastic) of the quadrotor have been delivered. The ArduCopter has been utilised and integrated in the ROS platform while as it has been presented in the thesis, a series of codes have been designed for the project, ranging from establishing the communication with the ground station to the way points following, with the most important to be the 43 44 Conclusion software implementation of the ROS enabled PID controllers for the attitude and altitude stabilisation of the quadrotor. Although the tests in a real environment have not had all the desirable extent due to the luck of having a full controllable laboratory environment, the developed software architecture for the attitude and altitude stabilisation of the quadrotor have been extended evaluated and the obtained experimental results have proven the overall feasibility of the novel ROS enabled control structure implementation and the achievement of a acceptable flying performance for the quadrotor. The potential of such autonomous quadrotors is enormous, and it can be even bigger when the size of these devices gets miniaturized, with a relative decrease in the overall hardware cost. For these quadrotors, a proper real time and modular operating system is needed in order to extend the capabilities of these platforms in higher standards. With this thesis it has been experimentally demonstrated that ROS is a proper operating system to manage all the requirements that might arise, while it has the unique merit of being an open source software, allowing the sharing of drivers and programs among the developer community, for speeding the developing phase. GLOSARIO APM AutoPilot Mega AUV Autonomous Unmanned Vehicle (Vehículo Autónomo no Tripulado) BSD Berkeley Software Distribution (Distribución de Software Berkeley) ∆Cantidad de Incremento ESC Electronic Speed Controller (Controlador Electrónico de Velocidad) GPS Global Positioning System (Sistema de Posicionamiento Global) IMU Inertial Measurement Unit (Unidad de Medida Inercial) IP Internet Protocol (Protocolo de Internet) κpConstante proporcional usada en el control κiConstante integrativa usada en el control κdConstante derivativa usada en el control ΩVelocidad angular ¨ ΦVelocidad angular en dirección X ¨ ΨVelocidad angular en dirección Z PID Proportional-Integral-Derivative Controller (Control Proporcional-Integral-Derivativo) p2p Peer-to-peer (Red de pares o red punto a punto) UAV Unmanned Aerial Vehicle (Vehículo Aéreo no Tripulado) UWV Unmanned Water Vehicle (Vehículo Acuático no Tripulado) RC Remote Control (Control Remoto) 128 ROS Robotic Operating System (Sistema Operativo para Robots) SLAM Simultaneous localization and mapping (Localización Y Mapeado Simultáneos) ¨ ΘVelocidad angular en dirección Y BIBLIOGRAFÍA [1] E. Fresk, “KFly.” Retrieved from http://kflyproject.blogspot.com.es/. [2] W. Schmidt, Pneumatica et Automata: Heron Alexandrinus ; accedunt Heronis fragmentum de horoscopiis aquariis, Philonis De ingeniis spiritualibus, Vitruvii capita quaedam ad pneumatica pertinentia ; recensuit Guilelmus Schmidt. Bibliotheca scriptorum Graecorum et Romanorum Teubneriana, B.G. Teubner, 1899. [3] S. Nof, Handbook of Industrial Robotics. No. v. 1 in Electrical and electronic engineering, Wiley, 1999. [4] R. D. Leighty and ARMY ENGINEER TOPOGRAPHIC LABS FORT BELVOIR, DARPA ALV (Autonomous Land Vehicle) Summary. Defense Technical Information Center, 1986. [5] B. Llc, Robotics at Hond: Asimo, Honda E Series, Humanoid Robotics Project, Honda P Series. General Books LLC, 2010. [6] NewEagleWiki, “Unmanned Systems,” http://www.neweagle.net/support/wiki/ index.php?title=Unmanned_Systems. [7] Scaled composites, “Bell Eagle Eye TiltRotor UAV.” Retrieved from http: //web.archive.org/web/20070113222345/http://www.scaled.com/projects/ eagleye.html. [8] OLIVE-DRAB, “RQ-7 Shadow UAV.” Retrieved from http://olive-drab.com/ idphoto/id_photos_uav_rq7.php. [9] K. Alexis, G. Nikolakopoulos, A. Tzes, and L. Dritsas, “Coordination of Helicopter UAVs for Aerial Forest-Fire Surveillance,” in Applications of Intelligent Control to Engineering Systems (K. Valavanis, ed.), vol. 39 of Intelligent Systems, Control, and Automation: Science and Engineering, pp. 169–193, Springer Netherlands, 2009. 129