Hummingbird Manual Introduction to Feedback...

101
Hummingbird Manual Introduction to Feedback Control USING DESIGN S TUDIES R ANDAL W. B EARD WITH C AMMY P ETERSON MARC KILLPACK MARK P ETERSEN DEVON MORRIS Updated January 6, 2021 TOC

Transcript of Hummingbird Manual Introduction to Feedback...

Page 1: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Hummingbird Manual

Introduction toFeedback ControlUSING DESIGN STUDIES

RANDAL W. BEARD

WITH

CAMMY PETERSON

MARC KILLPACK

MARK PETERSEN

DEVON MORRIS

Updated January 6, 2021

TOC

Page 2: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CONTENTS 2

Contents

1 Introduction 1Lab: hummingbird 4

I Simulation Models 52 Kinetic Energy of Mechanical Systems 73 The Euler Lagrange Equations 17

II Hummingbird Design Models 214 Equilibria and Linearization 255 Transfer Function Models 336 State Space Models 35

III PID Control Design 377 Pole Placement for Second Order Systems 398 Design Strategies for Second-Order Systems 439 System Type and Integrators 4710 Digital Implementation of PID Controllers 49

IV Observer-based Control Design 5111 Full-state Feedback 5312 Integrator with Full State Feedback 5713 Observers 5914 Disturbance Observers 63

V Loopshaping Control Design 6515 Frequency Response of LTI Systems 6716 Frequency Domain Specifications 6917 Stability and Robustness Margins 7118 Compensator Design 73

Appendices 64a Connecting to the Hummingbird with ROS 75b Parameters of the Hummingbird 85c supportFiles 87

TOC

Page 3: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

1Introduction

This objective of this document is to provide a detailed introduction to the BYUhummingbird including laboratory assignments that are intended to complementan introductory course in feedback control. The hummingbird is a three degree-of-freedom helicopter with complicated nonlinear dynamics, but the dynamics areamenable to linear analysis and design. The hummingbird has been designed withencoders on each joint that allow full-state feedback, but it is also equipped withan IMU (rate gyros and accelerometers). The sensor configuration allows esti-mated state information obtained from the IMU and camera to be compared totruth data obtained from the encoders, thereby decoupling the state feedback andstate estimation problems, and allowing each to be tuned and analyzed indepen-dently. We believe that this decoupling is essential to help students understand thesubtleties in feedback and estimator design.

The design process for control system is shown in Figure 1-1. For the hum-mingbird, the system to be controlled is a physical system with actuators (motors)and sensors (encoders, IMU). The first step in the design process is to model thephysical system using nonlinear differential equations. While approximations andsimplifications will be necessary at this step, the hope is to capture in mathemat-ics, all of the important characteristics of the physical system. The mathematicalmodel of the system is usually obtained using Euler-Lagrange method, Newton’smethod, or other methods from physics and chemistry. The resulting model isusually high order and too complex for design. However, this model will be usedto test later designs in simulation and is therefore called the Simulation Model,as shown in Figure 1-1. To facilitate design, the simulation model is simplifiedand usually linearized to create lower-order (and usually linear) design models.For any physical system, there may be multiple design models that capture certainaspects of the design process. For the hummingbird, we will decompose the mo-tion into longitudinal (pitching) motion and lateral (rolling and yawing) motionand we will have different design models for each type of motion. As shown inFigure 1-1, the design models are used to develop control designs. The control

TOC

Page 4: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 1. INTRODUCTION 2

Physical System

Simulation Model

Transfer Function Design Model

State Space Design Model

Observer Based Control

Euler-Lagrange Equations

Linearization, Model Reduction, Simplification, etc.

Test in Simulation

Implement on Physical System

PID Control

Loopshaping Control

Figure 1-1: The design process. Using physics models the physical system ismodeled with nonlinear differential equations resulting in the simulation model.The simulation model is simplified to create design models which are used for thecontrol design. The control design is then tested and debugged in simulation andfinally implemented on the physical system.

designs are then tested against the simulation, which sometimes requires that thedesign models be modified or enhanced if they have not captured the essentialfeatures of the system. After the control designs have been thoroughly tested insimulation, they are implemented on the physical system and are again tested anddebugged, sometimes requiring that the simulation model be modified to moreclosely match the physical system.

The physical system or "hardware" interfaces with our models and controllersusing the ROS framework. ROS stands for Robot Operating System and is usedthroughout academia and business and has a large user base. We have chosento use ROS for our hummingbird hardware since it is modular, fast, and highlyflexible. Students will learn the basics of ROS in this course and will preparethemselves to design more complex systems using ROS in the future. The firstpreliminary lab will cover learning the basics of ROS and setting up the hum-mingbird workspace. These details are found in a. It will be important for stu-dents to follow all the directions found in this section as it will ensure that thehummingbird hardware will run in a safe manner.

The purpose of these notes, and the associated laboratory assignments, isto walk you through the design cycle for the hummingbird. We will considerthree different design methodologies: successive loop closure, loopshaping, andobserver-based control. We believe that visualizing the physical system is an im-portant part of the simulation model. The simulation model has been implementedas a node in the ROS framework and is found in the Gitlab repository. If studentsare interested in learning how to animate other control systems they can visit rviztutorials.

These animations need to behave in a dynamically accurate manner. The equa-

TOC

Page 5: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 1. INTRODUCTION 3

tions of motions of the hummingbird are derived using the Euler-Lagrange methodin Chapters 2 and 3. Implementing the equations of motion in Python requiresknowledge of numerical integration of ordinary differential equations (ODEs),which is typically unfamiliar to students. Therefore, a simulator template nodehas been created for the students. This ROS node will handle the integration ofthe equations of motion of the hummingbird and students will be required to insertthe equations of motion. Understanding the equations of motion and implement-ing them in the ROS node comprises labs 2 and 3 A full python based approach isdescribed in Appendix ??. Support files for this approach are found on the controlbook website. Once the simulation model is complete, design models are devel-oped in Chapters 4, 5, and 6. Since the design models are in terms of force andtorque, the force and torque need to be converted to a left and right pulse widthmodulation command.

Developing physically realizable design specifications is an important part ofthe design process and described in Chapter 7. The remainder of the chapters in-troduce different controllers that control the hummingbird according to the designspecifications.

This book is used in conjunction with the Control Book website. The websitecontains many useful files such as the Design Study solutions for the Single LinkRobot Arm, Inverted Pendulum, and Satellite Altitude Control.

TOC

Page 6: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 1. INTRODUCTION 4

H Hummingbird Lab Assignments

Figure 1-2: The hummingbird system

A descripton of the hummingbird can be found in Appendix b

Laboratory Assignments:

H.1 Intro to hummingbird.H.2 Kinetic energy.H.3 Equations of Motion.H.4 Linearize equations of motion.H.5 Transfer function model.H.6 State space model.H.7 Pole placement using PD.H.8 Second order design.H.9 Integrators and system type.

H.10 Digital PID.H.11 Full state feedback.H.12 Full state with integrator.H.13 Observer based control.H.14 Disturbance observer.H.15 Frequency Response.H.16 Loop gain.H.17 Stability margins.H.18 Loopshaping design.

Lab Assignment H.11. Work through the hummingbird ROS tutorial listed in Appendix a

TOC

Page 7: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Part I

Simulation Models

TOC

Page 8: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics
Page 9: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

2Kinetic Energy of Mechanical Systems

The objective of this chapter is to develop the equations that describe the kineticenergy of the hummingbird. The physical parameters of the hummingbird and adescription of each can be found in Appendix b.

2.1 Kinetic Energy

A simplified diagram of the hummingbird is shown in Figure 2-1,

Figure 2-1: A simplified diagram of the hummingbird.

Since there are three different objects that move independently of each other,

TOC

Page 10: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 8

we will model the hummingbird as consisting of three masses, as shown in Fig-ure 2-1. The first mass, labeled m1, J1 in Figure 2-1 is the final rod and the headof the hummingbird, including the motors, propellers, and shrouds. The secondmass, labeledm2, J2 in Figure 2-1 is the main body of the hummingbird, the thirdmass labeled m3, J3 in Figure 2-1 consists of the metal block that connects themain body and also the control board.

The world coordinate frame is defined to be the point where the third bodyspins about the zw-axis. The xw − yw plane is horizontal to the ground, and theworld zw-axis points toward the center of the earth. The body-fixed coordinateframe is defined so that center of the frame corresponds to the center of the worldframe, and if an observer were sitting at the center and facing along the mainshaft of the hummingbird, the xb-axis would point forward, along the shaft of thehummingbird, the yb axis would point to the right, and the zb axis would pointdown.

2.1.1 Rotation matrices and transformations between coordi-nate frames (Bonus Material)

To fully understand the derivation of the equations of motion for the hummingbirdrequires an understanding of transformations between coordinate frames. One co-ordinate frame is transformed into another through two basic operations: rotationand translation. In this section we will describe rotation matrices and their use intransforming between coordinate frames, and we will also describes the specificcoordinate frames used for the hummingbird.

2.2 Rotation Matrices

We begin by considering the two coordinate frames shown in Figure 2-2. The

i0

i1

j1j0

p0y

p1y

p1x

p0xk0 = k1

Figure 2-2: Rotation in 2D

vector p can be expressed in both the F0 frame (specified by (i0, j0, k0)) and in

TOC

Page 11: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 9

the F1 frame (specified by (i1, j1, k1)). This is the same vector in either case, butexpressed in a different frame. In the F0 frame we describe this as

p = p0xi0 + p0y j

0 + p0z k0.

Alternatively in the F1 frame we have

p = p1xi1 + p1y j

1 + p1z k1.

The vector sets (i0, j0, k0) and (i1, j1, k1) are each mutually perpendicular setsof unit basis vectors.

One way to write the matrix that describes the rotation between the two framesis to set these two expressions equal to each other, which gives

p1xi1 + p1y j

1 + p1z k1 = p0xi

0 + p0y j0 + p0z k

0.

Taking the dot product of both sides with i1, j1, and k1 respectively, and stackingthe result into matrix form gives

p1 4=

p1xp1yp1z

=

i1 · i0 i1 · j0 i1 · k0j1 · i0 j1 · j0 j1 · k0k1 · i0 k1 · j0 k1 · k0

p0xp0yp0z

.

From the geometry of Figure 2-2 we could also write this same matrix as

p1 = Rz(θ)p0, (2.1)

where

Rz(θ) 4=

cos θ sin θ 0− sin θ cos θ 0

0 0 1

. (2.2)

The notation Rz is used to denote a rotation from coordinate frame F0 tocoordinate frame F1, where the rotation is about the z axis of F0.

Proceeding in a similar way, a right-handed rotation of the coordinate systemabout the y-axis of F0 by an angle of θ gives

Ry(θ)4=

cos θ 0 − sin θ0 1 0

sin θ 0 cos θ

, (2.3)

and a right-handed rotation of the coordinate system about the x-axis of F0 by anangle of θ is

Rx(θ)4=

1 0 00 cos θ sin θ0 − sin θ cos θ

. (2.4)

The negative sign on the sine term appears above the line with only ones and zeros.The matrices R∗ in the above equations are examples of a more general class

of orthonormal rotation matrices that have the following properties:

TOC

Page 12: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 10

P.1. (Rba)−1 = (Rba)> = Rab .

P.2. RcbRba = Rca.

P.3. det(Rba)

= 1,

where det(·) is the determinant of a matrix.There are several coordinate frames associated with the hummingbird. The ro-

tation between these frames can be described using rotation matrices as explainedbelow. The world frame Fw is the coordinate frame that is centered at the centerof rotation of the hummingbird. When the roll, pitch, and yaw angles are all zero,the iw-axis is aligned along the body and shaft of the hummingbird, the jw-axisis to the right, and the kw-axis points down, as shown in Figure 2-3.

Figure 2-3: The hummingbird world frame. The iw-axis points along the roll axis,the jw-axis points to the right, and the kw-axis points into the earth.

The hummingbird 1-frame, denoted F1, is obtained by rotating the Fw aboutthe kw axis by an angle of ψ, which is called the yaw angle. A top view of thisrotation is shown in Figure 2-4. The rotation matrix that transforms coordinates

Figure 2-4: The hummingbird 1-frame is obtained from the world frame by rotat-ing ψ about kw.

form Fw to F1 is Rz(ψ) as given in Equation (2.2).The hummingbird 2-frame, denoted F2, is obtained by rotating F1 about the

j1-axis by an angle of θ, which is called the pitch angle. A side view of thisrotation is shown in Figure 2-5. The rotation matrix that transforms coordinatesform F1 to F2 is Ry(θ) as given in Equation (2.3).

The hummingbird body frame, denoted Fb, is obtained by rotating F2 aboutthe i2-axis by an angle of φ, which is called the roll angle. A view of the headlooking from the rotation center along the hummingbird shown in Figure 2-6. Therotation matrix that transforms coordinates form F2 to Fb is Rx(φ) as given inEquation (2.4). When performing sequential rotations, these rotation matrices can

TOC

Page 13: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 11

Figure 2-5: The hummingbird 2-frame is obtained from the hummingbird 1-frameby rotating θ about j1.

Figure 2-6: The hummingbird body frame is obtained from the hummingbird 2-frame by rotating φ about i2.

be composed (or multiplied) to find the total rotation. This will be shown in thenext section.

2.2.1 Kinetic energy of the hummingbirdThe hummingbird spins about the world zw axis by the yaw angle ψ as shown inFigure 2-1. After rotating about zw by ψ, the hummingbird spins about the bodyyb-axis by the pitch angle θ. After yawing and pitching, the hummingbird spinsabout the body xb-axis by the roll angle φ, as shown in Figure 2-1. Therefore,the configuration of the hummingbird is given by the three generalized variables(along with other known geometric quantities such as length of the rods, etc.)

q =

φθψ

.

The position of the center of mass of m3 is a function of the yaw angle ψ. Theposition of the center of mass of m2 is a function of both the yaw angle ψ and thepitch angle θ, and the position of the center of mass ofm1 is a function of all threeangles ψ, θ, and φ. Therefore, the total kinetic energy of the system is given by

K =

3∑i=1

(1

2miv

Ti vi +

1

2ωTi Jiωi

).

TOC

Page 14: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 12

If the position of the center of mass of m1 in the hummingbird 2-frame isgiven by p2

1 =(`1 0 0

)>, then we can describe that same vector in the world

frame by using appropriate rotation matrices given by

pw1 = Rz(ψ)Ry(θ)

`100

=

cψ −sψ 0sψ cψ 00 0 1

cθ 0 sθ0 1 0−sθ 0 cθ

`100

=

`1cθcψ`1cθsψ−`1sθ

,

where to make the expressions easier to read, we have used the notation cφ4= cosφ

and sφ4= sinφ. Therefore, the velocity of the first mass is given by

v1 = p1 =

−`1θsθcψ − `1ψcθsψ−`1θsθsψ + `1ψcθcψ−`1θcθ

=

0 −`1sθcψ −`1cθsψ0 −`1sθsψ `1cθcψ0 −`1cθ 0

φθψ

(2.5)

= V1(q)q, (2.6)

where

V1(q)4=

0 −`1sθcψ −`1cθsψ0 −`1sθsψ `1cθcψ0 −`1cθ 0

. (2.7)

Calculating the angular velocity is a bit tricky because the angular rates φ, θand ψ are all expressed in different frames. The roll rate (φ, 0, 0)> is expressed inthe hummingbird body frame. The pitch rate (0, θ, 0)> is expressed in the hum-mingbird 2-frame, and the yaw rate (0, 0, ψ)> is expressed in the hummingbird1-frame. Since the inertia matrix of J1 is relative to the body frame, we also needto express ω1 in the body frame. Therefore

ω1 =

φ00

+

1 0 00 cφ sφ0 −sφ cφ

0

θ0

(2.8)

+

1 0 00 cφ sφ0 −sφ cφ

cθ 0 −sθ0 1 0sθ 0 cθ

00

ψ

(2.9)

=

1 0 −sθ0 cφ sφcθ0 −sφ cφcθ

φθψ

(2.10)

= W1(q)q, (2.11)

TOC

Page 15: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 13

where

W1(q)4=

1 0 −sθ0 cφ sφcθ0 −sφ cφcθ

, (2.12)

and where we have expressed the roll, pitch, and yaw rates in the body frame.If the position of the center of mass of m2 in the body frame is given by

pb2 =(`2 0 0

)>, then in the inertial frame, the position is given by

pw2 = Rz(ψ)Ry(θ)

`200

=

cψ −sψ 0sψ cψ 00 0 1

cθ 0 sθ0 1 0−sθ 0 cθ

`200

=

`2cθcψ`2cθsψ−`2sθ

,

where to make the expressions easier to read, we have used the notation cφ4=

cosφ and sφ4= sinφ. Therefore, the velocity of the second mass is given by

v2 = p2 =

−`2θsθcψ − `2ψcθsψ−`2θsθsψ + `2ψcθcψ−`2θcθ

(2.13)

=

0 −`2sθcψ −`2cθsψ0 −`2sθsψ `2cθcψ0 −`2cθ 0

φθψ

(2.14)

= V2(q)q, (2.15)

where

V2(q)4=

0 −`2sθcψ −`2cθsψ0 −`2sθsψ `2cθcψ0 −`2cθ 0

. (2.16)

The angular velocity of the second mass will be a function θ, and ψ and sinceJ2 is defined relative to the hummingbird 2-frame, ω2 is also expressed in thehummingbird 2-frame as

ω2 =

0

θ0

+

cθ 0 −sθ0 1 0sθ 0 cθ

00

ψ

=

0 0 −sθ0 1 00 0 cθ

φθψ

= W2(q)q,

TOC

Page 16: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 14

where

W2(q)4=

0 0 −sθ0 1 00 0 cθ

. (2.17)

If the position of the center of mass of m3 in the body frame is given bypb3 =

(`3x `3y `3z

)>, then in the inertial frame, the position is given by

pb3 = Rz(ψ)

`3x`3y`3z

=

cψ −sψ 0sψ cψ 00 0 1

`3x`3y`3z

=

`3xcψ − `3ysψ`3xsψ + `3ycψ`3z

.

Therefore, the velocity of the third mass is given by

v3 = p3 = ψ

−`3xsψ − `3ycψ`3xcψ − `3ysψ0

(2.18)

=

0 0 −(`3xsψ + `3ycψ)0 0 (`3xcψ − `3ysψ)0 0 0

φθψ

(2.19)

= V3(q)q, (2.20)

where

V3(q)4=

0 0 −(`3xsψ + `3ycψ)0 0 (`3xcψ − `3ysψ)0 0 0

. (2.21)

The angular velocity of the third mass will be a function ψ and is given by

ω3 =

00

ψ

=

0 0 00 0 00 0 1

φθψ

(2.22)

= W3(q)q, (2.23)

where

W3(q)4=

0 0 00 0 00 0 1

. (2.24)

TOC

Page 17: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 15

Therefore, the total kinetic energy is given by

K =

3∑i=1

(1

2miv

Ti vi +

1

2ωTi jiωi

)(2.25)

=

3∑i=1

(1

2miq

>V >i Viq +1

2q>W>i JiWiq

)(2.26)

=1

2q>

(3∑i=1

miV>i Vi +W>i JiWi

)q (2.27)

4=

1

2q>M(q)q, (2.28)

where

M(q) =

3∑i=1

miV>i (q)Vi(q) +W>i (q)JiWi(q). (2.29)

Note that

V >1 V1 = `21

0 0 00 1 00 0 c2θ

V >2 V2 = `22

0 0 00 1 00 0 c2θ

V >3 V3 =

0 0 00 0 00 0 `23x + `23y

.

Also note that if Ji are diagonal matrices, then

W>1 J1W1 =

J1x 0 −J1xsθ0 (J1yc

2φ + J1zs

2φ) (J1y − J1z)sφcφcθ

−J1xsθ (J1y − J1z)sφcφcθ (J1xs2θ + J1ys

2φc

2θ + J1zc

2φc

2θ)

W>2 J2W2 =

0 0 00 J2y 00 0 (J2xs

2θ + J2zc

2θ)

W>3 J3W3 =

0 0 00 0 00 0 J3z

.

Therefore

M(q) =

J1x 0 −J1xsθ0 M22 M23

−J1xsθ M23 M33

(2.30)

TOC

Page 18: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 2. KINETIC ENERGY OF MECHANICAL SYSTEMS 16

where

M22 = m1`21 +m2`

22 + J2y + J1yc

2φ + J1zs

2φ (2.31)

M23 = (J1y − J1z)sφcφcθ (2.32)

M33 = (m1`21 +m2`

22 + J2z + J1ys

2φ + J1zc

2φ)c2θ (2.33)

+ (J1x + J2x)s2θ +m3(`23x + `23y) + J3z.

Lab Assignment H.21. Carefully work the derivation of the kinetic energy for the hummingbird by

hand to verify that they are correct.

Hints1. Since the solution is provided in the manual, there are no hints. Good Luck!

TOC

Page 19: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

3The Euler Lagrange Equations

The objective of this Chapter is to define the potential energy for the humming-bird. And show how to use the hummingbird’s definitions of kinetic and potentialenergy to derive the equations of motion using the Euler-Lagrange equation.

3.1 Potential Energy

In this section, we will define the hummingbird’s potential energy.Since there are no springs in the system, the only source of potential energy is

due to gravity. Therefore the potential energy is given by

P = m1gh1 +m2gh2 + P0

where h1 is the height of the center of mass of m1 and h2 is the height of thecenter of m2. The height of the third mass does not change with q and so it isincluded in P0. From the geometry of the hummingbird we we have

P (q) = m1g`1sθ +m2g`2sθ + P0.

3.2 Euler-Lagrange Equations

The objective of this section is to develop the simulation model for the humming-bird using the Euler-Lagrange equation

d

dt

(∂L

∂q

)− ∂L

∂q= τ −Bq, (3.1)

where L is the Lagrangian, q is the vector of generalized coordinates, τ are thegeneralized forces, and B is the damping matrix.

TOC

Page 20: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 3. THE EULER LAGRANGE EQUATIONS 18

The Lagrangian is defined as

L4= K(q, q)− P (q)

=1

2qTM(q)q− P (q).

The generalized forces are

τ =

d(f` − fr)`T (f` + fr)cφ

`T (f` + fr)cθsφ − d(f` − fr)sθ

,

where `T is the length from the pivot point to the head of the hummingbird. Takingthe partial of L with respect to q gives

∂L

∂q=

1

2

qT ∂M∂q1qT ∂M∂q2qT ∂M∂q3

q− ∂P

∂q.

Alsod

dt

∂L

∂q=

d

dtM(q)q = M(q)q + M q.

Therefore, the Euler-Lagrange equation gives

M(q)q +

M − 1

2

qT ∂M∂q1qT ∂M∂q2qT ∂M∂q3

q +

∂P

∂q= τ −Bq.

If we define

c(q, q)4= M q− 1

2

qT ∂M∂q1qT ∂M∂q2qT ∂M∂q3

q,

then the equations of motion are given by

M(q)q + c(q, q) +∂P

∂q= τ −Bq.

We have that

M =

0 0 −J1xcθ θ0 M22 M23

−J1xcθ θ M23 M33

, (3.2)

where

M22 = 2(J1z − J1y)sφcφφ (3.3)

M23 = (J1y − J1z)[(c2φ − s2φ)cθφ− sφcφsθ θ] (3.4)

M33 = 2(−m1`21 −m2`

22 − J2z + J1x + J2x − J1ys2φ − J1zc2φ)sθcθ θ (3.5)

+ 2(J1y − J1z)c2θsφcφφ.

TOC

Page 21: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 3. THE EULER LAGRANGE EQUATIONS 19

In addition, we have

∂M

∂φ=

0 0 00 2(J1z − J1y)sφcφ (J1y − J1z)(c2φ − s2φ)cθ0 (J1y − J1z)(c2φ − s2φ)cθ 2(J1y − J1z)sφcφc2θ

(3.6)

∂M

∂θ=

0 0 −J1xcθ0 0 −(J1y − J1z)sφcφsθ

−J1xcθ −(J1y − J1z)sφcφsθ N33

(3.7)

∂M

∂ψ=

0 0 00 0 00 0 0

, (3.8)

where

N33 = 2(J1x + J2x −m1`21 −m2`

22 − J2z − J1ys2φ − J1zc2φ)sθcθ.

Working through the math, we get

c(q, q) =

(J1y − J1z)sφcφ(θ2 − c2θψ2) +[(J1y − J1z)(c2φ − s2φ)− J1x

]cθ θψ

−−−2(J1z − J1y)sφcφφθ +

[(J1y − J1z)(c2φ − s2φ) + J1x

]cθφψ − 1

2N33ψ2

−−−θ2(J1z − J1y)sφcφsθ

+[(J1y − J1z)(c2φ − s2φ)− J1x

]cθφθ

+(J1z − J1y)sφcφsθ θ2 + 2(J1y − J1z)sφcφφψ

+2[−m1`

21 −m2`

22 − J2z + J1x + J2x + J1ys

2φ + J1zs

]sθcθ θψ

,

and

∂P

∂q=

0(m1`1 +m2`2)gcθ

0

.

We will model damping in each axis using

B =

bφ 0 00 bθ 00 0 bψ

. (3.9)

3.2.1 Summary

The equations of motion are

M(q)q + c(q, q) +∂P

∂q= τ −Bq. (3.10)

TOC

Page 22: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 3. THE EULER LAGRANGE EQUATIONS 20

Lab Assignment H.31. Verify that the equations of motion derived in this section are correct.

2. Implement the dynamics of the hummingbird in the hb_student pack-age. This is done by editing the file dynamics.py found in

hb_student/scripts/.

You only need to edit the part that says "Implement Dynamics for Accelera-tions Here." You will need to implement this using numpy. For the creationof numpy arrays, these links will be helpful. You may find the functionnumpy.linalg.solve to be helpful. The ODE is integrated using Runge-Kuttanumerical integration, but that is all handled for you in the propagatemethod.

3. Once you have implemented the dynamics, you will need to test them.We have given you a pre-compiled controller node that was installed inyour workspace upon building it. The controller node subscribes to the/hb_reference_state topic to receive the desired pitch and yaw an-gles. It then uses an algorithm to compute the pwm commands and pub-lishes these commands to the /hb_command topic. The dynamics nodethat you complete in this lab will subscribe to the /hb_command topic,update the states, and publish them to the /hb_state topic.

With this setup, we can use the pre-compiled controller to test your dy-namics. If the pre-compiled controller can move the hummingbird to thedesired orientation, then your dynamics are most likely correct, but there isno absolute guarantee with this.

To run the pre-compiled controller, run the launch file using the commandin a terminal.

1 roslaunch hb_common dynamics.launch

This should pull up an RVIZ window. The panel should not be enabled, andit is set to publish to the /hb_state topic. You should change the topicto /hb_reference_state and click the enabled button. Play aroundwith the sliders and see if the simulation moves to the desired pitch and yawangles. This is a good indication that your dynamics are correct. Once youthink your dynamics are correct, have a TA pass you off for the lab.

HintsThere are no hints for this lab besides to be very careful to check your math andfunction implementation. Unit tests that might allow you to compare your outputfor a given set of initial conditions and inputs with other students may be helpful.

TOC

Page 23: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Part II

Hummingbird Design Models

TOC

Page 24: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics
Page 25: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

23

The equations of motion developed in the previous chapter are too complex tobe useful for control design. Therefore the objective of this chapter is to developseveral different design models for the hummingbird that capture certain behaviorsof the system. The essential idea is to notice that since the total force on thehead of the hummingbird is F = fl + fr, the pitching motion can be controlledby manipulating F . Also, since the torque on the head of the hummingbird isτ = (fl − fr)d, the rolling motion can be controlled by manipulating τ . We alsonote that the yawing motion is driven primarily by the roll angle φ.

Accordingly, we define the longitudinal motion of the hummingbird, to be themotion involving the state variables (θ, θ), and the lateral motion of the hum-mingbird to be the motion involving the state variables (φ, ψ, φ, ψ). While thesemotions are coupled, the coupling is weak and will be neglected in the designmodels.

TOC

Page 26: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

24

TOC

Page 27: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

4Equilibria and Linearization

In this chapter we will discuss the equilibria and linearization of the longitudinaland lateral dynamics of the hummingbird.

4.1 Equilibria and Linearization for the Longitudi-nal Dynamics

In this section, we will derive an expression for the equilibrium force using theequations of motion derived in the previous chapter. Since we are interested onlyin the equilibrium force of the longitudinal dynamics, we will use the governingequation for θ stated in the second line of Equation (3.10) which is

(m1`21 +m2`

22 + J2y + J1yc

2φ + J1zs

2φ)θ + (J1y − J1z)sφcφcθψ

− ψ2sθcθ[J1x + J2x −m1`

21 −m2`

22 − J2z − J1ys2φ + J1zc

]+ 2φθ(J1z − J1y)sφcφ + φψcθ

[J1x + (J1y − J1z)(c2φ − s2φ)

]+ (m1`1 +m2`2)gcθ = `T (fl + fr)cφ − bθ θ. (4.1)

We are interested in expressing the longitudinal dynamics assuming that φ =φ = ψ = ψ = 0 in order to decouple the logitudinal and lateral dynamics.This is a reasonable assumption since the longitudinal and lateral dynamics donot strongly influence each other. Setting φ = φ = ψ = ψ = 0 gives

(m1`21 +m2`

22 + J1y + J2y)θ + (m1`1 +m2`2)g cos θ = `T (fl + fr)cφ − bθ θ.

Defining F4= fl + fr gives

(m1`21 +m2`

22 + J1y + J2y)θ + bθ θ + (m1`1 +m2`2)g cos θ = `TF. (4.2)

TOC

Page 28: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 26

Setting θ = θ = 0 gives the expression for the equilibrium force

Fe =(m1`1 +m2`2)g cos θe

`T.

Alternatively, we could feedback linearize the system by setting

F =(m1`1 +m2`2)g cos θ

`T+ F

to get the feedback linearized system

θ +

(b

m1`21 +m2`22 + J1y + J2y

)θ =

(`T

m1`21 +m2`22 + J1y + J2y

)F .

(4.3)The damping coefficient is difficult to measure and should be relatively small.Therefore, assuming b = 0 gives

θ =

(`T

m1`21 +m2`22 + J1y + J2y

)F = bθF , (4.4)

where

bθ =

(`T

m1`21 +m2`22 + J1y + J2y

). (4.5)

4.2 Equilibria and Linearization for the Lateral Dy-namics

The objective of this section is to define the equilibrium orientation and to lin-earize the lateral dynamics. The governing equations for φ and ψ are the first andthird lines of Equation (3.10) which, after setting θ = θ = θ = 0 are

J1xφ− ψ2(J1y − J1z)sφcφ = d(fl − fr)(JT + J1ys

2φ + J1zc

2φ)ψ + 2ψφ(J1y − J1z)sφcφ = `T (fl + fr)sφ,

whereJT4= m1`

21 +m2`

22 + J2z +m3(`23x + `23y).

To decouple the motion from the longitudinal states, we will assume that fl +fr = Fe, the equilibrium force required to maintain θ = θe.

Defining the torque τ4= d(fl − fr) gives

J1xφ− ψ2(J1y − J1z)sφcφ = τ

(JT + J1ys2φ + J1zc

2φ)ψ + 2ψφ(J1y − J1z)sφcφ = `TFesφ. (4.6)

TOC

Page 29: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 27

The equilibrium values are found by setting φ = ψ = φ = ψ = 0 in Equa-tion (4.6) to obtain

τe = 0

Fe sinφe = 0

Since Fe is not zero, we get that φe = 0. Linearizing the nonlinear terms ofequation (4.6) around θe = φe = 0, we find that

ψ2 sinφ cosφ ≈ ψe2

sinφe cosφe +∂

∂ψψ2 sinφ cosφ

∣∣∣(ψ,φ)

(ψ − ψe)

+∂

∂φψ2 sinφ cosφ

∣∣∣(ψ,φ)

(φ− φe)

= ψe2

sinφe cosφe + 2ψe sinφe cosφe˙ψ + ψe

2cos(2φe)φ

= 0

sin2(φ)ψ ≈ sin2(φe)ψe +∂

∂φsin2(φ)ψ

∣∣∣(φe,ψe)

(φ− φe) +∂

∂ψsin2(φ)ψ

∣∣∣(φe,ψe)

(ψ − ψe)

= sin2(φe)ψe + sin (2φe)ψeφ+ sin2 φe¨ψ

= 0

cos2(φ)ψ ≈ cos2(φe)ψe +∂

∂φcos2(φ)ψ

∣∣∣(φe,ψe)

(φ− φe) +∂

∂ψcos2(φ)ψ

∣∣∣(φe,ψe)

(ψ − ψe)

= cos2(φe)ψe − sin (2φe)ψeφ+ cos2 φe¨ψ

=¨ψ

ψφ sinφ cosφ ≈ ψeφe sinφe cosφe +∂

∂φψφ sinφ cosφ

∣∣∣(φe,φe,ψe)

(φ− φe) +∂

∂φψφ sinφ cosφ

∣∣∣(φe,φe,ψe)

(φ− φe)

+∂

∂ψψφ sinφ cosφ

∣∣∣(φe,φe,ψe)

(ψ − ψe)

= ψeφe sinφe cosφe + ψeφe cos(2φe)φ+ ψe sinφe cosφe˙φ+ φe sinφe cosφe

˙ψ

= 0

sinφ ≈ sinφe +∂

∂φsinφ

∣∣∣φe

(φ− φe)

= sinφe + cosφeφ

= φ

TOC

Page 30: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 28

where we have defined φ4= φ − φe, ψ

4= ψ − ψe, and τ

4= τ − τe. Since

φe = ψe = τe = 0, we have φ = φ, ψ = ψ, and τ = τ . We can now writeEquation 4.6 in its linearized form as

J1x¨φ = τ (4.7)

(JT + J1z)¨ψ = `TFeφ. (4.8)

4.3 Model of the Motor-Propeller

In the previous sections, we modeled the motors as producing a force perpendic-ular to the hummingbird x-y plane. The input to the motors is actually a pulse-width-modulation (PWM) command that regulates the duty cycle of the currentsupplied to the motor. The motor stops when the PWM is below 1060 µs (0%duty cycle) and is at full power when the PWM is at 1860 µs (100% duty cy-cle). To make things easier, code has been added to the hummingbird’s firmwareto convert the duty cycle to PWM. That means that the output command to thehummingbird needs to be converted from force to duty cycle, and the duty cycleis constrained in the range [0, 1], where 0 represents zero percent duty cycle, orzero current supplied to the motor, and 1 represents 100 percent duty cycle, or fullcurrent supplied to the motor.

While there are dynamics in the internal workings of the motor, we will neglectthese dynamics and model the relationship between PWM command u and forceas

F = f(u).

F is not linearly proportional to u, but rather a function of u. However, forthe purposes of this class we will assume it to be linearly porportional to u by thescalar km.

F = kmu.

We can make this assumption since F and u are almost linearly proportional toeach other in the region of operation. The region of operation is centered aroundthe force needed to maintain the hummingbird in equilibrium when ψ = θ = φ =0.

To experimentally find the value of km we apply an equal PWM signal toeach motor and increase this signal until the force balances the hummingbird atconstant pitch angle. In the equilibrium position the forces cancel and we have

`TFe = m1`1g +m2`2g.

Setting Fe = fle + fre = km(ule + ure), and solving for km we get

km =m1`1g +m2`2g

`T (ule + ure).

TOC

Page 31: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 29

While PWM is the input to the system, it is easier to think in terms of torqueand force applied to the hummingbird. The relationship between PWM commandsand force and torque are given by(

τF

)= km

(d −d1 1

)(ulur

). (4.9)

Inverting the matrix and solving for PWM command gives

ul =1

2km

(F +

τ

d

)(4.10)

ur =1

2km

(F − τ

d

). (4.11)

Lab Assignment H.41. Verify that the linearized equations of motion for the lateral and longitudinal

dynamics are correct.

2. Calculate the value of km as described in Section 4.3 (and given in the pro-cedure section below). It is suggested that you do this for both simulationand hardware, since both will be useful in future labs, but will have uniquevalues.

3. Replace the entry in hb_student/param/hb_sim.yml from the sim-ulation and hb_student/param/hb.yaml from hardware with the cor-rect value for km.

Simulation and Hardware ProcedureTo calculate the value of km follow the steps below.

1. Fix the rolling and yawing motion of the hummingbird using two of thethree screws. See Figure 4-1.

2. Using the software simulation, you can run the command below to findkm. This will allow you to click the “PWM Cntrl Enabled” button under“hb_command” (along with the general “Enabled” button) as shown in Fig-ure 4-2 and then set the PWM value directly. You can do this by increasingthe PWM value with the slider until the simulated hummingbird is at rest,balanced in the horizontal direction, in order to find km (as described in thenext hint):

1 roslaunch hb_common sim.launch run_control:=false2

TOC

Page 32: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 30

3. We are interested in finding the value of km at equilibrium such that Fe =km(ule + ure) where Fe is the equilibrium force calculated from the equa-tions of motion, and ule , ure is the pulse width modulation command be-ing sent to the left and right hummingbird motors, which range from 0 to1 in value. Slowly increase the value of the PWM slider, until the hum-mingbird balances at 0 degrees pitch . This is the equilibrium PWM valuePWMe and is the value of ule and ure such that PWMe = ule = ure andFe = km(2(PWMe)). Solve for km for your simulation and then for oneof the hardware platforms as described in the next step.

4. For a given hummingbird, run the hardware as described in the “humming-bird hardware guide” on Learning Suite. After the initial setup, you can runthe hardware with direct PWM commands again by executing the followingin your terminal:

1 roslaunch hb_common hw.launch run_control:=false2

Figure 4-1: Close-up images of the two screws used to restrict yaw (shown on left)and roll (shown on right). Make sure the screws are centered and well-seated.

TOC

Page 33: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 31

Figure 4-2: GUI screenshot that shows settings used to identify the needed PWMto balance the hummingbird and identify km.

TOC

Page 34: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 4. EQUILIBRIA AND LINEARIZATION 32

TOC

Page 35: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

5Transfer Function Models

The response of a system to an input is described by its transfer function. Bymodeling the linearized lateral and logitudinal dynamics with a transfer function,we can gain intuition on how the hummingbird will respond to a given force ortorque input. These transfer functions will be used in a later chapter to design thecontrol system for the hummingbird.

5.1 Linear Transfer Function Model for Longitudi-nal Dynamics

The longitudinal equations of motion have been decoupled from the lateral gen-eralized coordinates φ and ψ, and linearized. The linearized equation (4.4) isa second-order differential equation relating θ and F . The longitudinal transferfunction is obtained by taking the Laplace transform of (4.4) and solving for θ(s).

θ(s) =bθs2F (s). (5.1)

5.2 Linear Transfer Function Model for Lateral Dy-namics

The lateral equations of motion have been decoupled from the longitudinal gener-alized coordinate θ and linearized. The linearized equations are shown in Equa-tion (4.8). The first is a second-order differential equation relating τ and ¨

φ, andthe second is a second-order differential equation relating φ and ¨

ψ.The Laplace transform of the first equation gives

φ(s) =(1/J1x)

s2τ(s), (5.2)

TOC

Page 36: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 5. TRANSFER FUNCTION MODELS 34

and the Laplace transform of the second gives

ψ(s) =

(`TFeJT+J1z

)s2

φ(s) =bψs2φ(s), (5.3)

where

bψ =

(`TFe

JT + J1z

)(5.4)

Equations (5.2) and (5.3) show that the transfer functions for the lateral dynam-ics form a cascade structure as shown in Figure 5-1. As shown in Figure 5-1the torque τ can be thought of as the input to the roll dynamics given by Equa-tion (5.2). The roll angle φwhich is the output of the roll dynamics can be thoughtof as the input to the yaw dynamics given by Equation (5.3). This cascade struc-ture will be exploited in later labs where we will design controllers for the rolldynamics and yaw dynamics separately and enforce suitable bandwidth separa-tion to ensure a good design.

Roll Dynamics

Yaw Dynamics

ψφτ

Figure 5-1: The lateral dynamics for the hummingbird can be thought of as acascade system, where the torque drives the roll dynamics and the roll angle drivesthe yaw dynamics.

Lab Assignment H.51. Verify the transfer functions derived in this section.

2. Why does the cascade structure shown in Figure 5-1 make sense physically?

TOC

Page 37: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

6State Space Models

The objective of this chapter is to develop the linear state space models for thelongitudinal and lateral dynamics of the hummingbird. This state space modelwill be used in later labs as we implement state space control methods.

6.1 Linear State Space Model for Longitudinal Dy-namics

The linear equations of motion for the longitudinal dynamics are given by

θ = bθF ,

where we assume that F = Ffl + F is the feedback linearized force.Defining the state as

xlon4= (θ, θ)T

and the deviated control input as

ulon = F ,

then the linear state model is given by

xlon = Alonxlon +Blonulon,

where

Alon =

(0 10 0

), (6.1)

Blon =

(0bθ

). (6.2)

TOC

Page 38: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 6. STATE SPACE MODELS 36

If the output is ylon = θ, then the output equation is

ylon = Clonxlon,

where Clon = (1, 0).Note that if we design a controller law ulon(xlon), then the commanded force

will beF = Ffl + ulon.

6.2 Linear State Space Model for Lateral Dynamics

From Equation (4.8), the linearized equations for the lateral dynamics are givenby

¨φ =

1

J1xτ (6.3)

¨ψ =

1

JT + J1z`TFeφ. (6.4)

Define the lateral state as xlat = (φ, ψ,˙φ,

˙ψ)>, and the lateral input ulat = τ .

The lateral output is ylat = (φ, ψ)>. Then the linearized state equations are givenby

xlat = Alatxlat +Blatulat (6.5)ylat = Clatxlat, (6.6)

where

Alat =

0 0 1 00 0 0 10 0 0 0

`TFeJT+J1z

0 0 0

(6.7)

Blat =

001J1x0

(6.8)

clat =

(1 0 0 00 1 0 0

). (6.9)

Lab Assignment H.61. Verify the state space equations derived in this section.

TOC

Page 39: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Part III

PID Control Design

TOC

Page 40: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics
Page 41: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

7Pole Placement for Second Order Systems

The objective of this lab is to implement PD control for the longitudinal motionof the hummingbird in Python. The block diagram for the longitudinal controlleris shown in Figure 7-1.

F

kDs

kP✓✓d ++

��

b✓s2

Figure 7-1: PD control design example.

A feedback linearizing force that cancels the gravity term can be calculated as

Ffl = (m1`1 +m2`2)g

`Tcos θ.

Remember that the control force sent to the propeller motors is given by F =Ffl + F , where F is calculated from a PD controller as shown in Figure 7-1.

Lab Assignment H.7

1. Find the transfer function from Θd to Θ of the closed loop system shown inFigure 7-1.

2. Find the characteristic polynomial ∆cl(s) of the closed loop system.

TOC

Page 42: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 7. POLE PLACEMENT FOR SECOND ORDER SYSTEMS 40

3. Find kP and kD so that the rise time is tr = 1.5 s and the damping ratio isζ = 0.707. Make the rise time a tuning parameter in your code so that youcan adjust it to get good performance.

4. For this lab you will need to constrain the lattitude dynamics of the hum-mingbird. In hardware this is done by placing the pin to constrain the rolland yaw movements. In simulation, this is done by ensuring that the torquecommand is always zero.

5. In the folder hb_student\scripts, copy the template controller,controller_template.py and give it a new name but keep the pythonextension. Ex: controller_7.py. Edit the new controller file to imple-ment the longitudinal PD controller. You may assume that pitch is availableto you (as member variables of the state object - state.pitch). You will needto estimate the derivate using the following equation:

˙θ[k] =

(2σ − dt2σ + dt

)˙θ[k − 1] +

(2

2σ + dt

)(θ[k]− θ[k − 1]

)where σ is a small constant value (between 0.005 and 0.05 for example),dt is the size of the time step, [k] denotes a value from the current timestep, and [k − 1] is from the previous time step. This is known as the “dirtyderivative” and we will discuss it in a class later on.

6. Your PD control can be implemented as F = kP (Θref − Θ) − kD ˙Θ. Re-call that F = F − Ffl and therefore F = Ffl + F which implies that thefeedback linearizing force needs to be added to the output of the PD con-troller. NOTE: Your force outputs must then be scaled using the km valueyou found in a previous lab before you send right and left motor commandsto the hummingbird.

7. Implement saturation, by not allowing your PWM values to go above 0.7.Note: Your PWM values also should not be allowed to go below 0, since itdoesn’t make sense for PWM to be negative. You can do this using the “sat-urate” function shown in the template controller. The syntax for that func-tion is saturate(current_value, min_allowed, max_allowed).

8. To use your new controller, you will need to edit the launch filehb_common\launch\sim(hw).launch to start your new controller.Comment the tag

<node pkg="hb_common" type="pre_compiled_controller" name="pre_compiled_controller"/>

by adding <! − − to the beginning of the line and −− > to the end.Then you will need to uncomment the following line by removing the extradashes, exclamation mark, and the greater and less than characters:

TOC

Page 43: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 7. POLE PLACEMENT FOR SECOND ORDER SYSTEMS 41

<node pkg="$(arg package)" type="controller_$(arg lab).py"name="controller" required="true" output="screen" />

And you will also need to define the lab variable in the launch file to matchwhatever you appended to the name of your controller file. You should startby doing this in simulation, then, when it is working and you have shownthe TA, update your kP and kD gains for the real hardware and test it.

9. Using the formulas you derived for kP and kD, tune your controller designusing the rise time tr and the damping ratio ζ parameters so that the stepresponse of the system is well-damped and responsive. To test this, driveyour controller using the sliders from−15 degrees to 15 degrees. Tune yourdesign so that saturation does not occur for this step size (30 degrees).

Hints

• If yaw and roll are constrained what does this imply about φ and ψ?

• Observe that the controller is implemented using a python class structure.Your gains are stored as member variables of this class. These are refer-enced using self.<variable>. You can modify these member variables inany method, but it makes most sense to tune your gains in the __init__method. Here is a tutorial on classes and object oriented programming inpython.

• You can test if your system is saturating by using rqt_plot on the /commandtopic. If you see clipping then your system is saturating and your gains willneed to be re-tuned.

TOC

Page 44: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 7. POLE PLACEMENT FOR SECOND ORDER SYSTEMS 42

TOC

Page 45: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

8Design Strategies for Second-Order Systems

The objective of this lab assignment is to use the desired transient response char-acteristics, rise time and damping ratio, to determine PD control gains that acheivethe desired response. The longitudinal control design will utilize a single PD con-trol loop, while the lateral control design will use two PD loops designed usingprinciples of successive loop closure.

Longitudinal Control Design

In the previous chapter we showed that the transfer function from F to θ is

θ(s) =bθs2F (s).

The closed-loop transfer function for the PD implementation shown in Figure 7-1is

θ(s)

θd(s)=

kpbθs2 + kdbθs+ kpbθ

The transfer function for a canonical second-order system can be expressed interms of the damping ratio ζθ and the natural frequency ωnθ as

ω2nθ

s2 + 2ζθωnθs+ ω2nθ

.

Values for ζθ and ωnθ are determined from the desired transient response charac-teristics of the system. The natural frequency and desired rise time are approxi-mately related by the expression

tr ≈2.2

ωnθ,

TOC

Page 46: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 8. DESIGN STRATEGIES FOR SECOND-ORDER SYSTEMS 44

while ζθ can be selected to give the desired overshoot and settling time behavior.Control gains are calculated by equating the coefficients of the desired character-istic equation

s2 + 2ζθωnθs+ ω2nθ

= 0

with those of the characteristic equation of the closed-loop system, in this case

s2 + kdbθs+ kpbθ = 0.

Lateral Control DesignThe lateral motion of the hummingbird is described by its rolling and yawingmotion. Changes in the roll angle φ are caused by torques produced when theleft and right thrust values are different. When φ is non-zero, a lateral force isproduced on the hummingbird causing it to yaw, which is described by the yawangle ψ. These lateral motions are modeled by the transfer functions derived inSection 5.2. The control strategy we will use for the control of the lateral dynamicshas the transfer functions for the rolling and yawing dynamics cascaded togetherin a successive loop closure configuration as shown in Figure 8-1

1/Jx

s2

b s2

Figure 8-1: Successive loop closure block diagram for lateral dynamics.

Roll Loop Design

To design the lateral dynamics control system for the hummingbird using succes-sive loop closure, we begin with the inner roll control loop. By design, the innerroll loop response will be at least ten times faster than the outer yaw loop dynamicresponse. This will allow us to approximate the inner loop by its closed-loop DCgain when designing the outer loop.

The open loop transfer function of the inner roll loop is

φ(s) =(1/J1x)

s2τ(s)

The closed-loop transfer function of the roll loop is

φ(s)

φd(s)=

kpφ/J1x

s2 +(kdφ/J1x

)s+

(kpφ/J1x

) (8.1)

TOC

Page 47: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 8. DESIGN STRATEGIES FOR SECOND-ORDER SYSTEMS 45

with the corresponding characteristic equation

s2 +(kdφ/J1x

)s+

(kpφ/J1x

)= 0.

Based on the desired rise time trφ and damping characteristics ζφ of the innerloop, we can determine the natural frequency of the roll dynamics ωnφ and thedesired characteristic equation

s2 + 2ζφωnφs+ ω2nφ

= 0.

Proportional and derivative gains for the roll loop, kpφ and kdφ are determined bymatching coefficients of the desired and actual characteristic equations.

Yaw Loop Design

Successive loop closure requires that there be adequate bandwidth separation be-tween successive loops in the control design. The inner loop is designed to bethe fastest (highest natural frequency), with each successive loop designed to bea factor of 10 to 20 slower in frequency. Higher natural frequencies correspondto shorter rise times. In the case of the yaw loop design, if we define M as thebandwith separation factor (a constant between 10 and 20), and if the roll loop hasa designed rise time of trφ , then we would calculate the rise time of the slowerouter yaw loop to be trψ = Mtrφ . Similarly, if the inner roll loop natural fre-quency is given by ωnφ , the outer yaw loop natural frequency would be calculatedto be ωnψ = ωnφ/M . Bandwidth separation allows the inner loop dynamics to bereplaced by the DC gain of the inner loop when designing the outer loop control,thus simplifying the outer-loop design significantly.

From the closed-loop transfer function for the roll loop given by equation 8.1,we can see that the DC gain of the inner loop is 1. Approximating the inner-loopdynamics with a transfer function of 1, the yaw closed-loop transfer function canbe written as

ψ(s)

ψd(s)=

kpψbψ

s2 + kdψbψs+ kpψbψ

with the corresponding characteristic equation

s2 + kdψbψs+ kpψbψ = 0.

As discussed above, the desired rise time trψ of the outer yaw loop is chosento be a factor of 10 to 20 slower than the rise time of the inner roll loop. Theyaw loop natural frequency ωnψ is calculated from the desired yaw loop rise time.The damping ratio of the yaw loop ζψ is chosen to give the desired overshootand settling characteristics. With values for ωnψ and ζψ determined, the desiredcharacteristic equation for the yaw loop can be expressed as

s2 + 2ζψωnψs+ ω2nψ

= 0.

Proportional and derivative gains for the yaw loop, kpψ and kdψ are determinedby matching coefficients of the desired and actual characteristic equations. Withthe gains for both the roll and yaw loops calculated, the lateral successive loopclosure design is complete.

TOC

Page 48: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 8. DESIGN STRATEGIES FOR SECOND-ORDER SYSTEMS 46

Lab Assignment H.81. Suppose that the longitudinal controller design requirements are that the

time rise is trθ ≈ 1.4 sec and a damping ratio of ζθ = 0.7. Find theproportional and derivative gains kp and kd for the longitudinal controllerto achieve these requirements.

2. Suppose that the inner roll loop of the lateral controller design requirementsare that the time rise is trφ ≈ 0.3 sec and a damping ratio of ζφ = 0.7. Findthe proportional and derivative gains, kpφ and kdφ , for the roll loop of thelateral controller to achieve these requirements.

3. Find the DC-gain of the roll loop and draw the block diagram of the outerloop for controlling the yaw angle ψ, where the roll loop has been replacedby its DC gain.

4. Suppose that the outer yaw loop of the lateral controller has design require-ments for a damping ratio of ζψ = 0.7. Specify the yaw loop rise timerequirement trψ based on bandwidth separation recommendations. Find theproportional and derivative gains kpψ and kdψ for the yaw loop of the lateralcontroller to achieve these requirements.

5. Implement the longitudinal and lateral controllers in a new controller file(e.g. controller_8.py) and use the rise time and damping parametersto tune the controllers as needed so that the performance specifications aremet. Do this first in simulation, then after you have passed it off to your TA,do it on hardware.

Hints• Don’t forget to remove the lateral constraints (in sim and on the real hard-

ware).

TOC

Page 49: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

9System Type and Integrators

Lab Assignment H.91. When the inner loop controller for the hummingbird is PD control, what is

the system type with respect to tracking of the inner loop? Characterize thesteady state error when φr is a step, a ramp, and a parabola. What is thesystem type with respect to an input disturbance?

2. When the outer loop controller for the hummingbird is PD control, what isthe system type with respect to tracking of the outer loop? Characterize thesteady state error when ψr is a step, a ramp, and a parabola. What is thesystem type with respect to an input disturbance?

3. When the longitudinal controller for the hummingbird is PD control, whatis the system type with respect to tracking of the longitudinal loop? Charac-terize the steady state error when φr is a step, a ramp, and a parabola. Whatis the system type with respect to an input disturbance?

TOC

Page 50: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 9. SYSTEM TYPE AND INTEGRATORS 48

TOC

Page 51: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

10Digital Implementation of PID Controllers

The purpose of this lab is to see the difference it makes when our model has someerror and to also implement integral control on the hummingbirds.

Lab Assignment H.101. For simulation, start by changing the following parameters in hb_sim.yml:

disturbances: true

disturbance_percent: 0.2

These changes allow the parameters dynamic model to be perturbed fromtheir nominal values, thus introducing modeling uncertainty in your dy-namic model of the hummingbird. Try running your PD controller from theprior lab on this perturbed system. You should see some steady-state errorin pitch due to the dynamic model now having mass parameters that aredifferent from those used to calculate your feedforward force command.

2. Start by using the same PD gains that you used in the previous lab. Adda digital integral term for your longitudinal controller and an integral termon your outer loop for the lateral controller as well. If saturation occurs,tune your rise time parameters again to reduce the control gains so that sat-uration is eliminated. With your integrator implementation, implement ananti-windup scheme as described in Appendix ??. Pass off your simulationwith the TA before proceding to the next step.

3. Now implement PID control on the hummingbird hardware. There is noneed to add disturbances to your hb.yml file since the real system tends tohave plenty of errors in your model and disturbances. Remember that youcan run the hardware using the following command:

TOC

Page 52: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 10. DIGITAL IMPLEMENTATION OF PID CONTROLLERS 50

roslaunch hb_common hw.launch

Please remember to be cautious and careful with the hardware. It is some-what fragile and could be dangerous, so please do not allow the humming-bird to go out of control!

Pass off your hardware implementation to the TA showing your ability tocontrol both the pitch and the yaw of the hummingbird.

TOC

Page 53: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Part IV

Observer-based ControlDesign

TOC

Page 54: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics
Page 55: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

11Full-state Feedback

The purpose of this lab is to design and implement full-state feedback controlstrategies.

11.1 Lateral Control using Linear State Feedback

The objective of lateral control is to design a linear state feedback of the form

τ = −Klatxlat + krlatψc

that places the poles of the lateral dynamics at the desired pole locations. Gainvalues can be calculated using the place command in Matlab using the Alat andBlat matrices and the desired pole locations. Suppose that we desire to tune thecontroller using the two natural frequencies ωnφ and ωnψ , and the damping ratiosζφ and ζψ , then the desired closed-loop poles are given by

plat = [p1, p2, p3, p4]

=[−ζφωn,φ ± jωn,φ

√1− ζ2φ,−ζψωn,ψ ± jωn,ψ

√1− ζ2ψ

].

In Matlab, the command K_lat = place(A_lat, B_lat, p_lat); canbe used to calculate the lateral state feedback gains. The feedforward gain krlat isgiven by the formula

krlat = − 1

Cyaw(Alat −BlatKlat)−1Blat,

where Cyaw = (0, 1, 0, 0).

TOC

Page 56: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 11. FULL-STATE FEEDBACK 54

11.2 Longitudinal Control using Linear State Feed-back

The form of the controller for the longitudinal portion of the system is

F = Fe −Klon(xlon − xlon,e) + krlon(θc − θe).The first term is the feedforward equilibrium force found in Chapter 4. The secondterm is the state feedback control based on the linearized state. The third term is afeedforward term that ensures that the DC-gain of the closed-loop system is one.If the equilibrium states are zero, xe = (θe, θe)

T = (0, 0)T , then the controllersimplifies to

F = Fe −Klonxlon + krlonθc.

The control design requires the placement of two poles similar to what was donein Chapter 7. Assuming that the desired closed-loop poles are characterized by anatural frequency ωnθ and damping ratio ζθ, they are given by

plon = [p1, p2]

=

[−ζθωn,θ ± jωn,θ

√1− ζ2θ

].

In Matlab, the command K_lon = place(A_lon, B_lon, p_lon); canbe used to calculate the longitudinal state feedback gains. The feedforward gainkrlon is given by the formula

krlon = − 1

Clon(Alon −BlonKlon)−1Blon.

Lab Assignment H.111. Implement a method to compute your lateral gains Klat and krlat where

the desired closed-loop pole locations are found by solving characteristicpolynomials defined by ωnφ , ωn,ψ , ζφ and ζψ . If you do this in Matlabyou will need to create a Matlab script that generates the gains and thencopy the gains over to your controller. To do this in Python, first familiarizeyourself with the python control library. You may need to install this onyour machine to get it to run. This is done with pip install --usercontrol. This toolbox provides many powerful functions associated withcontroller design and attempts to follow Matlab’s control toolbox in syntax.Once you understand how to use this toolbox, you may implement yourgain calculations in your controller.

2. Wherever you calculate your gains, make sure to also have a check pro-grammed in to verify that the systems (Alat, Blat) and (Alon, Blon) arecontrollable. If you’re doing this in Python, this is the controllability check-ing function..

TOC

Page 57: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 11. FULL-STATE FEEDBACK 55

3. Implement a method to compute the longitudinal gainsKlon and krlon wherethe desired closed-loop pole locations are found by solving characteristicpolynomials defined by ωn,θ and ζθ.

4. Implement the longitudinal and lateral controllers for your simulation of thehummingbird. Note: Since SS controllers are implemented differently thanPID controllers, it may be a good idea to copy controller.py to a newfile and use it as a template moving forward. Verify that you satisfy yourdesign specifications in terms of rise time. Tune the controllers by adjustingvalues for damping ratio and natural frequency until you are satisfied withtheir performance.

Hints• For most of the previous labs, you have not had to do much matrix math in

python. Going forward you should plan to use the numpy library. Usefulreferences that relate numpy operations and syntax to operations in Matlabcan be found at either of the following links:

– numpy-for-matlab-users

– cheatsheet

TOC

Page 58: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 11. FULL-STATE FEEDBACK 56

TOC

Page 59: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

12Integrator with Full State Feedback

Lab Assignment H.121. Augment the lateral and longitudinal state-space representations to include

a state that is the integral of the output error. For the lateral dynamics, thisis the integral of the yaw error and for the longitudinal dynamics, this is theintegral of the pitch error.

2. Compute the lateral gainsKlat and klat,I using the place command, wherethe desired closed-loop pole locations are defined by ωnφ , ωn,ψ , ζφ, ζψ , andthe integral pole location. For starters, select the integral pole location to be−ωn,ψ/2.

3. Compute the longitudinal gains Klon, klon,I using the place, where thedesired closed-loop pole locations are defined by ωn,θ, ζθ, and the integralpole location. For starters, select the integral pole location to be −ωn,θ/2.

4. Implement the longitudinal and lateral controllers with integral feeedbackin your controller and verify that the controller performs well on the sim-ulation. Introduce a constant disturbance to the longitudinal control (e.g.,an error in the equilibrium force) and a small constant disturbance torqueto the yaw control and verify that they are mitigated by the integral con-trol implemented. This can be done by adding some constant value to yourcalculated force and torque. Tune the controllers by adjusting values fordamping ratio, natural frequency, and integral pole until you are satisfiedwith their performance.

5. Implement the longitudinal and lateral controllers on the hummingbird hard-ware. Tune the controllers until you and the TA are satisfied with theirperformance.

TOC

Page 60: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 12. INTEGRATOR WITH FULL STATE FEEDBACK 58

TOC

Page 61: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

13Observers

Lab Assignment H.13.aIn this lab, we will be designing and implementing a full-state estimator, some-times called a Luenberger observer, using pole placement methods. Your designwill assume that only the angle states (roll, pitch, and yaw) are measured andavailable for feedback as the vector y. Full-state feedback requires both the an-gle and rate states (the derivatives of the angles), so we will use an estimator (orobserver) to estimate the full state vector for the hummingbird.

1. Compute the lateral observer gains Llat using the place command (inMATLAB or the python control library), where the desired observer polelocations are five times faster than the lateral controller pole locations (fromLab Assignment H.12).

2. Compute the longitudinal observer gains Llon using the place command,where the desired observer pole locations are five times faster than the con-troller pole locations (from Lab Assignment H.12).

3. Using your controller.py file from the full-state feedback lab, imple-ment a full-state estimator to estimate the state vector for the longitudinaland lateral dynamics of the hummingbird.

4. Implement full-state feedback controllers for longitudinal and lateral dy-namics using estimated states for feedback.

5. Test your controller-observer system in simulation.

6. Implement the longitudinal and lateral observers on the hummingbird hard-ware in conjunction with the full-state feedback designs from a prior lab.Demonstrate their correct function. Tune estimator pole locations if needed.

TOC

Page 62: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 13. OBSERVERS 60

Hints• When you place your observer poles, remember to take the transpose of A

and C. This is due to the mathematical duality between observability of(A,C) and controllability of (AT , CT ).

• As with the other hummingbird labs, when debugging, it may be beneficialto consider the longitudinal and lateral systems separately. This can be doneby zeroing the state derivatives in the dynamics.py file for those statesthat you want to ignore. You can then focus on the control and estimationfor each subsystem separately before combining them together.

Lab Assignment H.13.bThis lab is designed to stretch your skills in ROS and controls. So, don’t be afraidto ask for help from a TA. In this lab, we will be designing a Luenberger observerand you will be writing the ROS Node to implement it.

1. By hand, draw the ROS network for the combined controller-observer sys-tem, carefully identifying the topics and message types each node will pub-lish and subscribe two. Before, proceeding, have a TA check off your net-work.

2. Using your controller.py (from Lab Assignment H.12) as a guide,create a new file called observer.py.

3. Make necessary changes to the node name so it doesn’t conflict with controller.py.

4. Add in your publishers and subscribers to observer.py.

5. Set the publishers and subscribers in observer.py.

6. In observer.py, verify that the systems (Alat, Clat) and (Alon, Clon)are observable.

7. Make callbacks for the subscribers in observer.py. There should be 2callbacks, one for each subscriber.

8. Compute the lateral observer gains Llat using the place command, wherethe desired observer pole locations are five times faster than the lateral con-troller pole locations.

9. Compute the longitudinal observer gains Llon using the place command,where the desired observer pole locations are five times faster than the con-troller pole locations.

10. Test your observer to make sure that it localizes correctly. Note: at thispoint if you run rqt_graph the system will not be closed loop, we areonly testing to make sure we get a good estimate.

TOC

Page 63: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 13. OBSERVERS 61

11. Have the TA check your rqt_graph and observer estimate to make sureyour observer is working properly.

12. Modify controller.py to subscribe to the estimate coming out of yourobserver, and use that estimate for your control. Note: this means youshould no longer be differentiating states to get velocity estimates.

13. Test your controller-observer system in simulation.

14. Implement the longitudinal and lateral observers on the hummingbird hard-ware in conjunction with the full-state plus integral feedback designs fromthe last lab. Demonstrate their correct function. Tune estimator pole loca-tions if needed.

Hints

• When drawing your ROS network, you should only concern yourself with3 nodes in your system. Don’t worry about the nodes that publish to Rviz.

• For the publishers/subscribers associated with your state estimate x, you canuse geometry_msgs/Twist. Basically it contains 2 Vector3 attributes.You can store the roll, pitch and yaw in linear and the derivatives in angular.

• You do not need to make a separate node for the longitudinal and latitudinalobservers. These should reside in the same node.

• It’s best to set up observer.py with a class structure and store your stateestimates as member variables.

• For help with setting the publishers and subscribers refer to Controller.pyand rospy pub sub tutorial.

• When you place your observer poles, remember to take the transpose ofA and C. This is due to the duality between observability of (A,C) andcontrollability of (AT , CT ).

• observer.py should have 2 subscribers and 1 publisher. See Figure 13.1in the controlbook.

• When making the callbacks, have the callback associated with u updatesome member variable and have the callback associated with ym propogatethe dynamics of your observer.

• Use RK4 to propogate the dynamics of your observer. You can modify theRK4 method in your simulator to accomplish this.

TOC

Page 64: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 13. OBSERVERS 62

• You can test your observer estimation by adding in another publisher forthe hummingbird estimate with message type State.msg. You can viewthis message through Rviz to see your state estimate. You can even makeyour own message based on the State.msg that includes the angle ratesand call it FullState.msg. If you define this file in the same folder asState.msg, (/hb/hb_msgs/msg/) then you can simply run ”catkin_make“in your main hummingbird workspace directory and it will generate codefor this new message type.

• You can streamline testing your controller-observer system by adding an ad-ditional node tag to controller_sim.launch and controller_hw.launch.

TOC

Page 65: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

14Disturbance Observers

Lab Assignment H.141. Verify that the lateral and longitudinal systems are observable using thecontrol.obsv() command.

2. Compute the estimator gainsL for the lateral and longitudinal systems usingthe scipy.signalimportplacepoles command.

3. Implement the lateral and longitudinal controllers using the estimated statesxhat. Verify that the controller meets the time rise requirements. Tune thegains if necessary.

14.0.1 Python*

4. Modify your main.py and sim_plot.py files to plot the estimated states alongwith the actual states. Tune the estimator gain as necessary so that theestimated states closely approximate the real states.

14.0.2 Matlab*

4. Modify your simulink to plot the estimated states along with the actualstates. Tune the estimator gain as necessary so that the estimated statesclosely approximate the real states.

Hints

TOC

Page 66: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 14. DISTURBANCE OBSERVERS 64

TOC

Page 67: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

Part V

Loopshaping Control Design

TOC

Page 68: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics
Page 69: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

15Frequency Response of LTI Systems

Lab Assignment H.15

Hints

TOC

Page 70: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 15. FREQUENCY RESPONSE OF LTI SYSTEMS 68

TOC

Page 71: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

16Frequency Domain Specifications

Lab Assignment H.16

Hints

TOC

Page 72: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 16. FREQUENCY DOMAIN SPECIFICATIONS 70

TOC

Page 73: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

17Stability and Robustness Margins

Lab Assignment H.17

Hints

TOC

Page 74: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 17. STABILITY AND ROBUSTNESS MARGINS 72

TOC

Page 75: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

18Compensator Design

Lab Assignment H.18

Hints

TOC

Page 76: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

CHAPTER 18. COMPENSATOR DESIGN 74

TOC

Page 77: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

aConnecting to the Hummingbird with ROS

Often when building complex systems that incorporate multiple executable pro-grams, whether on a single machine or across a network of machines, they needto communicate by sharing data. This can be done using a program called ROS(Robot Operating System). ROS is like a bridge connecting two executable pro-grams that are otherwise unable to communicate. ROS controls the type of infor-mation and the rate at which the information is communicated. This is very usefulsince it allows developers to break down complex systems into smaller pieces thatare connected together with ROS. For example, the hummingbird (a remote ma-chine) needs to receive pulse width modulation (PWM) commands from anothercomputer (the host computer). To be truthful ROS is overly capable and complexfor controlling the hummingbird. In addition ROS 1.0 is technically not a realtime communication protocol. However, it will allow us to easily prototype andimplement control algorithms in python, both in simulation and on the humming-bird hardware. ROS is a widely used research and development tool for roboticsand autonomous systems. The labs have been structured so that much of its com-plexity will be hidden from the casual user. For those interested in learning moreabout ROS, these labs will provide an introduction.

ROS uses the catkin build system. A build system creates software targets(e.g., libraries, executables, scripts, interfaces, etc.) from raw source code that canbe used by an end user. The purpose of this appendix is to teach you the basics ofROS and set up a catkin workspace that will contain all of your code. You will alsoconnect to the hummingbirds, visualize the encoder values, view the ROS networklayout, and more. This walkthrough is based on ROS kinetic or later version inan Ubuntu 16.04 or later environment. We are currently using ROS melodic andUbuntu 18.10.

Note: Please do not connect to the hummingbirds using a wireless connection.Wifi is much slower than a direct Ethernet connection, and can have an average lagtime of 100 ms which will likely lead to instability of your control implementation.This could lead you to believe there is a bug in your code when the real issue isthe lag in the wireless connection.

TOC

Page 78: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 76

Setting Up Your catkin Workspace

The first step in getting started with your own ROS setup is to create a catkinworkspace. A catkin workspace is simply a folder (directory) where you canmodify, build, and install, ROS packages. In this tutorial we will name our catkinworkspace hummingbird_ws, however, feel free to use a different name. Ourhummingbird_ws will have three subfolders (subdirectories): build, devel,and src. Our attention will be focused primarily on src where our source codewill reside.

Start by opening up a terminal by using the keyboard shortcut ctrl+alt+t.Navigate to the directory where you want to create your workspace using the cdcommand. In this tutorial, we will place and initialize the workspace in the homedirectory using the following commands in the terminal.

cd ∼/mkdir -p hummingbird_ws/srccd hummingbird_ws/srccatkin_init_workspace

Next we need the hummingbird packages that are located on the BYU MagiccGitlab. (It is recommended that you go to this webpage and look at the differ-ent packages’ README.md files for more information about each package.) In thesource directory of your workspace we need to add some ROS packages: hb_st,hb_msgs, hb_viz. The hb_student directory will eventually contain the hum-mingbird parameters and your controllers. The hb_student directory will alsoeventually contain the hummingbird dynamics for simulation. The hb_msgs di-rectory contains all of the custom ROS messages for the hummingbird workspace,and the hb_viz directory contains the animation code.

To add these packages, navigate to the source directory of your workspace(you should already be there). Now clone the packages using the following com-mands.

git clone https://magiccvs.byu.edu/gitlab/hummingbird/hb_student.gitgit clone https://magiccvs.byu.edu/gitlab/hummingbird/hb.git

Now, build your workspace by using the command catkin_make in yourworkspace directory.

cd ..catkin_make

For more information on the individual packages or setting up your workspace,take a look at the different packages on the BYU Magicc GitLab.

ROS Basics

In this section, we will discuss the ROS workspace, ROS packages, ROS nodesand ROS topics. The majority of the work regarding initializing the hummingbird

TOC

Page 79: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 77

workspace, writing the packages, and communicating over the ROS frameworkhas been implemented for you. However, a brief overview of ROS and the pack-ages contained in the hummingbird workspace will allow you to test your workand understand where the controller fits into the ROS framework.

Hummingbird Workspace

A ROS workspace is the outermost directory that organizes the project’s com-ponents: source files, build files, etc. The hummingbird_ws contains multiplepackages in the source folder

• hb

– hb_common: Contains common code on top of which students willbuild for the entire semester.

– hb_ros_driver: Code that interfaces with the low-level microcontroller on the hummingbird platform.

– hb_msgs: Stores the custom ROS messages used for the humming-bird project.

– hb_viz: An RVIZ package to visualize the position of the humming-bird based on the hummingbird state. This package can also publishdifferent topics: hummingbird states, hummingbird reference states,and hummingbird command.

• hb_student: This is where you will put code to simulate the dynamicsof the hummingbird. This is also where you will put your code to controlthe hummingbird as we learn different control methods.

The majority of your work will take place in the hb_student directory.You should also notice a build and devel folder in your workspace. If you

don’t see them, you have not built your workspace using catkin_make. Forhelp doing this, refer to the above section or any of the README.md files in thepackages.

The build folder contains the compiled code. The devel folder containsseveral setup.*sh files that are responsible for adding the workspace path to avariable that ROS uses to locate workspaces. To include these variables in yourcurrent shell session, you will need to source them by running

$ source <path_to_workspace>/devel/setup.bash

Listing a.1: Add workspace to ROS path

You can tell that this command worked by looking at the environment variableROS_PACKAGE_PATH. This variable shows the paths of all current sourcedROS packages. This variable can be viewed by executing

TOC

Page 80: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 78

$ echo $ROS_PACKAGE_PATH

Listing a.2: ROS_PACKAGE_PATH

The contents of the variable ROS_PACKAGE_PATH should be printed to the termi-nal. Make sure that the path to your workspace has been added. If you see it, theworkspace has been properly created. The file setup.bash will need to be sourcedat the beginning of every bash session (or whenever you open a new terminal).You can automate this by adding the source command to your .bashrc. You cando this by executing the command

$ echo "source <path_to_workspace>/devel/setup.bash" >> ∼/.bashrc

Listing a.3: ROS_PACKAGE_PATH

Remember, if you do not source this file, ROS will not be able to find anything inthe ROS packages including nodes, messages, services, etc., so don’t forget this!If putting the command in your .bashrc file does not seem to work, you willneed to manually source that file for every terminal you open instead. If youare interested in learning more about catkin workspaces and how to create them,you can find more information in this tutorial.

ROS PackagesAs mentioned above, a ROS workspace can contain one or more packages. Apackage is a module that can contains various pieces of software to perform acertain function. Each package that ROS handles has certain dependencies thatmust be met in order to properly compile. These dependencies are listed in eachpackage’s CMakeLists.txt and package.xml files. For example, if you looked atthe hb_viz package’s CMakeLists.txt, you will see that it depends on hb_msgs. Infact, all of the hummingbird packages depend on hb_msgs.

To complete these labs, you will not be required to make any packages or mod-ify package.xml or CMakeLists.txt. The repo that you cloned is self-contained andwill only need to be modified to complete the labs, however, you can find moreinformation on ROS packages, including how to make your own package, in thistutorial.

ROS MessagesA way that programs (of the same or different languages) can communicate overROS is through using ROS messages. You can think of message as a user defineddata type that contains information that needs to be communicated between twopackages. A message file is a simple text file that consists of one or more fieldtype(s) and field name(s). Some of the different field types that can be used are:

• int8, int16, int32, int64 (plus uint*)

• float32, float64

TOC

Page 81: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 79

• string

• time, duration

If multiple packages depend on the same messages, it is convenient to cre-ate another package that contains only the messages. This will bypass the needto create the same messages in every package. Instead, the package containingthe messages can be included as a dependency by the other packages. To seehow this is implemented with the hummingbird, navigate to the directory hum-mingbird_ws/src/hb/hb_msgs/msg and look at the files State.msg and Com-mand.msg. You can see what is in the file by running

$ rosmsg show State

As you can see, the State message contains floats describing the state of the hum-mingbird and the Command message contains PWM commands sent to the rightand left motors of the hummingbird. Lastly, the ReferenceState.msg message isused to communicate the desired yaw and pitch values.

RoscoreRoscore is a collection of programs and nodes that are required to make ROS run.Before any node can run, roscore needs to be started. To start roscore, open upanother terminal or another tab in the current terminal (press Ctrl+Shift+t whilein the current terminal) and run this command

$ source <path_to_workspace>/devel/setup.bash

to initialize bash functions that will be used to setup your ROS environment.Note that you can also add this command to your .bashrc file.

Now enter the following commands in the terminal.

$ roscore

The first line is a function that sets the ros master to the local machine. Thesecond line starts roscore.

When working with a network of computers that communicate through ROSonly one computer needs to have roscore running, and this computer is knownas the ros master. By running roscore on your local computer, by default yourcomputer is the ros master.

If you are not working from a computer in the hummingbird lab, you need tomake sure that your computer is the ROS master. To check, type

$ echo $ROS_MASTER_URI

If http://localhost:11311 is printed to the screen then your computer is theROS master and you can go ahead and start roscore by entering the command

$ roscore

TOC

Page 82: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 80

Otherwise you computer is not the ROS master and needs to be changed to bethe ROS master. To do this, enter the command

$ export ROS_MASTER_URI=http://localhost:11311$ roscore

If there are problems in the future, make sure that ROS_MASTER_URI isset properly in all your terminals. One way to do this is to also add an explicitcommand to your .bashrc file (which is run every time a new terminal is opened).You can do this as follows:

$ echo "export ROS_MASTER_URI=http://localhost:11311" >> ∼/.bashrc

More information about roscore can be found here.

ROS NodesA ROS node is an executable file that uses ROS to communicate with other nodesvia messages or other means. ROS nodes are a powerful tool in abstraction, sincethey isolate the implementation of a single node from how it communicates withother nodes. This is inherently what makes ROS a very modular system. Later inthis tutorial, we will talk about tools to visualize the node network and see howthey communicate.

Starting a NodeTo start the node, use the command rosrun. An example is shown below. Note:since you have not yet implemented the controller, this command will assuredlythrow some errors.

$ rosrun hb_common controller.py

The command’s syntax is

rosrun ros_package_name executable_name

More information on rosrun can be found here. To verify that a node is run-ning, open up another terminal and type the command

$ rosnode list

This command lists all of the currently running nodes. To shutdown the nodeand roscore, use the command Ctrl+c in the terminals that you used to start thenode and roscore. You can also use the rosnode kill node_name com-mand to kill the node. Nodes, however, are of little use unless they can com-municate with each other. This communication is performed using messages andinstantiations of these messages are called topics.

TOC

Page 83: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 81

ROS TopicWhen a node sends or receives information using a message, it sends (publishes)or receives (subscribes) that information to or from a ROS Topic (a name used toidentify the type of message). A ROS Topic is like an intermediary that holds aqueue of ROS messages. When a node subscribes to the topic, the oldest messageis popped off the queue and given to the node. When a node publishes a messageto the topic, it is added to the queue. If the queue is full when a new message isbeing published to it, the oldest message will be discarded.

A ROS Topic can have multiple nodes subscribing (subscribers) to it and mul-tiple nodes publishing (publisher) to it. In their most basic form, a subscriber pullsinformation off of a topic and a publisher puts new information on a topic. For ex-ample, controller code you write as a ROS node will subscribe to the /hb_statetopic and publishes to the /Command topic. Students will not need to concernthemselves with the nuances of publishers and subscribers to complete these labsbut further information about them is found in these tutorials.

Current topics running on the ROS system can be viewed using the rostopiclist command. If you want to see the information being published to a certaintopic you can use the rostopic echo command. We will test to make sure weare getting information from the hummingbirds using this command. First openup a terminal, navigate to your workspace, source the setup.bash file if needed andrun the following command.

$ roslaunch hb_viz visualize.launch

This will start the visualization node and GUI. On the upper left hand side youwill see sliders, a button and a drop down menu. This area is called a panel andyou can interface with it to change the states of the hummingbird. First make surethat the enabled button is selected. Now move the sliders and see the animationmove with it.

Now let’s look at the states using the rostopic echo command, by open-ing up another terminal, navigating to your workspace, sourcing the setup.bashfile if needed and run the following command

$ rostopic echo /hb_state

You should see the states being printed. If you move the sliders, you will seethese values change.

If you want to see all of the topics available, run

$ rostopic list

In the Hummingbird RViz panel switch to the hb_command topic by chang-ing Layout Type. Now click on the enable button to start publishing commands.You can use the sliders to adjust the Force and Torque being applied to the hum-mingbird.

In a new terminal source the devel/setup.bash file and run.

rostopic echo /hb_command

TOC

Page 84: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 82

You should see the left and right motor pwm commands being printed to yourscreen. To stop the topic being written to the terminal, kill the process with ctrl +c.

ROS also has another utility rqt_plot that provides plotting. When rqt_plotis run it brings up a window displaying a live plot of a chosen topic. Try it out byrunning

$ rqt_plot /hb_command

Now move the adjust the sliders in the RViz panel to see the plot change. You canlearn more about rqt_plot here.

ROS provides a utility to visualize the current nodes and topics in the ROSnetwork. This utility is called rqt_graph. While running the dynamics andthe visualization that you launched earlier, run the command rqt_graph. Thiswill pull up a window displaying the ros nodes and rostopics currently running.rqt_graph is an extremely useful debugging tool and it is recommended thatyou use it in future labs when you run into errors. More info can be found here.

You can stop any process (besides "roscore") in any of your terminals beforemoving on to the next part by typing ctrl + c. at the same time in the terminal.

ROS Launch

A nice tool that ROS provides is a ROS Launch file. A Launch file is used toorganize the execution of one or more nodes across a network. You will use theroslaunch command many times throughout the labs, but all of the launch fileshave been written for you; however, you will have to edit the controller launchfiles to specify your specific controller node that you wish to run. A basic tutorialon launch files is found here.

Let’s start up the dynamics and visualization nodes by running the dynam-ics.launch file

roslaunch hb_common dynamics.launch

If you have an error stating that the dynamics.py file was not found, this ismost likely due to the python file not having executable permissions in Linux.ROS requires that every python node have at least user executable permissions.You can add these permissions by navigating to the file and running the command

chmod +x dynamics.py

To view the permissions of the file, type

ll

You should now see something like this

---x--x--x 1 ____ ____ 7361 Jan 23 15:05 dynamics.py*

TOC

Page 85: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 83

where the ’x’ indicates that the file is executable. Now that the file is exe-cutable, try running the node again

roslaunch hb_common dynamics.launch

Note that this command will almost certainly fail now for a second reason.This is because the file used to simulate the dynamics is currently missing infor-mation that you will include in a future lab. Adding the dynamics is left as a laterassignment.

You have now finished!

TOC

Page 86: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX A. CONNECTING TO THE HUMMINGBIRD WITH ROS 84

TOC

Page 87: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

bParameters of the Hummingbird

The physical parameters of the hummingbird are given in the table below, wherem1, J1 are the mass and inertia of the hummingbird head, rotors, and rolling shaft,m2, J2 are the mass and inertia of the pitching body, and m3, J3 are the mass andinertia of the hummingbird that only yaws. When the roll pitch and yaw angles areall zero, the position of the center of mass of m1 is (`1, 0, 0)>, the position of thecenter of mass of m2 is (`2, 0, 0)>, and the position of the center of mass of m3

is (`3x, `3y, `3z)>. The distance from the center of rotation to the hummingbird

head is `T and the distance from the center of the hummingbird head to the rotorsis d.

Figure 2-1: Hummingbird coordinate frames and nomenclature.

The hummingbird in the lab has the following parameters, which have beenfound experimentally:

The parameter value km is not given, but will be computed in one of the labs.

TOC

Page 88: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX B. PARAMETERS OF THE HUMMINGBIRD 86

g 9.81 m/s2

`1 0.247 m`2 −0.039 m`3x −0.007 m`3y −0.007 m`3z 0.018 m`T 0.355 md 0.12 mm1 0.108862 kgJ1 diag(0.000189, 0.001953, 0.001894) kg-m2

m2 0.4717 kgJ2 diag(0.000231, 0.003274, 0.003416) kg-m2

m3 0.1905 kgJ3 diag(0.0002222, 0.0001956, 0.000027) kg-m2

km ? N/PWM

TOC

Page 89: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

csupportFiles

This appendix discusses the support files: slider_input.py, signal_generator.py,and sim_plot.py which are used to simulate in Python.

slider_input.py

The slider_input.py file that will be looked at is from the example discussed in thesection Animation Example: Inverted Pendulum ?? . This file has been providedto make organizing multiple sliders on one axes simple. The file contains threeclasses: Sliders, mySlider and Slider. The Sliders class is the parent class thatinherits mySlider. It organizes one or more instances of mySlider class based onthe parameters set by the user, and is the only class the user needs to interact with.The mySlider class uses the parameters set in Sliders to organize multiple Sliderclasses in one axes. An inheritance diagram has been included to help visualizethe structure.

(Silders→ mySlider→ Slider)

The file might look long and complex, but the user only needs to be familiarwith the three sections of the file that are surrounded by two rows of the # sign.

Section 1

The first section only contains the variable self.num_of_sliders. This vari-able indicates the number of sliders that will be created and displayed in the sameaxes. The Inverted Pendulum has two inputs: θ and z. This means that there needsto be a slider for each input with a total number of two sliders.

Section 2

In the second section, the objects of mySlider class are created for each input.The mySlider class takes in 7 parameters. These parameters have default values

TOC

Page 90: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 88

which the user can customize. The default values allow the users to not have topass in every parameter. If a parameter is not passed in, the class assumes thedefault value. Also, the parameters can be passed in by order or by name. Bothways are demonstrated in section 2 of Listing c.1.mySlider(self,num_of_sliders=1, slider_number=1, maxV=1,minV =-1,intV=0,gain=1,name=’Slider’)

num_of_sliders - The total numbers of sliders that will be rendered.slider_number - Each slider object will have a unique slider number. This

determines the relative position of a specific slider to other sliders. Lower numbersliders will be placed above higher number sliders.

maxV - The maximum value the slider can have.minV - The minimum value the slider can have.intV - The initial value of the slider.gain - The value of the slider is multiplied by gain before it is passed to the

parent class. This allows for unit conversion or scaling. For example, the slidervalues may be in degrees, but the gain can convert it from degrees to radians asdone in this example.

name - The name of the slider.

In this example, an object of mySlider class needs to be created for z and θ.Slider z will be placed above slider θ since its slider_number is lower than θ′sslider_number. Both of them will have a maxV of 90, minV of -90, initV of 0,and a gain of π

180 to convert the value from degrees to radians.

Section 3

Section 3 resides in the function getInputValues which returns a list of thesliders’ values to the file main.py. In Section 3, the user can organize the order inwhich the values are returned.

In this example, since there are two sliders (z and θ), only the two values fromthem will be returned. The value from slider z will be element 0 and the valuefrom slider θ will be element 1 in the list object that is returned.

import numpy as npimport param as Pimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider

class Sliders:’’’ This class inherits the Slider class. Its purpose is to

help organize one or more sliders in an axes.’’’

# You only need to modify the code inside ’#’s as shown below.################################################################### CODE TO BE MODIFIED##################################################################

def __init__(self):

TOC

Page 91: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 89

# Creates a figure and axes for the Sliders.self.fig,self.ax = plt.subplots()plt.axis("off") # Suppress the axis from showing.

# SECTION 1###############################################################self.num_of_sliders = 2 # The number of Slider objects that

# will be used. The minimum value is 1###############################################################

’’’ Down below you will create Slider objects for each slideryou need. The format for each object is as follows:self.Object1 = Slider(self.num_of_sliders, slider_number,

maxV = 1,minV = -1,intV = 0, gain = 1, name = ’Slider’)self.Object2 = Slider(self.num_of_sliders, slider_number,

maxV = 1,minV = -1,intV = 0, gain = 1, name = ’Slider’)...

self.ObjectN = Slider(self.num_of_sliders, slider_number,maxV = 1, minV = -1,intV = 0, gain = 1, name = ’Slider’)

For a description of each parameter, see the Slider Classbelow.’’’

# SECTION 2################################################################# Instantiate objects hereself.Sz = mySlider(self.num_of_sliders,1,

2*P.ell,-2*P.ell,P.z0,1,’z’)self.Stheta = mySlider(num_of_sliders = self.num_of_sliders,

slider_number = 2, maxV = 90,minV = -90,intV =0,gain = np.pi/180, name =’theta’)

################################################################

plt.draw()

def getInputValues(self):’’’ This function is called to return the sliders’ values.

The variable values is a list that contains the values ofall of the sliders. You will need to insure that thisfunction returns the values in the following format.values = [self.object1.getValue(),

self.object2.getValue(),...,self.ObjectN.getValue] ’’’

# SECTION 3################################################################values = [self.Sz.getValue(),self.Stheta.getValue()]################################################################return values

# You do not need to modify the class below. However, it would be good

TOC

Page 92: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 90

# to become familiar with it.

class mySlider:

def __init__(self,num_of_sliders=1, slider_number=1, maxV = 1,minV = -1, intV = 0, gain = 1, name = ’Slider’):# num_of_sliders - The number of Sliders that you will use# slider_number - This number starts at 1 and its max value# should be num_of_sliders . This variable# determines the location of the Slider in# the axes; 1 corresponds to the top Slider# in the axes and largest number corresponds# to the bottom of the axes. Each Slider# object needs a unique slider_number.

self.data = 0 # Current value of Sliderself.name = name # Name of Sliderself.maxValue = maxV # Max value of the Sliderself.minValue = minV # Min value of the Sliderself.initValue = intV # Initial value of Sliderself.gain = gain # The gain of the Slider can be used for

# conversion purposes. EX, If you want the# Slider to be in terms of degrees but the# value passed in radians. The max and min# values will in terms of degrees and the# gain would be pi/180 to convert# the Slider’s value from degrees to radians.

self.Slider_length = 0.5 # This is the length of the Slider in terms# of the percentage of the figure’s length

self.Slider_width = 0.03 # This is the width of the Slider in terms# of the percentage of the figure’s width

# Sets the position and color of the Slider

# The horizontal position of the Slider in the figure.hpos = 0.8 - 0.6/(num_of_sliders+1)*slider_number

# Specify a subsection of the current axes where the slider will go.self.axSlider = plt.axes([0.5-self.Slider_length/2,hpos, self.Slider_length,

self.Slider_width], axisbg = ’orange’)

# Instantiate a slider, and create a handle to itself.SliderHandle = Slider(self.axSlider, self.name, self.minValue,

self.maxValue, valinit = self.initValue)self.data = self.initValue

# When a change occurs on the slider, the function self.update# will be called.self.SliderHandle.on_changed(self.update)

# Updates the value of the Slider when the Slider is changeddef update(self,val):

self.data = self.SliderHandle.val

TOC

Page 93: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 91

# Returns the current value of the Slider(s)def getValue(self):

return self.data*self.gain

Listing c.1: Slider Input File

step.py

In this section we will discuss the step.py file that can be used to generate stepfunctions with a specified amplitude and time delay. Many of the assignmentswill ask you to implement a step funciton, you can use this file, modify it, orcreate your own.

1 def step_function(t,T,A):2 # t is the sim time.3 # T is the sim time when the step4 # function assumes the value of A5 # A is the amplitude of the step function6 u = 0;7 if t > T:8 u = A9 return u

Listing c.2: step.py

As you can see from listing c.2, the function step_function accepts three pa-rameters: t, T , and A. t is the current simulation time, T is the time delay insimulation time, and A is the amplitude of the step function. This file is fairlystraight forward. For an example of this file, look at the robot arm design studyassignment 7 that is on the Control Book Website.

3.1 sim_plot.py

In this section we will discuss the sim_plot.py file that can be used to plot keydata. This section uses an example based off of the Robot Arm assignment 7 thatis discussed in Appendix ?? Section ??.

An example of the sim_plot.py file is shown in Listing c.3.

1 import matplotlib.pyplot as plt2 from matplotlib.lines import Line2D3 import numpy as np456 class plotGenerator:7 ’’’ The purpose of this class is to organize multiple plots in one8 figure using subplots.The plots will be organized in n x m9 dimensions in the figure; where n represents the number of rows,

10 and m represents the number of columns. Ex, a subplot with11 dimensions 3 x 2 will hold 6 plots. 3 plots per row, and 2 plots12 per column.

TOC

Page 94: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 92

1314 Not every plot needs to be used. Ex, if you were to plot only15 5 plots, you would still need dimensions 3 x 2 and one of the16 plots would never be populated.’’’1718 # You only need to modify the code inside ’#’s as shown below.19 ##################################################################20 # CODE TO BE MODIFIED21 ##################################################################22 def __init__(self):23 #SECTION 124 ##############################################################25 # Number of subplots = num_of_rows*num_of_cols26 self.num_of_rows = 2 # Number of subplot rows27 self.num_of_cols = 1 # Number of subplot columns28 ##############################################################2930 # Crete figure and axes handles31 self.fig, self.ax = plt.subplots(self.num_of_rows,32 self.num_of_cols, sharex=True)3334 # A list to hold the time history35 self.time_history = []3637 # The list type variable will store your plot objects38 self.handle = []3940 ’’’ Create the handles below.41 The class plotGenerator inherits the class myPlot, and42 organizes one or more instances of myPlot in a figure. The43 myPlot class organizes one or more line objects in a single44 axes. The syntax for myPlot is4546 myPlot(axes,gain,xlabel,ylable,etc)4748 To see a full description of myPlot, read the comments located49 in the class myPlot. However, note that all arguments have50 default values except the axes argument.51 (i.e., A myPlot object could easily be created by5253 myPlot(self.ax[0])5455 The class myPlot also supports pass-by-reference and56 pass-by-name. Examples are given below.5758 self.handle.append(myPlot(self.ax[0],2,’xlabel’,’ylabel’,59 ’title’))60 self.handle.append(myPlot(self.ax[1],180.0/np.pi,61 title="y_r/y")62 self.handle.append(myPlot(self.ax[2],1,title="Force",63 legend=("Force","Torque"))6465 The myPlot class also comes with default line and color66 styles. You can either specify the line or color styles67 that you want when creating the myPlot object or you can68 modify the default values that are contained within the69 myPlot class.

TOC

Page 95: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 93

70 ’’’71 # Section 272 ####################################################################73 self.handle.append(myPlot(self.ax[0],180.0/np.pi,’t(s)’, ’deg’,74 ’theta_r/theta’))75 self.handle.append(myPlot(self.ax[1],1,’t(s)’,’Nm’,’torque’))76 ####################################################################777879 # Update the history80 def updateDataHistory(self,new_t, new_data):8182 """83 This function updates the data history of all the plots.84 - new_t: The current simulation time.85 - new_data: Is a list of data lists for each plot. The86 order of the data must be the same order in which87 the classes myPlot were created.8889 Ex: There are two subplots. Instantiated as shown below9091 self.handle.append(myPlot(self.ax[0],180.0/np.pi,92 ’t(s)’, ’deg’,’theta_r/theta’))9394 self.handle.append(myPlot(self.ax[1],1,’t(s)’,95 ’Nm’,’torque’))9697 The first subplot plots theta_r and theta and the second subplot98 plots Torque. Since this is the order in which the myPlot99 classes were appended to the handle list, this is the order

100 in which the data must be passed.101102 Continuing the example:103104 new_data = [[theta_r,theta],[torque]]105106 Notice that new_data is a list of lists. The first inner list107 contains the data meant for the first plot, and the second108 inner list is meant for the second plot.109110111 """112113 # Add the new time data114 self.time_history.append(new_t)115116 # Update all other data117 for i in range(len(self.handle)):118 self.handle[i].updateHistory(new_data[i])119120 # Renders the data to the plots121 def update_plots(self):122 for i in range(len(self.handle)):123 self.handle[i].update_plot(self.time_history)124125126

TOC

Page 96: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 94

127128 class myPlot:129 ’’’ This class organizes one or more line objects on one axes’’’130131 def __init__(self, ax, gain = 1,xlabel = ’x-axis’,132 ylabel = ’y-axis’,title = ’title’,133 colors = [’b’,’r’,’g’,’c’,’m’,’y’,’b’],134 line_styles = [’-’,’--’,’-.’,’:’],135 legend = None, grid = True):136137 ’’’ ax - This is a handle to the an axes of the figure138 gain - a scalar variable used on the data. This can be used139 to convert between units. Ex. to convert from140 radians to degrees, the gain should be 180/np.pi141 colors - Indicates the line color. If there are multiple lines,142 colors can be a list of different colors. Below is a143 list of options. Note that they are strings.144145 ’b’ - blue146 ’g’ - green147 ’r’ - red148 ’c’ - cyan149 ’m’ - magenta150 ’y’ - yellow151 ’k’ - black152153 line_style - Indicates the line style. If there are multiple154 lines, line_style can be a list of different line155 styles. Below is a list of options. Note that they156 are strings.157158 ’-’ - solid line159 ’--’ - dashed line160 ’-.’ - dash_dot161 ’:’ - dotted line162163 legend - A tuple of strings that identify the data.164 EX: ("data1","data2", ... , "dataN")165166 xlable - Label of the x-axis167 ylable - Label of the y-axis168 title - Plot title169 gird - Indicates if a grid is to be overlapped on the plot170 ’’’171172173 self.legend = legend174 self.data_history = [] # Will contain the data history175 self.ax = ax # Axes handle176 self.gain = gain # The scales the data177 self.colors = colors # A list of colors.178 # The first color in the list179 # corresponds to the first line180 # object.181 self.line_styles=line_styles # A list of line styles.182 # The first line style in the list183 # corresponds to the first line

TOC

Page 97: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 95

184 # object.185 self.line = []186187 # Configure the axes188 self.ax.set_ylabel(ylabel)189 self.ax.set_xlabel(xlabel)190 self.ax.set_title(title)191 self.ax.grid(grid)192193194 # Keeps track of initialization195 self.init = True196197198 # Adds the new data to the data history list after199 # scaling it by the gain.200 def updateHistory(self,new_data):201 # new_data: a list containing the new data.202 # Ex: new_data = [theta_r, theta]203 self.data_history.append([t*self.gain for t in new_data])204205 def update_plot(self,time_history):206207 # If it is being initialized208 if self.init == True:209210 # size contains the number of line objects to create211 size = len(self.data_history[0])212213 for i in range(size):214 # zip rearranges the list215 data = zip(*self.data_history)216217 # Instantiate line object and add it to the axes218 self.line.append(Line2D(time_history,data[i],219 color = self.colors[np.mod(i,len(self.colors)-1)],220 ls = self.line_styles[np.mod(i,len(self.line_styles)-1)],221 label = self.legend[i] if self.legend != None else None))222223 self.ax.add_line(self.line[i])224225 self.init = False226 if self.legend != None:227 plt.legend(handles=self.line)228 else: # Add new data to the plot229230 # zip rearranges the list231 data = zip(*self.data_history)232233 # Updates the x and y data of each line.234 for i in range(len(self.line)):235 self.line[i].set_xdata(time_history)236 self.line[i].set_ydata(data[i])237238 # Adjusts the axis to fit all of the data.239 self.ax.relim()240 self.ax.autoscale()

TOC

Page 98: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 96

Listing c.3: robotArm/hw_7/sim_plot.py

The sim_plot.py file contains the parent class plotGenerator which organizesmultiple child classes called myPlot. The class plotGenerator organizes multipleplots in one figure using subplots. The plots are organized in n x m dimensions;n represents the number of rows and m represents the number of columns. Forexample, a figure containing subplots with dimensions 3 x 2 will hold 6 plots. 3plots per row, and 2 plots per column.

Not every subplot needs to be used. Ex, if you were to plot only 5 plots, youwould need dimensions 3 x 2 and one of the plots would never be populated.

The subplot’s dimensions are indicated on Lines 23-38 using the variableself.num_of_rows and self.num_of_cols. Notice that these variables are sur-rounded by ’#’ indicating that this section needs to be modified by the user. Theother section that needs to be modified by the user starts on Line 72 and is labeledSection 2.

In Section 2, the multiple instances child class myPlot are created and theirobject handles are placed inside the list handle. The order in which the myPlotobject handles are placed inside the list handle determines the order in which dataneeds to be passed in (this will be discussed later).

The syntax for the class myPlot is

myPlot(ax, gain, xlabel, ylabel, title, colors, line_styles, legend, grid).

All of these parameters have default values except the parameter ax. A de-scription of each parameter is given below.

• ax - This is a handle to one of the axes on the figure.

• gain - This is used to scale the data that is passed to the plot. This canalso be used to convert between units. Example, to convert from radians todegrees, the gain should be 180.0

π . This parameter has a default value of 1.

• colors - This indicates the line colors. If there are multiple lines on a givenaxes, colors can be a list of containing different colors. Example, colors= [’b’,’r’]. This parameter has a default value of [’b’,’r’,’g’,’c’,’m’,’y’,’b’].There are more color option that can be found online.

• line_style - Indicates the line style. If there are multiple lines on a giveaxes, the first line style in line_style corresponds to the first line. Thedefault value of this parameter is [’-’,’–’,’-.’,’:’].

• legend - The parameter is used to add a legend on the axes. It must be atuple of strings that identify the data. Example, ("data1","data2","data3").The default value is no legend.

• xlabel - The label of the x-axis

• ylabel - The label of the y-axis

TOC

Page 99: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 97

• title - The title of the plot

• grid - Indicates if a grid is to be overlapped on the plot.

The axes’s properties are mostly set up in lines 172-193. You can read the filefor more information on these properties.

The parent class plotGenerator uses two functions to pass data to the childclass myPlot: updateDataHistory and update_plots.

The function updateDataHistory updates the plot’s data with new data, butit does not render the data to the plot. This function is passed the parameternewt and newdata. newt is a float containing the current simulation time andnew_data is a list of lists containing data for each plot. The order of the datamust be the same order in which the myPlot object handles were passed to the listhandles.

In this example, there are two subplots created in Section two starting on line71. The first subplot plots thetar and theta as a function of time, and the secondsubplot plots torque as a function of time. Since this is the order in which theymyPlot classes were appended to the list handle, this is the order in which thedata must be passed.

Continuing the example:

new_data = [[thetar, theta], [torque]]

Notice that new_data is a list of lists. The first inner list contains the datameant for the first subplot, and the second inner list is meant for the second sub-plot.

In Line 114, new_t is added to time_history, and in lines 116-118, the plotsare updated with the new data.

The function update_plots starts on line 121. It renders the plot’s data tothe axes. The two tasks performed by updateDataHistory and update_plots arekept separate to allow the data history to be updated at a different rate than theplots. This will increase efficiency.

The rest of the file will not be discussed, but it is recommended that you lookthought it to understand how it works. Using the file is rather simple once it isunderstood since the user only needs to modify two sections of it.

signal_generator.py

In this section we will discuss the signal_generator.py file that can be used togenerate signals with a specified amplitude, frequency and offset. This sectionuses an example based off of the inverted pendulum design study assignment 8that is discussed in Appendix ?? Section ??. The listing for this can be seenbelow.

1 import numpy as np2 from scipy import signal

TOC

Page 100: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 98

34 class Signals:5 ’’’ This class inherits the Signal class. It is used to organize6 1 or more signals of different types: square_wave,7 sawtooth_wave, triangle_wave, random_wave.’’’89 # You only need to modify the code inside ’#’s as shown below.

10 ##################################################################11 # CODE TO BE MODIFIED12 ##################################################################13 def __init__(self):14 self.handle = [] # This is the handle to various signals1516 ’’’ Down below you will create mySignal objects for each signal17 you need. The syntax for each object is as follows:18 self.Object1 = Signal(A, F,signal_type, phase)19 self.Object2 = Signal(A=1, F=0.1, signal_type, phase)20 ...21 self.ObjectN = Signal(A, F)2223 The class MySignal parameters can be passed by reference or name.24 The parameters also have default values as shown below. This makes25 creating a myClass simple if the default values are wanted.2627 self.handle.append(mySignal())2829 For a description of each parameter, see the mySignal Class30 below.3132 All mySignal objects need to be appended to the list self.handle ’’’3334 #SECTION 135 ##################################################################36 self.handle.append(mySignal(0.5,0.01)) # z37 ##################################################################3839 # This function returns the values of the signal generator as40 # as a function of time. The order in which the values are returned is41 # the same order that the mySignal objects were appended to the42 # list self.handle.43 def getRefInputs(self,t):44 ref_inputs = []45 for i in range(len(self.handle)):46 ref_inputs.append(self.handle[i].signal(t))47 return ref_inputs484950 class mySignal:5152 def __init__(self,A = 1,f = 1,offset = 0, signal_type = ’square_wave’, phase = 0):53 self.A = A # Amplitude of the signal54 self.f = f # Frequency of the signal, Hz55 self.phase = phase # Phase of the signal, Radians56 self.offset = offset # Offset of signal5758 if signal_type == ’square_wave’:59 self.signal = self.square_wave

TOC

Page 101: Hummingbird Manual Introduction to Feedback Controlcontrolbook.byu.edu/lib/exe/fetch.php?media=hummingbird_manual.pdfJan 06, 2021  · preliminary lab will cover learning the basics

APPENDIX C. SUPPORTFILES 99

60 elif signal_type == ’sawtooth_wave’:61 self.signal = self.sawtooth_wave62 elif signal_type == ’triangle_wave’:63 self.signal = self.triangle_wave64 elif signal_type == ’random_wave’:65 self.signal = self.random_wave66 else:67 print("input signal type not recognized")6869 def square_wave(self,t):70 return self.A*signal.square((2*np.pi*self.f*t+self.phase), duty = 0.5) +self.offset7172 def sawtooth_wave(self,t):73 return self.A*signal.sawtooth((2*np.pi*self.f*t + self.phase), width = 0)+self.offset7475 def triangle_wave(self,t):76 return self.A*signal.sawtooth((2*np.pi*self.f*t + self.phase), width = 0.5)+self.offset7778 def random_wave(self,t):79 return self.A*np.random.rand()+self.offset

Listing c.4: invertedPendulum/hw_8/signal_generator.py

The parent class Signals organizes multiple instances of the child class mySig-nal. The class mySignal begins on line 50 of Listing c.4, and its syntax is

mySignal(A,f,offset,signal_type,phase)

A is the amplitude of the signal, f is the frequency of the signal in Hz, offsetis the offset of the signal, signal_type is the type of signal, and phase is the phaseof the signal. There are four different signal types that are available: square wave,sawtooth wave, triangle wave, and random wave. The random wave signal canrepresent random noise.

The class mySignal is instantiated in the parent class on line 34. Notice howthis section is surrounded by ’#’ indicating that it is a section that the user needsto modify. In Section 1, all of the mySignal objects are created and placed in a listof handles. The order in which the objects handles are placed in the list handlesdetermines the order in which the input reference is returned to the main function.

In this example there is only one reference input being generated with an am-plitude of 0.5 and a frequency of 0.01 representing zr. Lets say that there isanother input reference such that Section 1 looks like

self.handle.append(mySignal(0.5,0.01)) # zself.handle.append(mySignal(15*np.pi/180,0.2)) # Psi

then the order in which the reference signals are returned is refinputs =[zr, psir]. This is shown in function getRefInputs on line 43.

For more information, read the provided file.

TOC