BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta...

110
BACHELOR THESIS Computer System Engineering, Mechatronic Engineering, 180 credits Virtual Prototyping and Physical Validation of an Inverted Pendulum "Sea-Calf Bot" Martin Gustavsson, Viktor Frimodig Cyber-Physical System, 15 credits Halmstad, February 5, 2015

Transcript of BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta...

Page 1: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BA

CH

EL

OR

THESIS

Computer System Engineering, Mechatronic Engineering, 180 credits

Virtual Prototyping and Physical Validation of anInverted Pendulum

"Sea-Calf Bot"

Martin Gustavsson, Viktor Frimodig

Cyber-Physical System, 15 credits

Halmstad, February 5, 2015

Page 2: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt
Page 3: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Virtual Prototyping and PhysicalValidation of an Inverted Pendulum

”Sea-Calf Bot”

Bachelor thesis 15 credits

Computer System EngineeringMechatronic Engineering

February 5, 2015

Authors

Viktor FrimodigMartin Gustavsson

Supervisor: Walid TahaExaminer: Bjorn Astrand

Halmstad University

Page 4: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

iv

Page 5: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Acknowledgments

We would like to thank Thomas Lithen and Tommy Salomonsson for theirknowledge and help about hardware. Xu Fei for help with Acumen. DucVinh La, Rami Raad Ishac, Adam Davidsson, Fredrik Lindblom and ShivanandNarayandas for perusal and feedback. Our supervisor and customer Walid Tahafor a lot of ideas, leadership and for providing us with this project. BjornAstrand our examiner for valuable feedback and the grades we pray for.

Sincerely

Viktor Frimodig

Martin Gustavsson

Halmstad February 5, 2015

v

Page 6: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

vi

Page 7: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Link to the project homepage http://sea-calf-bot.webnode.se/ in QR-code. Made in MS Paint Adventures.

This work is licensed under a Creative Commons Attribution-NonCommercial4.0 International License.

vii

Page 8: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

viii

Page 9: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Abstrakt

Arbetet motiveras av malet att knyta samman verklighet och modell, samt att seom det finns mojlighet att utveckla ett billigt utbildningsverktyg for utbildningi cyberfysiska system.

Detta projekt har undersokt mojligheter att bygga en billig inverterad pendelmed regulator samt koppla samman denna med modelleringsspraket Acumen. IAcumen skapa en modell av systemet och jamfora den med en fysisk prototyp.

For att losa dessa problem har en 3D skrivare anvants for att skapa hardvara.Arduino UNO for styrning och Raspberry Pi for att mojligora kommunikationmed Acumen over WLAN.

Resultatet blev en billig inverterad pendel, som kan byggas for en kostnadrunt 750 kr. Grafer fran Acumen, och fran data samlad fran sensorer kananalyseras.

Med en modell av en inverterad pendel visar resultaten att Acumen kananvandas i utveckling av cyberfysiska system. Skillnader finns mellan modelloch verklighet men aven likheter.

Nyckelord - Reglerteknik, Cyberfysiska System, Inverterad Pendel, LagrangesEkvationer, PD-Regulator.

ix

Page 10: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

x

Page 11: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Abstract

The work is motivated by the goal of linking reality and model, and to see ifthere is an opportunity to develop an inexpensive educational tool for trainingin cyber-physical systems.

This project has investigated the possibilities to build a cheap inverted pen-dulum with controller and connect this with the modeling language Acumen.Acumen models is used for comparison with the actual prototype.

To solve these problems has a 3D printer been used to create hardware,Arduino UNO for control and Raspberry Pi for enable communication withAcumen over WLAN.

The result was a cheap inverted pendulum, which can be built for a costaround 750 SEK. Graphs created in Acumen and from data collected fromsensors can be analyzed.

With a model of the inverted pendulum system, the results show that Acu-men can be used in the development of cyber-physical systems. There aredifferences between model and reality but also similarities.

Keywords - Automatic Control, Cyber-Physical Systems, Inverted Pendulum,Lagrangian Mechanics, PD-Controller.

xi

Page 12: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

xii

Page 13: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Contents

1 Introduction 11.1 Goals and Objectives . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Background 52.1 Acumen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Cyber-Physical Systems . . . . . . . . . . . . . . . . . . . . . . . 52.3 Inverted pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . 62.4 State-of-the-Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.4.1 Similar projects and products . . . . . . . . . . . . . . . . 72.5 Conclusion background . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Theory 93.1 Modeling of Dynamic Systems . . . . . . . . . . . . . . . . . . . . 9

3.1.1 Model of a Pendulum . . . . . . . . . . . . . . . . . . . . 93.1.2 Euler-Lagrange’s equation . . . . . . . . . . . . . . . . . . 10

3.2 Control theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.2.1 Balance control . . . . . . . . . . . . . . . . . . . . . . . . 123.2.2 Energy based Swing-Up control . . . . . . . . . . . . . . . 153.2.3 Hybrid control . . . . . . . . . . . . . . . . . . . . . . . . 16

3.3 Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.3.1 Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.3.2 Potentiometer . . . . . . . . . . . . . . . . . . . . . . . . . 183.3.3 Accelerometer and Gyro . . . . . . . . . . . . . . . . . . . 18

3.4 Actuator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.4.1 DC motor . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.4.2 Servo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3.5 Computer Networking . . . . . . . . . . . . . . . . . . . . . . . . 223.5.1 TCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.5.2 UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Method 254.1 Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.2 Modeling in Acumen . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.2.1 Visual model . . . . . . . . . . . . . . . . . . . . . . . . . 274.2.2 Modeled characteristics of the real system . . . . . . . . . 27

4.3 Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.4 Construction of prototype . . . . . . . . . . . . . . . . . . . . . . 28

xiii

Page 14: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

4.4.1 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.5 Actuation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.6 Automatic Control . . . . . . . . . . . . . . . . . . . . . . . . . . 304.7 Microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

4.7.1 SAM3U4E . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.7.2 Arduino UNO . . . . . . . . . . . . . . . . . . . . . . . . . 324.7.3 Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . 33

4.8 Measuring technology . . . . . . . . . . . . . . . . . . . . . . . . 334.8.1 Gyro and accelerometer . . . . . . . . . . . . . . . . . . . 344.8.2 Hengstler rotary encoder . . . . . . . . . . . . . . . . . . . 344.8.3 Bourns potentiometer . . . . . . . . . . . . . . . . . . . . 34

4.9 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364.9.1 Quality tests . . . . . . . . . . . . . . . . . . . . . . . . . 36

4.10 Experiment and analysis of data . . . . . . . . . . . . . . . . . . 374.10.1 Network latency . . . . . . . . . . . . . . . . . . . . . . . 374.10.2 Noise level . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.10.3 Disturbance rejection . . . . . . . . . . . . . . . . . . . . 374.10.4 Simulation of control program . . . . . . . . . . . . . . . . 384.10.5 Validation of Acumen models . . . . . . . . . . . . . . . . 38

5 Results 415.1 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.2 Prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

5.2.1 Power requirements and Noise . . . . . . . . . . . . . . . 475.2.2 Control system . . . . . . . . . . . . . . . . . . . . . . . . 485.2.3 BOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.3 Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.3.1 Network Latency . . . . . . . . . . . . . . . . . . . . . . . 49

5.4 Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.4.1 Increased task period . . . . . . . . . . . . . . . . . . . . 525.4.2 Increased resolution of the ADC . . . . . . . . . . . . . . 545.4.3 Increased friction . . . . . . . . . . . . . . . . . . . . . . . 56

5.5 Control system sturdiness . . . . . . . . . . . . . . . . . . . . . . 57

6 Discussion 596.1 Summary of goals . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

6.1.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596.2 Analysis and Interpretation . . . . . . . . . . . . . . . . . . . . . 59

6.2.1 Virtual models . . . . . . . . . . . . . . . . . . . . . . . . 596.2.2 Network latency . . . . . . . . . . . . . . . . . . . . . . . 606.2.3 Noise level . . . . . . . . . . . . . . . . . . . . . . . . . . . 606.2.4 Disturbance . . . . . . . . . . . . . . . . . . . . . . . . . . 606.2.5 Prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

6.3 What would be done differently today . . . . . . . . . . . . . . . 61

7 Conclusion 637.1 Experiences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637.2 Future work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

7.2.1 Certification . . . . . . . . . . . . . . . . . . . . . . . . . 64

xiv

Page 15: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Bibliography 67

A Requirement specification 73

B Virtual models in Acumen 77

C Wiring 83

D Control program 85

xv

Page 16: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

xvi

Page 17: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

List of Figures

1.1 Ping pong game in Acumen. . . . . . . . . . . . . . . . . . . . . . 11.2 Virtual prototype. . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Typical control system. . . . . . . . . . . . . . . . . . . . . . . . 31.4 Control system and Acumen. . . . . . . . . . . . . . . . . . . . . 31.5 Control system and Acumen controller. . . . . . . . . . . . . . . 4

2.1 Issues in a Cyber-Physical System (CPS) [5]. . . . . . . . . . . . 52.2 Law enforcement Segway. . . . . . . . . . . . . . . . . . . . . . . 72.3 Similar projects and products. . . . . . . . . . . . . . . . . . . . . 8

3.1 Diagram of pendulums. . . . . . . . . . . . . . . . . . . . . . . . 103.2 Inverted pendulum. . . . . . . . . . . . . . . . . . . . . . . . . . . 103.3 Poles unstable system. . . . . . . . . . . . . . . . . . . . . . . . . 133.4 Closed loop negative feedback control system. . . . . . . . . . . . 133.5 Diagram of a P- and D-controller poles. . . . . . . . . . . . . . . 143.6 Diagram of a PD controller’s poles. . . . . . . . . . . . . . . . . . 153.7 Hybrid control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.8 Principle of an optical encoder. . . . . . . . . . . . . . . . . . . . 173.9 Principle of an optical absolute encoder. . . . . . . . . . . . . . . 183.10 Block diagram of a complementary filter. . . . . . . . . . . . . . 193.11 Basic knowledge about a brushed DC motor. . . . . . . . . . . . 203.12 Diagram of a DC motor used for derive motor equations [32]. . . 203.13 Block diagram over a servo motor . . . . . . . . . . . . . . . . . . 213.14 Difference between TCP and UDP [49]. . . . . . . . . . . . . . . 22

4.1 Visualization in Acumen. . . . . . . . . . . . . . . . . . . . . . . 274.2 Feautures added to Acumen. . . . . . . . . . . . . . . . . . . . . 284.3 Design, prototype. . . . . . . . . . . . . . . . . . . . . . . . . . . 294.4 Hitec HS-422, DC-servo [56]. . . . . . . . . . . . . . . . . . . . . 304.5 SAM3U-EK [60]. . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.6 Arduino UNO [62]. . . . . . . . . . . . . . . . . . . . . . . . . . . 324.7 Raspberry Pi Model B+ [64]. . . . . . . . . . . . . . . . . . . . . 334.8 Rotary Encoder, Hengstler RI32-O/1000ER.11KB. . . . . . . . . 344.9 Potentiometer, Bourns 3590S-6-103L [69]. . . . . . . . . . . . . . 35

5.1 Set-up of Acumen simulation. . . . . . . . . . . . . . . . . . . . . 415.2 Visual representation of RIP. . . . . . . . . . . . . . . . . . . . . 455.3 3D-printed parts. . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

xvii

Page 18: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

5.4 Prototype. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465.5 PWM-signal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475.6 Measured angle from potentiometer. . . . . . . . . . . . . . . . . 475.7 Network latency. . . . . . . . . . . . . . . . . . . . . . . . . . . . 505.8 Latency, sending larger data. . . . . . . . . . . . . . . . . . . . . 515.9 Packets got buffered. . . . . . . . . . . . . . . . . . . . . . . . . . 525.10 Simulation of increased period. . . . . . . . . . . . . . . . . . . . 545.11 Simulation increased resolution. . . . . . . . . . . . . . . . . . . . 555.12 Simulation increased friction. . . . . . . . . . . . . . . . . . . . . 565.13 Graphs showing the system’s robustness. . . . . . . . . . . . . . . 57

7.1 TOPIO 3.0, a ping pong playing robot [74]. . . . . . . . . . . . . 64

xviii

Page 19: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

List of Tables

3.1 Definitions [32] of variables from Fig. 3.12. . . . . . . . . . . . . . 21

5.1 BOM, all prices in Swedish kronor. . . . . . . . . . . . . . . . . . 495.2 Initial condition for simulation. Resolution from the prototype. . 535.3 Increased instability. . . . . . . . . . . . . . . . . . . . . . . . . . 535.4 Initial condition for simulation, resolution. . . . . . . . . . . . . . 555.5 Simulation, increased resolution. . . . . . . . . . . . . . . . . . . 555.6 Initial condition for simulation, friction. . . . . . . . . . . . . . . 565.7 Simulation, friction. Change in overshoot and amplitude. . . . . 56

xix

Page 20: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

xx

Page 21: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Nomenclature

Abbreviations

ADC Analog to Digital ConverterBOM Bill of materialsCAD Computer-Aided DesignMCU MicrocontrollerPC Personal ComputerPWM Pulse-width modulationRIP Rotary Inverted PendulumSPI Serial Peripheral InterfaceSSI Server Side IncludesTCP Transmission Control ProtocolUDP User Datagram ProtocolUSB Universal Serial BusWLAN Wireless Local Area Network

Pendulum

Symbol Meaning Unit

α The angle between the horizontal axisand the arm

[rad]

g Gravitational constant [m/s2]Ja Moment of inertia for the arm [kg ∗m2]Jp Moment of inertia for the pendulum [kg ∗m2]la Length of the arm [m]lp Length of the pendulum [m]ma Mass of the arm [kg]mp Mass of the pendulum [kg]ra The distance between the arm pivot

point and the center of mass[m]

rp The distance between the pendulumpivot point and the center of mass

[m]

θ The angle between the vertical axis andthe pendulum

[rad]

T Kinetic energy [J ]

xxi

Page 22: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

u The linear acceleration of the pivotpoint

[m/s2]

V Potential energy [J ]

Actuator

Symbol Meaning Unit

β Actuator angle [rad]βm Motor angle [rad]Bm Motor, viscous friction [Nms]ia Current, motor winding [A]Kb Motor back-emf, constant [V/rad/sec]Kt Motor torque, constant [Nm/A]La Inductance, motor winding [H]n Gearbox ratio [n : 1]Ra Resistance, motor winding [ω]τ Torque, actuator [Nm]τm Torque, motor [Nm]vm Supply voltage [V ]

xxii

Page 23: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

1 Introduction

This chapter introduces a definition of the problem and objectives of the project.Although limitations will be described.

Halmstad University has a model of a ping pong game with competing agentsin Acumen, shown in Fig. 1.1. This model is used as the term project for theMasters (and Senior Bachelors) level course in cyber-physical systems. Thegeneral problem question for the university are how to go from the model inAcumen to a real ping pong playing robot, and to do this in a manner thatcan allow them to demonstrate this important connection to students takingadvanced courses.

Figure 1.1: Ping Pong game in Acumen. Used at Halmstad university as aneducational tool.

To achieve this many key critical step has to be taken toward that goal, and thisproject will be about the first step which will be constructing both virtual andphysical models of an inverted pendulum with a controller, and establishingthe tight connection between them. Ultimately, the aim is to build workingprototypes and then improve and validate the model.

1.1 Goals and Objectives

The needs that the project should satisfy is that the university wants to showstudents how the real world is connected to the virtual. It will also benefit theglobal research project Acumen since it should demonstrate that it is possibleto use Acumen to make a tangible prototype.

1

Page 24: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 1. INTRODUCTION 2

To do this a virtual model of the pendulum and its controller will be made inAcumen. And for validating of the simulated model a physical model of aninverted pendulum, including the control system, will be constructed. To testthe strong connection between the virtual and physical models, the plan is toset up the virtual and physical systems so that it is possible to have Acumencontrol the pendulum directly. With this functionality, if there is a differencebetween the virtual and physical models, there is a chance to improve both toget them to be reasonably consistent.

The work is based on the assumption that by using an inverted pendulumit is possible to experimentally investigate enable virtual prototyping and de-velopment of much more sophisticated robots. By virtual prototyping, it willbecome feasible to visually observe improvements in the controlling software.An intriguing ability that will make software contributes more to people’s phys-ical life and well being.

Some requirements for the project from the full requirement specification inAppendix A.

• Develop an accurate mathematical model and visualize it in Acumen.

• Develop an inverted pendulum controller in Acumen.

• Construct inverted pendulum system with controller that communicateswith Acumen by WLAN.

• Use data from the sensor in Acumen.

• It shall be possible to build more inverted pendulums to a low cost.

• The pendulum should be able to swing up from an non-inverted position.

Following figures visualize parts of the project that will be implemented to reachthe goals that were presented above. One part will be to develop models of thecontrol system in Acumen. Fig. 1.2 shows a block diagram of different parts ofa control system modeled in Acumen.

Figure 1.2: Virtual Prototype: Several models interact with each other to createa virtual model that can be observed.

Page 25: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 1. INTRODUCTION 3

Figure 1.3: Graph of a typical control system. This system will be modeled inAcumen and implemented in a MCU.

In Fig. 1.3 is a graph presented which shows a typical control system. It closelyresembles the diagram showed in Fig. 1.2 which representing an Acumen model.The controller in this system is typically implemented on a microcontroller(MCU) and this control system will also be implemented and running on aMCU as a test to demonstrate closed loop control for the prototype.

Figure 1.4: Control system and Acumen. By connecting the model in Acumenwith a real physical prototype can verification be made.

If Fig. 1.3 presents a real system controlling a plant and Fig. 1.2 present asimulation of the same system it is interesting to show how much these twosystem differs. One step will be to create a connection between these two systemsand allow comparison between them. Fig. 1.4 show this link between the controlsystem and the modeling language.

This link can be implemented by using WLAN with a server and a client.The values can be used to make the models in Acumen to move. These valuescan also be utilized to provide graphs to make comparisons with the graphsAcumen presents.

Page 26: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 1. INTRODUCTION 4

Figure 1.5: Control system and Acumen controller. By enabling Acumen tosend actuation signals in real time, difference between model and reality can befurther examined.

One goal of the project is to make Acumen to be a part of the control loopas showed in Fig. 1.5. This would make it possible to use and verify the con-troller in Acumen directly by enabling it to send actuation signals to actuators.By switching from the MCU controller and Acumen controller their behaviorcan be compared. This enables the engineer to work more on models and con-trollers in the modeling language and verify the function in the real world beforeimplementing the control on a MCU.

1.2 Limitations

In this project, an inverted pendulum with a movement in two degrees of freedomis considered.

Control

The control system should only keep the pendulum upright. This implies thatthe arm the pendulum is mounted on is allowed to move in order to keep thependulum from falling but no or small effort is made to control the arm position.Control of multiple variables like arm position and angle of the pendulum ispossible but requires more complex control system.

Budget

The project has a budget of 6000 SEK that should not be exceeded. To achievethis equipment provided from the university should be used when necessary.

One prototype should cost around 100 dollars to reproduce. This is becauseit should be possible to sell the prototype to schools in developing countries.

Even if the final prototype should cost around 100 dollars so can more sensorsfor validation be used.

Page 27: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

2 Background

This chapter provides a description of the work done related to this project.Research and similar projects will be presented. A description of Acumen andthe inverted pendulum will also be given here.

2.1 Acumen

Acumen is a program currently developed by Prof. Walid Taha and the rest ofthe Effective Modeling research group [1]. It is used for modeling and simulationof dynamic systems that have both continuous and discrete behaviors, so calledhybrid systems [2].

This is important in applications like real-time software, robotics and mecha-tronics. In recent years, methods for modeling of hybrid systems has been de-veloped and Acumen is one of the applications were it is possible to performmodeling in. Another modeling language which have likeness to Acumen isModelica. Modelica is used in industry by many companies [3]. This concludesthat there is a need for research and improvements in modeling languages tomeet the industry today and in the future.

2.2 Cyber-Physical Systems

A cyber-physical systems [4] deals, Fig. 2.1, with the interaction between soft-ware and a physical process. Embedded computers that wireless monitor phys-ical processes, through feedback, which affects computations is a typical cyber-physical system.

Figure 2.1: Issues in a Cyber-Physical System (CPS) [5].

5

Page 28: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 2. BACKGROUND 6

Economic and social conditions is greater than realized and great efforts are be-ing made to develop the technology. Significant challenges exist because physicalcomponents differs from object-oriented software components through qualityand safety.

2.3 Inverted pendulum

An inverted pendulum is a pendulum upside down with it pivot point placedunder its center of mass. This form an inherent unstable system. While theinverted pendulum can stand up as described before, inverted position, anysmall disturbances will cause the pendulum to fall. An inverted pendulumcontroller’s job is to keep the pendulums center of mass above its pivot pointeven when disturbances occur [6].

2.4 State-of-the-Art

The inverted pendulum problem is not uncommon in the field ofcontrol engineering. The uniqueness and wide application of tech-nology derived from this unstable system has drawn interest frommany researches and robotics enthusiasts around the world. In re-cent years, researchers have applied the idea of a mobile invertedpendulum model to various problems like designing walking gaitsfor humanoid robots, robotic wheelchairs and personal transportsystems. ([7], p.2).

As Rich Chi Ooi [7] writes in its thesis so has much work been done to buildrobots based on the inverted pendulum principle. Work on both how to buildthe robot, but also how to explain its behavior mathematically.

For example a demonstration of how Lagrange’s method can be used fora simple inverted pendulum on a cart [8], and how Lagrange’s method canbe used to describe the pendulum physical properties [9, 10]. Thesis projectswhich discusses how to build a two-wheeled robot that can self-balance onlyby reading and understand data provided from the sensors and act on the twowheels according to the inverted pendulum model [7, 11–15].

Research papers that describes the use of the inverted pendulum princi-ple and how it gives an effective application. The papers addresses control ofunder-actuated systems like the inverted pendulum on a cart, mobile invertedpendulum which can be a Segway, like the one in Fig. 2.2, and gait patterngeneration for humanoid robots [16, 17]. A research paper from Swiss FederalInstitute of Technology Lausanne that presents JOE, which is a mobile invertedpendulum and a revolutionary prototype of a balancing robot [18]. Books andtutorials which describe the control theory for the inverted pendulum problemand the mathematics necessary for the calculation of the pendulums physicalproperties [6, 19, 20].

Page 29: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 2. BACKGROUND 7

Figure 2.2: Law enforcement Segway, offers added mobility in an urban envi-ronment [21]. This is an product based on the inverted pendulum principle.

Experiments have been done with all kind of hardware, for example, a tutorialof how to build a rotary inverted pendulum [22], a robot balancing an invertedpendulum have been done with Lego [23] and a couple of videos showing apendulum on a cart standing up straight [24–27].

It is currently important in the development of control systems to makeunstable systems safer. So when testing control system it is common to usethe classic nonlinear problem of the inverted pendulum which without controlsystem will become very unstable [28].

Acumen can run in real time and interact with the real world. In the work ofXu Fei, he shows that it is possible to get position readings from an smart-phoneto control a racket in Acumen. This is done over WLAN. This capability couldbe used to interact with the inverted pendulum prototype directly [29, 30].

2.4.1 Similar projects and products

A product developed for academic teaching is an Rotary Inverted PendulumTrainer on a NI ELVIS platform with LABVIEW™ software from National In-struments [31], shown in Fig. 2.3a. Unit price for a NI ELVIS platform withRotary Inverted Pendulum plug-in module and LabVIEW™ software will costat least 120 000 SEK where only the pendulum module costs around 20 000SEK.

Page 30: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 2. BACKGROUND 8

(a) RIP on NI ELVIS platform [31]. Thisproduct is commercially available, but veryexpensive.

(b) RIP on a servo motor [32].

Figure 2.3: Similar projects and products.

A project has been made with cheap hardware and self-manufactured parts [33]and describe how to proceed to build and analyze an inverted pendulum ona cart. No results are presented on whether the person succeeded to get thependulum to balance or not.

In [22] a guide is presented on how to build an Rotary Inverted Pendulum(RIP) with controller for approximately 2000 SEK.

An RIP on a servo motor, Fig. 2.3b, to demonstrate model-based design ofa cyber-physical system. The system is modeled using Simulink and Modelica[32]. Something similar would be possible to construct and model with Acumen.

2.5 Conclusion background

An inverted pendulum is a popular problem in control theory and much workhas been done in this subject both by amateurs and professionals. By examinethe material provided on the net further and with sufficient hardware it shouldbe possible to create an inverted pendulum with a controller.

The basic math on how to describe the physics of this kind of system isalso available and can be used to derive the equations needed for modeling inAcumen.

Page 31: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

3 Theory

This chapter provides a description of the theory needed to model an invertedpendulum in Acumen. Theory of different sensors and actuators which is thebasis for component selection. As the project includes transfer of data is theoryfor network communication also given here.

3.1 Modeling of Dynamic Systems

Dynamic systems are often used as a part of the modeling of mechatronic sys-tems. A dynamic system’s behavior depends on how it affected at an earliertime. To analyze a dynamic system will an mathematical model be required.The model can be linear or nonlinear, and both continuous and discrete [34].

3.1.1 Model of a Pendulum

In the Free body diagram of a pendulum, Fig. 3.1a, is it possible to see thependulum pivot point being accelerated u in one direction, that will give thependulum an acceleration that will cause the pendulum to swinging upward toan inverted position.

When it has reached its inverted position, it needs a controller that can keepit balanced, an application which requires this is the RIP in Fig. 3.1b.

In order to calculate the moment of inertia Jp of the pendulum can thegeneral expression (3.1) be used.

Jp =

∫r2 dm (3.1)

were r is the distance from the pivot point. For a simple pendulum can thesum of all elemental point masses dm multiplied by the square of the length begeneralized to

Jp = mp l2p. (3.2)

The resulting nonlinear equation of motion of the pendulum in Fig. 3.1a is givenby

Jp α(t) = mp g rp sinα(t) + mp u rp cos α(t) (3.3)

which will later be used to create an energy controller that can swing up thependulum [35].

9

Page 32: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 10

(a) Free body diagram of a regular pendu-lum.

(b) Rotary Inverted Pendulum - RIP.

Figure 3.1: Diagram of pendulums.

Differential equations is commonly used to describe dynamic systems. Onemethod to find a fitting equation for a system is by Lagrangian mechanics. Byusing the Lagrangian it is possible to set up the equation of motion by usingthe equation of kinetic energy together with the equation of potential energy.This form an equation over the dynamic system behavior and will later be usedto create a balance control that can balance the pendulum.

3.1.2 Euler-Lagrange’s equation

Figure 3.2: Inverted pendulum. By using Euler-Lagrange’s equation so can thissystem be described mathematically.

The Lagrangian L definition [36] in Equation 3.4 will be used to derive theequation of motion for an inverted pendulum.

L = T − V

=1

2mv2 −mg h.

(3.4)

In Equation 3.4 are T and V replaced with their respective definition of kineticand potential energy. Were v stands for velocity, m mass and h displacement in

Page 33: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 11

height. The potential energy of the pendulum, which is in its inverted position,shown in Fig. 3.2 is

V = mp g lp cosα. (3.5)

The pendulums velocity can be divided into a vector v representing the changein position. The pendulums position from Fig. 3.2 is presented in Equation 3.6.

x = lp sinα, y = lp cosα. (3.6)

In Equation 3.4 can v2 be rewritten to l2p α2 by using Pythagorean trigonometric

identity.

v2 = x2 + y2

= (lp α cosα)2 + (− lp α sinα)2

= l2p α2(sin2α+ cos2α)

= l2p α2.

(3.7)

The Lagrangian (3.4) becomes then

L =1

2mp l

2p α

2(sin2α+ cos2α)−mp g lp cosα

=1

2mp (l2p α

2)−mp g lp cosα.

(3.8)

The Euler-Lagrange equation is defined as

d

dt

∂L∂α

=∂L∂α

(3.9)

and the Lagrangian (3.8) can be substituted into Euler-Lagrange’s equation(3.9) by taking the time derivative and partial derivatives with respect to α andα.

∂L∂α

= mp g lp sinα,d

dt

∂L∂α

= mp l2p α

mp l2p α = mp g lp sinα ⇒ α =

g

lpsinα.

(3.10)

The same method can be used for an inverted pendulum on a cart.

x = p+ lp sinα, y = lp cosα,

x = p+ lp α cosα, y = −lp α sinα.(3.11)

Equation 3.11 differ from Equation 3.6 because it has a variable p which repre-senting a cart position. Using Equation 3.4 to get the kinetic energy T of thesystem gives

T =1

2mp (p2 + 2 lp p α cos α+ l2p α

2). (3.12)

Use the Lagrangian definition (3.4) with T and V (3.5) to get the Lagrangian

L = T − V =1

2mp (p2 + 2 lp p α cos α+ l2p α

2)−mp g lp cosα. (3.13)

Page 34: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 12

Using Equation 3.9 to take the time derivative and partial derivatives as inEquation 3.10 gives then

mp l2p α+mp lp p cosα = mp g lp sinα⇒ α =

g sinα− p cosα

lp. (3.14)

The conclusion of this is that a longer pendulum will accelerate slower and it istherefore possible to have a slower actuator. This result will be used when thebalance control system will be designed, see Section 3.2.1.

3.2 Control theory

Control theory about a PD-controller that can balance the pendulum, the energycontroller to swing it up and the hybrid control to create a system of bothfunctions is provided in this section.

3.2.1 Balance control

Alan V. Oppenheim, Professor of Engineering at MIT’s Department of ElectricalEngineering and Computer Science [20], have an open lecture about controltheory and feedback. This section sum up some of the points he gives. Themotion of an inverted pendulum was described in Section 3.1.2 and by usingEquation 3.14 which can be written as

lp α(t) = g sinα(t)− u(t) cosα(t). (3.15)

This system is not linear. By assuming that α(t) is close to zero a linear systemcan be achieved since

sinα(t) ' α(t), cosα(t) ' 1

⇒ lp α(t)− gα(t) = −u(t).(3.16)

Using the Laplace transform (α(t) ∼ A(s)) on Equation 3.16 gives

A(s) =1

lp s2 − g(−U(s)) (3.17)

where U(s) is the input to the system and

1

lp s2 − g= H(s) (3.18)

which is the plants transfer function. The poles in the s-plane are

s = ±√g

lp(3.19)

which gives an unstable system due to poles in the right plane, see Fig. 3.3.

Page 35: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 13

Figure 3.3: Poles in the s-plane. Since one pole is on the right half plane thesystem is unstable.

PD-Controller

Figure 3.4: Closed loop negative feedback control system.

To achieve a stable system can Proportional (P) plus Derivative (D) feedbackbe used. The carts acceleration u(t) is proportional to the pendulums angleα with a constant K1 and to the derivative of the pendulums angle α with aconstant K2.

u(t) = K1α(t) +K2 α(t). (3.20)

By choosing reasonable values of K1 and K2 a PD-controller can be imple-mented. The system function G(s) is given by the Laplace transform on u(t)

G(s) = U(s) = K1 +K2 s. (3.21)

The closed loop system function A(s) of the system shown in Fig. 3.4 is describedby

A(s) =H(s)

1 +G(s)H(s)(3.22)

and inserting Equation 3.18 and 3.21 in 3.22 gives the closed loop system func-tion

Page 36: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 14

A(s) =

1lp s2−g

1 + (k1 + k2 s) 1lp s2−g

=1

lp s2 − g + k1 + k2 s.

(3.23)

The system poles for Equation 3.23 can then be calculated to be

0 = s2 + s (K2/lp)− g/lp +K1/lp

⇒ s = −K2

2 lp±

√(K2

2 lp)2 − K1− g

lp.

(3.24)

With a positive K2 so that

K2

2 lp>

√(K2

2 lp)2 − K1− g

lp(3.25)

and poles in the left plane is achieved which implies a stable system. Now,Equation 3.15 is attributed to

lp α(t) = g sin (α(t))− (K1α(t) +K2 α(t)) cos (α(t)). (3.26)

In Fig. 3.5a is it presented how the poles move with increasing K1, Fig. 3.5bshows how the poles change with increasing K2. Figures are made in MATLAB.

(a) P-control. When increasing the P-partof the controller the poles moves along theimaginary axis.

(b) D-control. With only D-control thepole in the right never cross the imaginaryaxis. The system do not become stable.

Figure 3.5: Diagram of a P- and D-controller poles.

With only proportional control, a stable critical system can be achieved. Whenincreasing the P-part of the controller poles move along the imaginary axis.This means the system will oscillate and never settle. With only D-control thesystem cannot become stable. By using the P and D together can be a stablesystem be achieved, according to Fig. 3.6.

Page 37: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 15

Figure 3.6: PD-control: Used together the poles ends up in the left-half planeand a stable system is achieved.

If external disturbances is added to the system, Equation 3.22 will then become

A(s) =H(s)

1 +G(s)H(s)lpQ(s) (3.27)

which don’t change the poles of the system. Equation 3.26 becomes then withdisturbances

α(t) = g sin (α(t)) + lp q(t)− (K1α(t) +K2 α(t)) cos (α(t)). (3.28)

3.2.2 Energy based Swing-Up control

Katsuhisa Furuta and Karl J. Astrom [37] has a simple algorithm for swingingup a pendulum by assuming that the pendulum begins with zero velocity in itsnon inverted position. And if the pivot point is accelerated in one direction,the pendulum begins to swing upward toward an inverted position as describedin Section 3.1.1. By letting the pendulum swing symmetrical about its pivotpoint, this will pump sufficient energy to the pendulum so that it can swing upto an inverted position. An introduction of how to perform an energy controlwas given in [35]. The energy equations of the pendulum is given in Equation3.29 and 3.30 with the assumption that the pendulum starts in its non invertedposition as in Fig. 3.1a. The potential energy

V = mp g rp (1− cos α) (3.29)

and the kinetic energy

T =1

2Jp α

2. (3.30)

The total energy E of the pendulum become then

E = mp g rp (1 − cos α) +1

2Jp α

2 (3.31)

and differentiating gives the differential equation

Page 38: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 16

E = α Jp α2 + mp g rp sinα (3.32)

substituting Equation 3.3 into 3.32 to get the pendulums acceleration

E = mp u rp α sinα. (3.33)

By assuming that the arm acceleration is proportional to the motor drive cur-rent and voltage will it be easier to control the energy of the pendulum. Theproportional control law will increase the energy E towards the reference energyEr

u = (Er − E) α cos α. (3.34)

This equation is nonlinear and depend on the pendulums angle. It is this linearacceleration u that will be controlled in order to swing up the pendulum.

To use the energy control to swing up the pendulum, Equation 3.34 hasto be modified because the control signal have to be large in order to changethe energy fast and the control signal have to be saturated at the maximumacceleration for the arm.

u = sat(µ(Er − E) α cos α) (3.35)

where sat will saturate the control signal and µ will gain the control signal.

3.2.3 Hybrid control

In order to both balance the pendulum and swing it up so can the swing-upcontrol be combined with the balance control according to Fig. 3.7.

Figure 3.7: Hybrid control. Two controllers run in parallel, the switch choosewhich one to use. The switch is done at some discrete event. For an invertedpendulum system can this discrete event happen when the error is within acertain value.

Hybrid system is both continuous and discrete. The both closed loop controlleris continuous while the switching part is discrete. The switching part choosewhich controller to use. The balance controller is used in the interval wherethe angle is close to 0◦. When the pendulum is outside that range the systemswitch to the swing-up controller [35].

Page 39: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 17

3.3 Sensor

One part of a control system is a sensor that gives feedback to the controller. Inthis case a sensor that can measure the angle of the pendulum is needed. Sometechniques to measure rotary applications is going to be described.

3.3.1 Encoder

Incremental encoder

A common encoder is the optical encoder, which consist of a circular disk withopaque lines and patterns that creates a coded track mounted on a rotatingshaft, a light source and a photo detector (light sensor), see Fig. 3.8. When thedisc rotates, the photo sensor will detect the segments in the disc and usuallygenerate a square pulse signal output that can be used in a counter. Theresolution on the encoder depends of the number of segments per revolution[38].

Figure 3.8: Principle of an optical encoder [39]. A LED send light through adisc with holes. When the disk spin, signals is generated, in form of squarewaves. This signal can be used to sense speed.

A measure of the direction of rotation is not possible with only one kind of pulse.To do that two code tracks is used which is called quadrature outputs, becausethey are 90◦ out of phase with each other, and the direction is determined bythe phase relationship between the two channels. The position is calculated byadding up the number of pulses in a counter.

A disadvantage with incremental encoder are that they loses the count whenpower is turned off. When it should start over, the equipment must begin in ahome location to initialize the counter.

Absolute encoder

In applications were absolute position information is needed this type of encoderare used. The principle of an absolute encoder is similar to the incremental en-coder, the difference is how the segments are placed [40]. Absolute means thateach position is unique. It is composed by some channels that are combinedbinary, the number of channels will determine how high resolution it is possibleto get. The encoder will emit a combination of signals that together will deter-mine the actual position. Unlike the incremental encoder the absolute encoder

Page 40: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 18

is not needed to start in a fixed reference point because as soon as the voltageis turned on it will notify the control system the exact position.

Figure 3.9: Principle of an optical absolute encoder [41]. With several LED andseveral different signals generated, position and speed can be sensed.

As shown by Fig. 3.9, the disc consists of several channels that determine theposition. The upper first channel determines which half of the disc, the secondquarter, and the third eighth and so on. The segments are arranged so that thebinary code that is provided is a Gray code. It uses Gray code, because everychange is changing only one bit at a time and know exactly where it is, even ifit is between two different segments.

3.3.2 Potentiometer

The potentiometer is a form of controllable resistor, it has a shaft which ro-tates a slide connector along a resistive path. A potentiometer functioning as avoltage divider where the voltage gained from the potentiometer can be used todetermine the absolute position. There are single and multi-turn potentiometerand the difference between them is that the multi-turn has greater precision[42].

To use that analog signal in a MCU, there is first a need to convert the analogsignal to a digital signal and it is made with an Analog to Digital Converter(ADC). Sending in an electrical analog signal on the ADC and it outputs abinary value. The value that comes out is the rounded value of the originalsample as the number of bits is not unlimited [43].

3.3.3 Accelerometer and Gyro

By using these two components together, it is possible to measure the anglealong a single axis [44]. Earth’s gravity has a constant acceleration and whenan accelerometer is parallel to gravity so will the measured acceleration be 1Gand when it is perpendicular to gravity 0G. And by using Equation 3.36 whereA is the measured acceleration and g is the gravity of Earth the tilt angle α canbe calculated.

α = arcsinA

g. (3.36)

Page 41: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 19

There can be incorrect measurements of the angle if the accelerometer is usedon an object that is affected by other accelerations. To avoid that it is possibleto use a low pass filter to filter out high-frequency acceleration. By using a lowpass filter the measurement will take even longer time.

A gyroscope measures the angular velocity and by integrating the velocity itis possible to get the angle. When a gyro is in a stationary position, it will notdelivering a constant offset. This phenomenon is called drift. Upon integrationthe smallest offset can cause data to grow to infinity.

By using a complementary filter it will be possible to use the gyro data fora short time and use the accelerometer to correct drift over time. This way isone solution to rapidly provide an angle and a drift-free system.

Figure 3.10: Block diagram of a complementary filter. This is needed becausethe sensed angle from the gyro can drift over time. While the accelerometer isnoisy. By using them together they can complement each other.

Fig. 3.10 shows a block diagram of a complementary filter, it will combine thebest part from the two sensor signals. Inputs to this complementary filter isan angle from the accelerometer and an angular velocity from the gyro. Theangle from the accelerometer is low pass filtered to reduce influence from shortduration signals. The gyro data is integrated to give an angle and high passfiltered to remove long-term drift. These two filtered signals are then summedup together to give a single estimated angle [45].

3.4 Actuator

An actuator is a device used to control a mechanical system. The actuator iscontrolled by a signal and converts the signal into mechanical motion. In orderto balance the pendulum it will require some form of actuators that can performthe work to balance the pendulum.

3.4.1 DC motor

A basic DC motor [46], Fig. 3.11a, consists of an axle, armature, stator andcommutator. Brushed DC motors have also brushes. The stator contains of themotor case and coils or permanent magnets depending on type of motor. Theprinciple of a DC motor is to convert electrical energy to mechanical motion.

A brushed DC motor allows an electric current to flow through an armature,which is also called the rotor, placed in a magnetic field to produce a force which

Page 42: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 20

causes the rotor to rotate.Fleming’s left hand rule can be used to determine in which direction the

motor will rotate. Hold the left hand as Fig. 3.11b shows, let the index fingergo in the magnetic field direction and the middle finger in the direction of thecurrent so will the motor rotate in the direction of the thumb.

To create a magnetic field can either electromagnets or permanent magnetsbe used. The split ring commutator has two segments which closes the armaturecircuit, and the main task of the commutator is to reverse current so that therotor can continue to rotate in the same direction. The brushes drag againstthe commutator and feed it with electrical power. The most common DC mo-tor brushes is made of graphite, but in the past brass and copper was used.Nowadays, engineers work to make metal brushes more effective than graphitebrushes.

(a) Picture shows how a brushed DC motoris constructed [46].

(b) Fleming’s left hand rule [47].

Figure 3.11: Basic knowledge required to understand how a brushed DC motorworks and is built.

A brushless DC motor works the same way as the brushed. The difference is thatthey are differently constructed. In a brushed DC motor is the rotor composedof coils and the stator consists of magnets. In a brushless DC motor is this theopposite.

Figure 3.12: Diagram of a DC motor used for derive motor equations [32].

Page 43: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 21

La Inductance, motor winding Bm Motor, viscous frictionRa Resistance, motor winding τ Torque, actuatoria Current, motor winding τm Torque, motorvm Supply voltage n Gearbox ratioKb Motor back-emf β Actuator angleKt Motor torque βm Motor angle

Table 3.1: Definitions [32] of variables from Fig. 3.12.

Based on Fig. 3.12 so is the motor dynamics [32] set in Equation 3.37, definitionscan be seen in Table 3.1.

Laia +Raia = vm −Kbβm

τm = Ktia −Bmβm.(3.37)

3.4.2 Servo

Figure 3.13: Block diagram over a servo motor. A feedback loop with P-controlis implemented inside the servo. The goal is to control the position of the servo.Setpoint is given by PWM.

A servo is a motor which does not usually rotating full turns, instead it willmove into a position. To do this it will need a feedback loop with a sensor formeasuring the position of the shaft and something that can take decisions basedon the feedback. A small servo, Fig. 3.13, usually consists of an amplifier (K),a sensor, a DC motor (M) and a gearbox (G) to reduce the speed and increasethe torque.

In cheap servos is potentiometer the most common sensor used to measurethe position of the shaft. It also have an error signal generator that compares theset point with the actual value and move the servo until the error is eliminated.A servo is controlled by the width of the pulse sent to the servo, that meansthe servo is controlled by PWM [48]. As can be seen in Fig. 3.13 the amplifier

Page 44: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 22

(K) works as a P-controller. By adding a gearbox to the model of a DC motor,Equation 3.37, can a linear model [32] of a servo be obtained.

τ = τmn

β = βm/n.(3.38)

This equation can be used to model the dynamic behavior of the actuator.

3.5 Computer Networking

As stated in Section 1.1 the prototype should communicate over WLAN. Inorder to send and receive data over WLAN between a server and a client asocket is needed. There are two types of sockets, TCP and UDP, see Fig. 3.14.They differ in reliability, package delivery order, connection and method oftransmission.

Figure 3.14: Difference between TCP and UDP [49].

3.5.1 TCP

TCP is a connection-oriented protocol where a connection between two applica-tion programs is established and maintained until all segments have been sentand/or received. TCP explains how to break down the application data intosegments, how to send and receive data, flow control, retransmission of lost ordamaged segments and confirmation that the segment arrived.

TCP guarantees that all segments will arrive because it sends back to thesender an acknowledgment that it has received a segment, it will also ask thesender to resend the segment if it didn’t arrive. If any segments gets lost, TCPsorts the received segments so they end up in the order the segments weretransmitted in. Retransmission and that TCP have to sort segments after theyarrived can cause latency in TCP transmission [50].

Page 45: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 23

3.5.2 UDP

UDP is an alternative to TCP. Unlike TCP which sends data in segments, UDPsends single packets. Because UDP is a connection less protocol it does notcreate a connection between sender and receiver before a packet is transmitted.Therefore, the receiver cannot know if all packets were received or if they camein the right order. If the receiver receives a fragmented packet it’s discarded andthe receiver does not request the sender to resend the package. UDP assumesthat the application program takes care of delayed and lost packets [51].

Page 46: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 3. THEORY 24

Page 47: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

4 Method

This chapter will describe the approach and how the components was selected.Various components pros and cons will be critically analyzed against each other.Methods for testing against requirements will also be described.

With the background material as a base, a requirement specification has beendeveloped. The requirement specification describes the requirements of eachsubsystem, in order to have the goal deemed to be fulfilled. The requirementsare written so that they can’t be interpreted in several different ways. With arequirement specification, see Appendix A, it is possible to start working on aprototype. The prototype will be tested against the specifications.

4.1 Approach

The project will attempt to keep an idealized design process which is an itera-tive process. It has four steps that are repeated until a finished product [52].

The 4 steps of an iterative process.

• Modeling continuous systems (eg inverted pendulum).

• Simulating models in a modeling program (eg Acumen).

• Build a prototype.

• Comparing the model against the prototype.

4.2 Modeling in Acumen

Modeling makes it possible to find out new ideas and implementations beforethey become prototypes. This is desirable since prototypes can be expensive,especially if they contain errors.

Acumen is a program for modeling of dynamic systems, but there are severalother programs that can do that, for example, MATLAB, Mathematica andModelica. Since this project will favor the development of Acumen will then allmodeling be done in this program.

At Acumen will an RIP be modeled and it should be as similar to the realprototype as possible. To begin with, only the real and the virtual model willbe compared visually. It is only when the model is as close to the real, and it’s

25

Page 48: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 26

hard to tell the difference between them, it will be essential to collect sensordata to Acumen and compare them with data Acumen generate.

The Euler-Lagrange method can be used to model the dynamics of the sys-tem. These methods is presented in Section 3.1.2. Equation that are derivedwill be rewritten to fit Acumen.

lp α(t) = g sinα(t)− u(t) cosα(t). (4.1)

Equation 4.1 is the same as Equation 3.15 which was presented in Section 3.2.1and can be rewritten into Acumen, as in Program 1.

Program 1 Equation 4.1 rewritten to Acumen language.

angle’’ = (g * sin(angle) - pos’’ * cos(angle)) / len;

Acumen supports object-oriented modeling. Models can be encapsulated tomake more readable models. It is also possible to write Acumen simulationswithout this object-oriented manner. The choice to make Acumen simulationsthat consist with several models that interact with each other is motivated bythe need for further development. Changes or additions to the model will bemade and without an clear understandable setup this becomes difficult. InFig. 1.2 and Fig. 1.3 in Section 1.1 the idea how these models should interact ispresented. More details in how to model in Acumen is presented in tutorials byWalid Taha [53, 54]. In Program 2, basic set up for object-oriented modeling isshown.

Program 2 Modeling, Counter class example.

// Model of a counter

class Counter()

// Differential equation

// t’ = 1, with the initial condition t(0) = 0

private

t := 0; t’ := 1;

end

end

// Create the counter and waits until the simulation is done.

class Main(simulator)

private

mode := "init";

end

switch mode

case "init"

create Counter();

mode := "wait";

case "wait"

end

end

Page 49: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 27

4.2.1 Visual model

Models in Acumen can be presented visually as stated in Section 1.1. Thisis done by connecting variables from models with graphical presented objects.Program 3 is a visualization of a pendulum. A picture of the pendulum can beseen in Fig. 4.1.

Program 3 Visualization of a pendulum.

_3D =

[["Cylinder",

[0, pos + sin(angle), cos(angle)], // Center point

[0.05, 2], // Thickness, length

yellow, // Color

[-angle + pi/2, 0, 0]]]; // Tilt angle

Figure 4.1: Visualization of the pendulum in Acumen.

Depending on how the variables angle & pos change so will this cause the visualmodel to move.

4.2.2 Modeled characteristics of the real system

The model of the inverted pendulum will have certain characteristics in orderto mimic the reality. The characteristics are

• Quantization - Some sensors can’t detect small changes.

• Discretization - Control algorithms is often implemented as task runningat a predefined period [55]. This can be modeled in Acumen using avariable as timer.

Quantization is modeled as an if-statement.

if x > x_sample + sensitivity_of_sensor

x_sample := x_sample + sensitivity_of_sensor

Page 50: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 28

While discretization is modeled with timers.

if timer_value >= task_period

timer_value := 0 // Reset timer

// Do periodic task

4.3 Communication

A controller shall be developed in Acumen, and it should send control signals tothe prototype and the model, as presented in Fig. 1.5 and Fig. 4.2. Efforts aregoing to be made to add functionality to Acumen that enable communicationwith the real world. This will be implemented with programming in Scala andor Java, using sockets and WLAN. Scala is the language Acumen is designedand programmed in, but it is possible to use Java classes in Scala.

The communication will be implemented as a server added to Acumen andit will communicate with a client on the prototype, Fig. 4.2. A client will beimplemented on a Raspberry Pi and it will communicate with the server inAcumen through WLAN.

Figure 4.2: Server should be added to Acumen. Efforts is going to be made inorder to control of the prototype from Acumen.

According to Section 3.5, UDP is the best choice for real streaming of sensordata. But since no connection at the protocol level is created between thePC and the prototype, the server can not know who is sending the data. Adesirable feature is that it should be possible to see if there is a connectionbetween the server and client, and then TCP is the best choice because UDPdoes not connect directly to the receiver like TCP does. The biggest reason thatTCP will be selected is that the idea that in the future, be able to communicatewith multiple clients. With UDP, it is not possible to know who sent the datafor anyone can send to the recipient’s UDP port. To be able to see who sent thedata, TCP, has been prioritized before the higher transmission rate of UDP.

4.4 Construction of prototype

A study was made between the inverted pendulum on a cart and a RIP. The pro-totype that was chosen to be built is the RIP, because it consists of a minimumnumber of mechanical parts. Generally, fewer parts that are used, the cheaperprototype. This makes it also easier to meet the requirement of an inexpensiveprototype. The prototype will mainly consist of a servo, a potentiometer (tomeasure the pendulums angle) and a MCU. Justification for the choice of thesecomponents will be made later in this chapter.

Page 51: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 29

These components will be assembled to a prototype and to assemble these parts,a 3D printer will be used to create mechanical parts. A 3D printer will be usedsince it can produce parts for prototypes quickly and easily to a low cost. Toprint these parts, the first thing is to design them in a CAD program. Knowledgeis available in the CAD program SolidWorks and will therefore be used.

Figure 4.3: Design, A MCU interact with a potentiometer and servo in order tokeep the pendulum upright. Sensor data is sent over WLAN.

Fig. 4.3 shows how the prototype is supposed to work. The servo should keep thependulum upright and the potentiometer measures the pendulum’s angle. Themeasured angle is sent to the MCU and out of the MCU comes control signalsto the servo. The MCU will also handle the communication with Acumen.

4.4.1 Design

All parts will be mounted on a plate that it is possible to drill in. The MCUcomes with pre-drilled screw holes, so it will only be to drill the holes in theplate and screw it on. A servo bracket is a part that will be made in a 3Dprinter. A bracket is needed since there is a risk that the servo creates largeforces that it will loosen. The servo brackets job is to ensure that the servo isfasten properly.

In order for the servo to be able to keep the pendulum upright will one armout from the servo be printed out by the 3D printer. At the tip of the arm willa potentiometer be mounted. The arm will be designed to be mounted on theservo and have a potentiometer mounted at the front. A bracket to mount thependulum on the potentiometer shaft will also be printed. The pendulum willbe a rounded rod.

4.5 Actuation

There are essentially two types of actuators that have been studied in detail.A DC motor and a servo motor. The two factors that have determined thechoice are the speed and torque. The speed is needed for the system to rapidlycompensate the pendulum tilt angle. The torque is required for the motor tobe capable of moving the arm where the pendulum is mounted on. Both types

Page 52: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 30

of motors can cope with the job because there are projects that have used themsuccessfully, see Chapter 2.

A DC motor with gear can hold both high speed and have a high torque, butthen requires higher power. A DC motor also requires additional electronics inthe form of an H-bridge to change the direction.

Figure 4.4: Hitec HS-422, DC-servo [56].

Servos consists of a DC motor with gearbox and has built-in electronics, accord-ing to Section 3.4.2. A servo has the limitation that it has a limited operatingrange. It will therefore be a risk that the servo can reach its end position be-cause no control of arm position is made. The pendulum will fall when the servoreaches its end position.

One crucial factor is the cost, a servo is cheaper than a DC motor withgearbox and associated electronics. A servo was selected with the justificationthat the pendulum should not raise so large excursions so that the servo reachesits end position. The selected servo is Hitec HS-422, Fig. 4.4.

4.6 Automatic Control

Different method to implement an closed-loop controller exist. One commoncontroller is the PD (Proportional & Derivative) controller. It has its back-ground in analog control but is often used in digital systems, together withADC. To make the algorithms work well the computer system must sample thecontinuous signal measured from the plant accurate so a discrete representationof the continuous signal can be obtained. The sampling is an drawback for thePD controller implemented in a computer. To recreate the signal in a computermust the sampling be done at a frequency that is at least twice so big as thesignals, according to Nyquist–Shannon sampling theorem [57].

Some other control methods that came up during the background investigation.

• Fuzzy logic control.

• P-, PI-, PD- and PID-control.

• Energy based control.

• Hybrid control.

Page 53: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 31

• Sliding mode control.

• Feedforward control.

• LQR.

Since the project group already have experience about PD control and the surveyof the field, Section 2.4 and Chapter 3, shows that this method have been usedsuccessfully before. It was chosen to get implemented. Energy based controland hybrid control was also chosen to be implemented in order to swing-up thependulum and combine swing-up with balance control. Because they are themost common methods, according to Chapter 2.

4.7 Microcontrollers

A MCU will be needed to read the sensor data, send control signals to theactuator and manage communication with a server that will be available on aPC. Comparisons between different MCU will be done here, and ends with anexplanation of why Raspberry Pi was selected.

4.7.1 SAM3U4E

SAM3U4E, Fig. 4.5, is a chip which contains of an ARM cortex-M3 reducedinstruction set computing processor. Maximum speed of operation is 96 MHzfor the Cortex-M3. The chip also includes peripherals such as timer counters,real-time timer, PWM, 12-bits ADC. The timer counters are equipped withquadrature decoder logic. SAM3U is very well suited or USB applications [58].Platforms with the SAM3U4E microprocessor is the SAM3U-EK and ArduinoDUE [59].

Figure 4.5: SAM3U-EK [60].

Benefits

• Many I/O.

• Good real time capabilities.

• Quadrature decoder logic.

• High resolution on the ADC.

Page 54: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 32

Disadvantages

• No WLAN module is included.

• Expensive.

4.7.2 Arduino UNO

Arduino UNO, Fig. 4.6, is a development platform with an 8 bit ATmega328processor. It has 14 digital I/O pins (of which 6 are PWM outputs), 6 analoginputs with an ADC of 10 bits. It has a clock speed of 16 MHz. Arduino UNOalso supports SPI communication. Programming can be done in the Arduinosoftware IDE (Integrated Development Environment) but also in other thirdparty programs like Visual Studio. The programming is done in C/C++ [61].

Figure 4.6: Arduino UNO [62].

Benefits

• Cheap.

• Good real time capabilities.

• Easy to connect hardware.

• Big community with a lot of material on the web.

• Several different libraries is provided for program development.

Disadvantages

• No WLAN shield is included.

• Low resolution on the ADC.

Page 55: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 33

4.7.3 Raspberry Pi

Raspberry Pi, Fig. 4.7, is a mini computer with Broadcom BCM2835, a System-on-Chip, which consists of a ARM1176JZFS processor running at 700MHz andit has 512 MB RAM. It runs on the operating system Raspbian which is a versionof Linux. The newest model Raspberry Pi Model B+ has 4 USB ports and 40GPIO pins that can be programmed to become an input or output. GPIO pinsare the physical link between the real world and the Raspberry Pi. RaspberryPi is provided with a SPI bus for communication with peripherals. To writeprograms on a Raspberry Pi is Python used as the programming language [63].

Figure 4.7: Raspberry Pi Model B+ [64].

Benefits

• Cheap.

• Several different libraries is provided for program development.

Disadvantages

• No WLAN module is included.

• No built-in ADC.

• Lot of different features were some of them will not be relevant to thisproject.

From this survey wanted the customer that the Raspberry Pi should be usedbecause, together with the WLAN module, was the cheapest.

4.8 Measuring technology

A sensor is needed to measure the angle of the pendulum according to thevertical axis. Bourns 3590S-6-103L potentiometer was chosen to be the sensorthat detect the pendulums angle α. It can turn 3600◦ and have a relative lowfriction in comparison with other potentiometers. Here is options presented andweighed against each other.

Page 56: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 34

4.8.1 Gyro and accelerometer

Something that has been taken in mind when selecting materials has been howto reduce the amount of materials, how to optimize production and how to getso long component life as possible. The fact that accelerometer and gyro werenot selected is because it would entail more components. It can also be difficultto mount these two sensors, they suit better in a self-balancing robot than ona pendulum. An encoder or potentiometer with axle is desirable because thenthere is something to attach a pendulum on.

4.8.2 Hengstler rotary encoder

RI32-O/1000ER.11KB from Hengstler is an incremental encoder with a resolu-tion of 1000 pulses per revolution [65] provided from the university. HengstlerRI32-O/1000ER.11KB is presented in Fig. 4.8.

The reason why not an encoder, rotary or absolute was chosen is because oftheir high price. A typically absolute encoder cost a lot while a decent rotaryencoder cost more than 1000 Swedish kronor. A cost that don’t fit in the budget.

Figure 4.8: Hengstler RI32-O/1000ER.11KB. Rotary encoder, that generatepulses on 3 channels.

Quadrature decoder logic

A preferred feature that the development board should have if using incrementalencoder is quadrature decoder logic for decoding the pulses from the encoder.The quadrature decoder will take the incoming pulses and count them and storethe value in a register in the MCU [66]. This register will automatically countup when the encoder is moved in one direction and count down when moves inthe other. Details of how this technology is implemented is presented on theweb [67].

4.8.3 Bourns potentiometer

The sensor that was finally chosen was a potentiometer. Encoders in the sameprice as the chosen one has more torque than the potentiometer. The chosenpotentiometer 3590S-6-103L from Bourns can turn 3600◦ which is 10 full turns[68]. The sensor is shown in Fig. 4.9. It has a torque on 1.1 Ncm [68] compared

Page 57: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 35

to the Hengstler encoder which has ≤ 0.05 Ncm [65]. Since the potentiometeris a mechanical construction where the shaft slides along a resistive path, it willeventually wear out, and the potentiometer must be replaced.

Figure 4.9: Bourns 3590S-6-103L [69]. Potentiometer with 10 turns and rela-tively low friction.

ADC for selected potentiometer

To use the analog signal from the potentiometer, which is used as a sensor todetect the pendulum’s angle, in a MCU an ADC has to be done to get a digitalsignal that can be used by the MCU.

Following equations will give how many degrees the potentiometer shaft mustturn for the ADC to detect a change by one. To control the pendulums angleis a hypothesis made that the need for an ADC with around 1◦ resolution tobe able to measure the angle of the pendulum is enough. If the hypothesis waswrong, an ADC with higher resolution will be chosen. Equation 4.2 gives howmany volts it goes to 1◦.

5

3600◦= 1, 388889 mV/deg. (4.2)

According to Equation 4.3 will a 10 bits ADC detect the interval 0◦ to 3,5◦ as0 and 3,5◦ to 7◦ as 1. This will not be enough to control the pendulum.

5V

1024= 4, 882813 mV/step,

3600◦

1024= 3, 515625 deg/step. (4.3)

In order to improve the resolution have an ADC with a resolution on 12-16 bits(4096-65536 different values) been considered.

5V

4096= 1, 220703 mV/step,

3600◦

4096= 0, 87890625 deg/step. (4.4)

5V

65536= 76, 293945 µV/step,

3600◦

65536= 0, 054931 deg/step. (4.5)

With a better ADC, it will be possible to detect smaller changes on the pen-dulum’s angle. The ADC that was selected is ADS1286 [70], because accordingto Equation 4.4 can this have sufficiently high resolution, and it may sample ata frequency of 20kHz. To use it with a MCU so supports this ADC SPI and

Page 58: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 36

SSI. SPI communication will be used between the ADC and the MCU. SPI hasa master device. In this case the MCU, and a slave unit which in this case isthe ADC. The master selects the slave device it wants to read by inserting alow signal on the slave SS (Slave Select) and then read the value of the MISO(Master Input, Slave Output) channel [71].

4.9 Testing

A good model is one that act much like in reality. Everything about it shouldalso be derived from physics. With other words, everything in the model shouldbe possible to explain, i.e. no ”magic” constants that just makes the modelwork.

The Acumen model provides data and so does the real model. Comparingthese two sets of values conclusions can be drawn about the quality of the model.

The virtual and the real model should ultimately have the same character-istics in all considered ways. Comparisons will be made visual to see how thesystem behave.

4.9.1 Quality tests

Quality test will be done on the prototype to see if it meets the requirements.

Test of Sensor system

To test the sensor system, software has to be implemented which can handlethis. It should be possible to receive sensor data into a MCU. This will be testedby running the program that is implemented on the MCU and tilt the pendulumin different directions and with different large slope. Reasonable values shouldbe obtained. This means that there must be a value in the ADC’s operatingrange. The value will increase if the pendulum is tilted in one direction anddecreases in the other.

To make it feasible to test if it is possible to retrieve values into a PC mustthere be a wireless connection between the PC and the prototype. Then twotests need to be performed. One is to see if there is a connection between thePC and the prototype and the other has the same test method that was usedwhen the sensor system was tested on the MCU. To test whether there is awireless connection between the PC and the prototype will there be a server onthe PC and a client on the prototype. The server is started up and letting theclient to connect to it. The test is met if the client can send a message to theserver and receive a response.

Test of Control system

To test if there is a control system the sensor system must function flawlesslyand a software program has to be implemented to handle this. The MCU shoulddemonstrate closed loop control. This will be tested by running the programthat is implemented on the MCU and tilt the pendulum in different directionsand with different large slope. The servo should then go in the direction of thependulum leaning towards to in order to prevent it from falling. It should have

Page 59: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 37

a higher speed if the slope is large and the lower speed if there is a slight slopeof the pendulum.

To test whether it is possible to have the control system on a PC must therebe a wireless connection between the PC and the prototype. Then two testshave to be performed, one is to see if there is a connection between the PC andthe prototype, the same test method that was used to test whether there was awireless connection between the PC and prototype when sensor data was sentto a PC will be used again, and the other has the same test method used whenthe control system was tested on the MCU. If the test is met, can the serverbe integrated with Acumen and the same test is performed again to see if thecontrol system can be used from Acumen.

The pendulum should be able to swing up to an inverted position. The testwill see if the servo is able to swing up the pendulum. In this test will theswing-up program run, and the arm will run back and forth until the pendulumhas accumulated enough energy for it to be able to swing up. This test willrun without a hybrid control and, therefore, the pendulum will fall when it hasreached an inverted position.

4.10 Experiment and analysis of data

4.10.1 Network latency

Sending data over WLAN takes time and data can be lost in the process. Whensending sensor data delays are going to be observed. This motivates exper-imentation to examine this behavior. This is done by sending data betweenRaspberry Pi and PC and observe the time it takes to ping1 a message withdifferent size.

4.10.2 Noise level

It is of interest to know how much noise there is in the circuit but also howit affects the performance. When there are components that often switch inelectrical circuits, eg motors, so can they create short-term changes in the powersupply, so-called transients. This will be measured to determine how big theyare. During the starting moment for a motor it is common to voltage drops,this will also be measured.

4.10.3 Disturbance rejection

To see if the system can cope with disturbances at 3◦, the values retrieved bythe sensor system are used to draw graphs. By studying the graph it will bepossible to see when the pendulum subjected to disturbances, how big they wereand how the system handled them.

Testing method

Set up the pendulum system. Configure desired set point, pendulum standsstraight. Introduce disturbance by touching the pendulum. Optional, to log

1This is done by using PsPing, By Mark Russinovich, with TCP ping and UDP ping.

Page 60: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 38

data on the Raspberry Pi and/or PC.

4.10.4 Simulation of control program

Increasing task period

Control programs is often implemented in a MCU. It is common to have a taskrunning periodically and from sensor data calculate settings on actuators. If thecontrolled process change much between the execution of two tasks, the systemcan be unstable. This experiments examine how the simulation in Acumen ofthe inverted pendulum and controller reacts when increasing the period at whichthe control law is applied.

Testing method

A controller is found for the ideal system. The period at which the controllaw is applied increases between simulations. From the experiment observe howsettling time, overshoot change and when the system become unstable.

angle = 10◦. = 10 ∗ ( π180 ) = pi/18,

1. Start inverted pendulum model A in Appendix B.

2. Set initial conditions.

3. Run simulation, observe settling time and overshoot.

4. Increase task period, repeat step 3.

4.10.5 Validation of Acumen models

The project name implies verification. A model is an imitation of reality. Im-itation implies that they are not identical. Acumen models will be comparedagainst the prototype and these experiments try to observe how much differencethere is. In this experiment observation on how the model behaves is made whenusing the same parameters as reality. The developed prototype may have someweaknesses, friction in the potentiometer and low resolution of the ADC, howthese parameters change the behavior of the system will be examined.

Testing method

The parameters are set to match reality. Observations of simulations will bemade.

Examining how the models behave when the resolution of the ADC changes.

1. Start the inverted pendulum model B in Appendix B.

2. Set initial conditions.

3. Run simulation, observe settling time and overshoot.

4. Increase sensitivity on sensor, repeat step 3.

Page 61: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 39

Examining how the models behave when the friction of the sensor changes.

1. Start the inverted pendulum model B in Appendix B.

2. Set initial conditions.

3. Run simulation, observe settling time and overshoot.

4. Increase friction, repeat step 3.

Page 62: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 4. METHOD 40

Page 63: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

5 Results

This chapter will describe the results. Beginning with the models in Acumen.Then the physical prototype, its design, BOM and control program. Under Net-work latency result is presented from experiments regarding communication overWLAN. Results from simulations in Acumen is then presented and experimentswith the prototype.

5.1 Model

One goal presented in Section 1.1 is to develop an inverted pendulum controllerin Acumen. Using the equations derived from Section 3.2 the controller can beimplemented. The basic set-up of the models is shown in Fig. 5.1. The simula-tion includes a mediator that control the flow of information in the simulation.The pendulum model, models the plant and visualize it. The controller getsinput from the plant and sets an output that affect the plant.

Figure 5.1: Set-up of Acumen simulation. Controller contains behavior of con-troller and control program. Pendulum contains the plants behavior and visu-alize it. Mediator control the flow of information between the models.

Set-up is seen Fig. 5.1 and it models a feedback loop in Acumen. The mediatoris shown in Program 4.

41

Page 64: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 42

Program 4 Mediator

class Mediator(angle)

private

// Creates the pendulum

pend := create Pendulum(angle);

// Create controller, angle, task period: 20 ms, res

ctrl := create Controller(angle,0.02,0.1*(pi/180),12,2);

end

// Set controllers angle. To create sample

ctrl.angle= pend.angle;

// Set the input for the plant

pend.pos’’ = ctrl.acceleration;

end

The Acumen models is shown in detail in Appendix B. The controller containsthe discretization and quantizations process from Section 4.2.2. The controllaw is calculated and the acceleration is set periodically. Under quantizationsin Program 5, if the angle change more than the resolution of the sensor thesensed data get updated.

Page 65: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 43

Program 5 Controller Acumen non-ideal

// Discretization

if t >= period_time

// reset timer

t :=0;

// Apply control law

acceleration :=

k1 * angle_sample

+ k2 * angle_dt;

// Quantization

if angle > angle_sample + resolution

// Save old value, needed for calculate the derivative: angle_dt

angle_old := angle_sample;

// Create the modeled sample

angle_sample := angle_sample + resolution;

// Calculate the modeled derivate

angle_dt := (angle_sample - angle_old)/period_time

else if angle < angle_sample - resolution

// Same as above, for decreasing.

angle_old := angle_sample;

angle_sample := angle_sample - resolution;

angle_dt := (angle_sample - angle_old)/period_time

end

end

end

end

In Program 6 is the implementation of an virtual representation of a RIP anda picture of this is shown in Fig. 5.2. A description of how this relates to thesimulation was given in Section 4.2.1.

Page 66: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 44

Program 6 Graphical representation of a RIP in Acumen.

// Graphical representation of an Rotary Inverted Pendulum (RIP)

// that goes in a circle.

_3D =

// Pendulum

[["Cylinder",[1.15*sin(pos),1.15*cos(pos),0.25],[0.05,3],

white,[angle+(pi/2),0,((pi/2)-pos)]],

// Bracket, pendulum

["Box",[1.05*sin(pos),1.05*cos(pos),0.1],[0.5,0.15,0.15],

yellow,[angle+(pi/2),0,((pi/2)-pos)]],

// Potentiometer

["Box",[sin(pos),cos(pos),-0.05],[0.501,0.501,0.6],

blue,[0,0,((pi/2)-pos)]],

// Bracket, arm

["Box",[0,0,-0.25],[2,0.5,0.2],

white,[0,0,(pi/2-pos)]],

// Servo

["Box",[-0.5,0,-1],[1,2,1],

black,[0,0,pi/2]],

// Gear bracket

["Cylinder",[0,0,-0.5],[0.2,0.5],

white,[pi/2,0,0]]

];

Page 67: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 45

Figure 5.2: Visual representation of a RIP. The blue box, pendulum and shafttravel in a circular motion.

5.2 Prototype

The prototype that has been built is a RIP. Arm, servo bracket and a bracketfor mounting the pendulum to the potentiometer shaft were manufactured inthe 3D printer.

The arm consists of two parts. One part is designed to mount the poten-tiometer and the other to mount the arm on the servo. The arm is long becauseit will be possible to place the prototype at the edge of the table in order tobe able to swing up the pendulum. Fig. 5.3a shows how the potentiometer ismounted on the arm bracket. The servo is mounted in a self-made bracket, seeFig. 5.3b.

Page 68: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 46

(a) A self-made arm where the potentiome-ter is mounted.

(b) The servo mounted in self-madebracket. In the background, the pictureshows a glimpse of the two MCU.

Figure 5.3: 3D-printed parts.

For this prototype has two MCU been used, an Arduino UNO and a RaspberryPi, due to the ADC was delivered late. The Arduino UNO is used because ithas a built-in ADC. The entire prototype where the arm is mounted on theservo and pendulum mounted on the potentiometer without breadboard wherethe prototype is connected electrically can be seen in Fig. 5.4.

Figure 5.4: Prototype, Raspberry Pi, Arduino UNO, Servo, and Potentiometerfastened on a board.

Page 69: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 47

5.2.1 Power requirements and Noise

In order to control the inverted pendulum is it necessary to have the servomotor HS422 connected to an external power supply. Because none of the MCUis capable of giving enough current to run the servo. Arduino UNO can givemaximum 40 mA per I/O pin [61], Raspberry Pi can give 16 mA [72], the servowill need at least 150 mA [73] without any load. For external power is a powersupply unit used. Wiring diagram can be seen in Appendix C.

There was a minor problem with a faulty connection between the RaspberryPi and the router. This was thought to only be due to poor reception, but itturned out to be due to the Raspberry Pi cannot operate a keyboard, mouseand WLAN adapter simultaneously. This was resolved by having the keyboardand mouse driven from the screen.

(a) Without capacitor. (b) With capacitor.

Figure 5.5: PWM-signal.

Fig. 5.5a shows a PWM pulse to the servo during driving. As it is possible tosee arises a transient at each step change. Fig. 5.5b shows a PWM pulse witha decoupling capacitor (150 nF) between the PWM output and ground. Thetransients are nearly removed.

(a) Without capacitor. (b) With capacitor.

Figure 5.6: Measured angle from potentiometer.

Fig. 5.6a shows the output of the potentiometer without a pendulum attachedthat can change the value. Ideally, when the signal is completely straight. Thesechanges result from the execution of the servo. In Fig. 5.6b is a capacitor (220uF) connected between the power supply VCC and GND. The result is notperfect but this is solved in software through a filter.

The filter that is implemented in the Arduino UNO is a moving average filterand it helps to minimize the risk that the controller reacts to inconsistent eventsat the input. Program 7 shows this filter.

Page 70: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 48

Program 7 Weighted moving average filter implemented in Arduino.

PotValue = (0.7 * PotValue + 0.3 * oldPotValue) + 0.5;

5.2.2 Control system

A hybrid control have not been realized, but a balance controls exist and success-ful tests have been made to swing up the pendulum. The control program wasimplemented on Arduino UNO. Full control program can be seen in AppendixD.

Balance control

Visual observations, on how the system reacts when the pendulum is about tofall, the system tries to stop the pendulum from falling, and it works until theservo reaches its end position and stops, causing the pendulum to fall.

Swing-up experiment

A swing up model has not been implemented in Acumen, this is just the resultof a test to see if it is possible to swing up the pendulum or not. A simple swingup program for the pendulum has been written. The test has been done witha long and a short pendulum and shown that it is possible to swing up a short(10 cm) pendulum but not a long (30 cm). An additional weight on top of thependulum makes it easier to swing it up. Program 8 swings the pendulum backand forth. This is just a program to demonstrate that it is possible to swing upthe pendulum, it is not a control program with feedback.

Program 8 Swing-up program.

// Move servo to position 180 with speed 145 and wait for pendulum

// to gain energy

servo.write(180,145,true);

delay(16);

// Move servo to position 20 with speed 145 and wait for pendulum

// to gain energy

servo.write(20,145,true);

delay(16);

5.2.3 BOM

One goal presented in Section 1.1 was to make the prototype as cheap as possible,so that more prototypes could be built. In Table 5.1, is it possible to see allused materials and where to buy it for a minimum price. Please note that theprices apply 4/12/2014, and do not include shipping.

Page 71: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 49

Item Description Retailer Set Total price1214453 ADC Farnell Components AB 1 86,60715-4081 Arduino UNO RS Components AB 1 197,2965-246-49 Capacitor 150 nF Elfa Distrelec 1 3,7867-040-42 Capacitor 220 uF Elfa Distrelec 1 2,67DFR0058 Potentiometer DFRobot 1 44,001

811-1284 Raspberry Pi B+ RS Components AB 1 230,26ROB-11884 Servo SparkFun 1 75,002

11-992-3 Threaded rod Clas Ohlson 1 12,00814 WiFi Stick Adafruit 1 97,003

- - Total : 748,6

Table 5.1: BOM, all prices in Swedish kronor.

Accessories needed to use the prototype but that is not included in the total costis breadboard, clutch cables, power supply and other things on the prototypethat was self made.

5.3 Communication

A server was created to have a communication between PC and the prototype.The server was written in Java. The server was also added to Acumen and it ispossible to run the server in parallel with the other program by choosing it froma menu alternative. But when the server waits for a client to connect, Acumenlock itself until a client connects. The Raspberry Pi handle the communicationwith Acumen. On the Raspberry Pi was a client implemented, and it waswritten in Python.

5.3.1 Network Latency

The latency in communication between the Raspberry Pi and PC have beenmeasured. The measurements have been made for both TCP and UDP. Theaim is to determine the transfer rate. One wish was to make it possible forAcumen to self check this out, but this has not been met.

1Rounded from 5.90 US Dollar according to current exchange rate2Rounded from 9.95 US Dollar according to current exchange rate3Rounded from 11.95 US Dollar according to current exchange rate

Page 72: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 50

Figure 5.7: Network latency. Messages is sent and acknowledgments is sentback, the time between these two events is logged.

Fig. 5.7 show the result from a 250 iterations long ping test with 32 bytes of data.

Ping statistics for TCP:Sent = 250, Received = 250, Lost = 0 (0% loss),Minimum = 2.04ms, Maximum = 52.36ms,Mean = 4.2962ms, Variance = 65.2342.

Ping statistics for UDP:Sent = 250, Received = 249, Lost = 1 (0% loss),Minimum = 1.98ms, Maximum = 77.52ms,Mean = 5.1070ms, Variance = 123.2433.

On average, it takes longer time to send a packet with UDP. For UDP is it alsohigher distribution in the time it takes to get a acknowledgment.

Page 73: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 51

Figure 5.8: Latency, sending larger data.

Fig. 5.8 show the result from a 250 iterations long ping test with 8 kilobytes ofdata.

Ping statistics for TCP:Sent = 250, Received = 250, Lost = 0 (0% loss),Minimum = 8.65ms, Maximum = 127.92ms,Mean = 16.3443 ms, Variance = 164.4888.

Ping statistics for UDP:Sent = 250, Received = 250, Lost = 0 (0% loss),Minimum = 12.58ms, Maximum = 102.13ms,Mean = 20.4586 ms, Variance = 173.3617.

The results show that TCP is still more reliable than UDP. As expected, thetransmission rate is higher for larger data.

Page 74: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 52

Figure 5.9: This test is done when the network is heavily used.

In this test, is more packets sent simultaneously. Fig. 5.9 show the result froma 250 iterations long ping test with 32 bytes of data.

Ping statistics for TCP:Sent = 250, Received = 248, Lost = 2 (0% loss),Minimum = 1.93ms, Maximum = 291.91ms,Mean = 56.1448ms, Variance = 7515.8.

Ping statistics for UDP:Sent = 250, Received = 248, Lost = 2 (0% loss),Minimum = 1.92ms, Maximum = 287.47msMean = 83.9782ms, Variance = 9879.3.

5.4 Simulations

A series of experiments were introduced in Section 4.10.4 and here are the resultof the experiment presented. The experiments is using Acumen to simulate aninverted pendulum with a controller.

The test of increased task period shows what happens when the control lawis applied less often.

Increased resolution is based on the actual prototype and this experimentshows how the behavior could change when switching to a better ADC.

Increased friction shows how the behavior is changing when friction is addedto the model.

5.4.1 Increased task period

This experiment shows what happens to the ideal inverted pendulum modelwhen the period in which the periodic control task is executed increases.

Page 75: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 53

Pendulum:len 0.5Controller:p 22d 4resolution 3.5*(pi/180)Task period variesInitial angle 10◦

Table 5.2: Initial condition for simulation. Resolution from the prototype.

In this experiment is the resolution from the sensor the same. The values thatwas set in Acumen is presented in Table 5.2. These values produced the resultin Table 5.3.

Task period Overshoot Settling time

0 2.9 % 590 ms10 ms 2.9 % 590 ms20 ms 3.2 % 590 ms40 ms 3.7 % 580 ms60 ms 4.6 % 570 ms80 ms 5.7 % 880 ms100 ms 7.4 % 910 ms150 ms 14.9 % 910 ms200 ms 31.6 % 1200 ms250 ms 94.6 % 1710 ms300 ms Marginally stable350 ms Unstable

Table 5.3: The time increases from each simulation. Se table, from 0 to 350 ms.Increased instability can be observed.

The period time can be compared with the transmission rate in network latency,Section 5.3.1. Note that this is a model of an otherwise ideal system.

Page 76: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 54

(a) Simulation, ideal with a period set to 0.Overshoot: 2.9% and settling time: 590ms.

(b) Simulation, period set to 10ms. Typicalcharacteristics of graphs in this experiment.

Figure 5.10: Simulation of increased period.

Fig. 5.10a shows an ideal model where the control law is applied all the time,continuously. While in Fig. 5.10b computations and control signals is only setat certain times which are the case if they were performed by a scheduled task,as Program 9.

Program 9 Scheduled task.

t :=0; t’:=1; // Timer, t increases

end

// Discretization

if t >= period_time

// reset timer

t :=0;

// apply control law

acceleration :=

k1 * angle_sample

+ k2 * angle_dt;

end

In Program 9 does a timer count up, and after some time a control signal is sentand the timer is reset. In Fig. 5.10 it is of interest to note the increased angulardisplacement between Fig. 5.10a and Fig. 5.10b.

5.4.2 Increased resolution of the ADC

This simulation gives a hint of how performance changes in pace with increasedresolution of the ADC.

Page 77: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 55

Pendulum:len 0.5Controller:p 12d 2Task period 0.02resolution variesInitial angle 5◦

Table 5.4: Initial condition for simulation. p, d and task period is taken fromthe control program of the prototype.

In Table 5.4 comes the most values from the physical prototype. The interestingthing about this experiment is that it can give an idea of how the performancecould be altered by using a better ADC.

Resolution Overshoot Amplitude

4◦ 65.3 % unstable after 5 s3.5◦ 73.2 % 18.22◦

2◦ 21.5 % 7.5◦

1◦ 22.6 % 5◦

0.5◦ 16.0 % 2◦

0.3◦ 4.4 % 1.52◦

0.1◦ 21.4 % 0.4◦

Table 5.5: Simulation, increased resolution.

(a) Simulation, resolution = 3.5◦. (b) Simulation, resolution = 0.35◦.

Figure 5.11: Simulation of increased resolution of the sensor.

Fig. 5.11a is a simulation of the physical prototype, but where friction is ne-glected. In Fig. 5.11b is the same system simulated but with the resolutionincreased to 0.35◦ instead of 3.5◦ as in Fig. 5.11a.

Page 78: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 56

5.4.3 Increased friction

In the mathematical models used to generate models, it assuming no friction.This experiment indicates the effect of friction and how it changes the behaviorof the system. Settings on the controller is from the physical system.

Pendulum:len 0.5Controller:p 12d 2period time 0.02resolution 3.5*(pi/180)friction variesInitial angle 5◦

Table 5.6: Initial condition for simulation. p, d and period time is taken fromthe control program of the prototype.

Friction Overshoot Amplitude

none 73.2 % 18.22◦

0.09 71 % 13.5◦

0.18 63 % 14.2◦

0.5 63 % 13.4◦

0.9 56 % 11.9◦

1.1 54 % 9.9◦

Table 5.7: Simulation, friction. Change in overshoot and amplitude.

In Table 5.7 it can be noted that the system oscillates lesser with increasedfriction. This is also presented in Fig. 5.12.

(a) Simulation, friction = 0.09 (b) Simulation, friction = 1.1

Figure 5.12: Simulation of increased friction in the potentiometer.

Page 79: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 57

5.5 Control system sturdiness

(a) Experiment plotted, from start to end.The pendulum is in upright position at 0◦.Downward position at ± 180◦.

(b) Zoomed in view from Fig. 5.13a. Hereis the pendulum subjected to manual dis-turbance.

(c) Close up on sensor values fromFig. 5.13b. Resolution is 3.515625◦.

Figure 5.13: Graphs showing the system’s robustness.

Experimentation with the pendulum. Fig. 5.13 show sensor data from the con-troller. Small disturbances on 1-3◦ get rejected. Bigger disturbances or theactuator reach its end position result in falling. Video of the test procedure ispresented on http://sea-calf-bot.webnode.se/. Fig. 5.13a shows the wholeexperiment. The pendulum gets set upright, is subjected to a series of pokesbetween 20s and 45s. The experiment is carried out again between 65s and 100s.Note how the data seem to have a discrete behavior, 0◦ or 3.5◦ in Fig. 5.13c.

Page 80: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 5. RESULTS 58

Page 81: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

6 Discussion

This chapter will discuss the arisen results and what could be done differently.

6.1 Summary of goals

The aim of the project was to compare a virtual model of an inverted pendulumwith a physical prototype. The idea behind this is to examine how well Acumenis suited as a tool when implementing a cyber-physical system.

To achieve this, one goal was set to develop a mathematical model of aninverted pendulum and simulate it in Acumen. One other goal was set toconstruct a prototype of an inverted pendulum. This prototype is vital sincewithout it, comparisons with reality could not take place. The prototype shouldalso be as inexpensive as possible so it is possible to build more of them. Withsimulated models in Acumen and a physical prototype, the main goal of theproject was to demonstrate the close connection between them.

6.1.1 Theory

The most important knowledge gap that needed filling was how to model aninverted pendulum and a control system. A very accurate study of the Euler-Lagrange’s equation was made early in the project to develop a model of thesystem. This model was for an inverted pendulum on a cart, but was laterchanged to work on a RIP. These two models have been simulated in Acumen.

6.2 Analysis and Interpretation

6.2.1 Virtual models

Many virtual models have been created in order to demonstrate the prototype’sdifferent behavior. Some are presented in Appendix B. The results presentedin the form of graphs show that the pendulum model and reality share manycharacteristics. But differences exist.

For example is that the model does not take into account the position of thearm, which was also a limitation. To control the position of the arm does twocontrollers have to work together. The model of the potentiometer friction isnot completely accurate.

Compare the prototype with other inverted pendulums, eg Jiyues pendulum[22], and it shares the same behavior as the pendulum oscillates also around itspivot point.

59

Page 82: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 6. DISCUSSION 60

6.2.2 Network latency

A network connection was created between Acumen and the prototype but thedata did not arrive in real time because the data got buffered by the router. Thisphenomenon is called bufferbloat and it occurs when a network link becomesoverloaded, resulting in that the packages end up in a long queue in the router’sbuffer.

6.2.3 Noise level

Without capacitors, the servo will have a shaking behavior that makes it impos-sible to control the pendulum. The capacitors help to remove transients whichmake the servo shakes when it trying to keep its position. They also help withkeeping the voltage level to the potentiometer fairly constant. The filter servesto get a so good estimate of the pendulum angle as possible.

6.2.4 Disturbance

The disturbance the system can handle is quite small, only a few degrees. Onereason for this is the low resolution of the ADC. In Fig. 5.13c is it showed thatthe only change greater than 3.5◦ is detected. The friction in the potentiometeris helping the pendulum to keep itself upright.

Increased sampling time

In Table 5.3 is data from the simulation presented. It is demonstrated thatwith increased time between the events, where acceleration is set. The systemresponds more forcefully and eventually becoming unstable.

The plots, Fig. 5.10a and Fig. 5.10b, shows the ideal model with a continuousbehavior with the control law applied at a period of 10 ms. The most noticeabledifference between Fig. 5.10a and Fig. 5.10b is that the angle increases in thebeginning of Fig. 5.10b. This is caused by the speed of the pendulum hasgained during the time that the controller does not know exactly what hashappened. First after 10 ms does the simulated actuator attempts to stabilizethe pendulum.

This result is interesting together with the network latency experiment. Be-cause even in an ideal environment that Acumen provide it is not feasible tohave a control loop which was presented in Fig. 1.5, Section 1.1. This due tolatency and unreliability of the WLAN.

Resolution

The virtual model does not fall. Decreasing the resolution generally leads tobetter performance. At 3.5◦ resolution the pendulum model oscillates with anamplitude of 18.22◦ which would be a dangerous behavior on an real prototype.The conclusion of this experiment is that with a better resolution it is possibleto get a system that handles disturbances better, thus to obtain a more robustsystem.

Page 83: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 6. DISCUSSION 61

Friction

With sampling time and quantizations the pendulum will oscillate. With frictionadded to the model the oscillation is reduced.

6.2.5 Prototype

The prototype that has been built is a RIP and the total cost of the prototype isaround 750 SEK, presented in Section 5.2.3. Using only one MCU, the require-ment for an inexpensive prototype for 700 SEK (∼ $100) would be achieved,but the prototype meets the requirement of an inexpensive prototype. The pro-totype is cheaper than the BOM Jiyue Hes [22] presents on his website. Theresult in Section 5.2 together with the study of similar products in Section 2.4.1makes it possible to think that it could be possible to make a product out ofthe prototype. This is because the problem of stabilizing an inverted pendulumis used in university courses. But the products available to buy are expensiveso it is positive if there is a low cost alternative.

Suggestions on how to make a more viable product follows, the prototypecan be done even cheaper by just using one MCU. The use of two MCU has itspros and cons. Raspberry Pi has almost all the conditions as needed. However,it lacks ADC. The ordered ADC was not delivered on time which forced theuse of Arduino UNO. In mass production would the cost be even lower, sincediscount is received if larger quantities is purchased.

The extra amount of money from just using one MCU can be used to buya better potentiometer with lower friction. The selected potentiometer hashigh friction which reduce the strains from the different forces pendulum issubjected to. Since the tests have been done with an ADC with low resolution,the pendulum has had time to fall much (3.5◦ <) before the control systemreacts, that’s why the servo needs a higher speed to keep the pendulum upright.

The method used to prevent the pendulum from falling is that before theservo reaches its end position trying to get the pendulum to fall in the otherdirection. Nonetheless, since the ADC had too low resolution, the pendulumhad to fall much in the other direction before the system responded. This meantthat the servo went so far that it did not have the time to go back and stop thependulum from falling.

6.3 What would be done differently today

The things that should have been done differently if the project would be donetoday with all knowledge are to have a ”complete working prototype” early inthe project instead of start planning for a final product. They can be a help toconfirm that the project follows the plan and meets the customer’s expectations,and if it does not, it is possible to adjust the plan to what suits both partiesbest. This is important if the customer does not know exactly how the productshould be designed.

The biggest reason that the project didn’t go as planned is that no completeworking prototype was built at all. Mostly because the ”easy” parts wasn’tsettled early in the project. Motor control and data acquisition was completedearly, however, the network connection between prototype and PC should have

Page 84: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 6. DISCUSSION 62

been implemented much earlier in the project. Setting up clearer requirementsand limitations from the outset, above all, how much the prototype should cost.

Page 85: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

7 Conclusion

This chapter summarizes the results of the project and gives a hint of futuredevelopment.

The results show that a physical prototype of an inverted pendulum has beenbuilt. The prototype could be built cheaper if a better ADC (12 bits) had beendelivered on time. Since then, only one MCU would be used and it would alsobe possible to measure the pendulum angle with a better resolution.

The result shows a physical prototype of an inverted pendulum. It costsaround 750 Swedish crowns. By removing one MCU there are opportunities tomake it cheaper.

Despite the low resolution (10 bits) of the used ADC the results show thatthe pendulum can cope with a disruption of at least 3.5◦ before it falls.

Another goal was to send sensor data to Acumen and use it in real time. It ispossible to send and receive data. Nevertheless, the data do not arrive reliablywith real time constraints because the router place data in buffer queues. Thisis in order to not overload the network. Tests have proven that the data sentvia WLAN can arrive after a substantial time. Having the control system inAcumen has not been possible since the communication is not quick enough.

From theory was equations derived for describing the inverted pendulum andits controller. By using these equations, were the virtual models implementedin Acumen. The virtual prototype enables fast prototyping where differentcharacteristics can be made apparent.

Comparisons between the model and reality were made. This concludedthat there were differences. One reason for this could be the case that themodel of the inverted pendulum was derived from theory before the prototypewas developed. Models based on system identification could prove to be moreprecise.

The project has shown that it is possible to build an inverted pendulum witha controller at a minimal cost. The performance is acceptable regarding the lowcost components that the system was constructed with. It is possible to thinkthat the virtual and physical prototypes could be used as educational tools, forgraduate and undergraduate students.

7.1 Experiences

Much have been learned in this project. The challenge to go from all theoryto model and implementing the control system has been interesting. Especially

63

Page 86: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 7. CONCLUSION 64

in the way it all is connected, from forces to differential equations, transferfunctions to sensor, actuators and computer system.

The breath of the project have been substantial. Also including things withlittle knowledge.

Experiences gained in working in project will be valuable in future work.This of course includes lessons made by mistakes.

Writing this kind of report have also been new and challenging. But it issomething that no longer is as frightening as before.

7.2 Future work

The first step in order to achieve the university’s main objective with a pingpong robot was to build an inverted pendulum. The next step may be a doubleinverted pendulum where an inverted pendulum balancing a pendulum. Whenthere is a good inverted pendulum model, it is possible to go over and use theprinciple for a racket and a ping-pong ball. Always keep the rack under theping-pong ball is one form of an inverted pendulum. Eventually, it is possibleto have a ping pong playing robot, Fig. 7.1.

Figure 7.1: TOPIO 3.0, a ping pong playing robot [74].

An inverted pendulum may also be interesting for people who are interested incontrol theory. To develop the prototype into a product in which it is possibleto use Acumen to control it, so has it been a powerful tool for testing controlsystems. Universities and individuals may be interested in acquiring these fortraining purposes. A certification is needed to be able to sell it as a product.

7.2.1 Certification

In order to sell the prototype on the market it needs some product certifications.To sell the product in Europe, it needs to meet the requirements for CE-marking

Page 87: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 7. CONCLUSION 65

and the EMC-directive. The R&TTE directive must also be met since it has abuilt-in radio communication, in the form of Wi-Fi. FCC for selling it in theUSA.

At least a closer look at safety standard IEC 61010-1, and EMC standardEN 61326-1 needs to be done. In addition, the product must comply with theRoHS directive restricting the use of certain hazardous substances in electricaland electronic equipment.

Risks that may arise during the certification are error in the product thatis detected at the end of the development process and this can be very costly ifthe product is rejected. This could mean that the product must be redesigned.The consequence is that the product coming to market late, lost sales and costof redesign and re testing of the product [75–77].

Page 88: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

CHAPTER 7. CONCLUSION 66

Page 89: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

Bibliography

[1] Acumen homepage. Available: http://www.acumen-language.org/p/development.html. [Cited 2014-12-11].

[2] Hybrid Systems: Modeling, Analysis, and Control Stanford University.Available: http://web.stanford.edu/class/aa278a/. [Cited 2014-12-11].

[3] Jobs in the simulation field. Available: https://modelica.org/jobs.[Cited 2014-12-11].

[4] Edward A. Lee. January 23, 2008. Cyber Physical Systems: DesignChallenges. Available: http://ecs.utdallas.edu/news-events/events/deanspong/documents/Challenges%20of%20Cyberphysical%20syste

ms.pdf. [Cited 2015-01-14].

[5] P. R. Kumar. Challenges of Cyberphysical systems. Available:http://ecs.utdallas.edu/news-events/events/deanspong/documents/Challenges%20of%20Cyberphysical%20systems.pdf. [Cited2015-01-14].

[6] Control Tutorials for MATLAB and Simulink (CTMS): Inverted Pen-dulum: System Modeling. Available: http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling.[Cited 2015-01-18].

[7] Rich Chi Ooi (2003). Balancing a Two-Wheeled Autonomous Robot. TheUniversity of Western Australia. Available: http://robotics.ee.uwa.edu.au/theses/2003-Balance-Ooi.pdf. [Cited 2014-09-17].

[8] Randall Paige (2003). Controlled Lagrangians and the Inverted Pendulumon a Cart. Available: http://www.cds.caltech.edu/~marsden/wiki/uploads/projects/geomech/Randall2003.pdf. [Cited 2014-09-17].

[9] C. Aguilar-Ibanez, O. Octavio Gutierrez F., and H. Sossa A. (2008).Controlled Lagrangian approach to the stabilization of the inverted pen-dulum system. Available: http://www.ejournal.unam.mx/rmf/no544/RMF005400411.pdf. [Cited 2014-09-17].

[10] Regents of the University of Michigan (1996). Example: Modeling an In-verted Pendulum. Available: http://www.ee.usyd.edu.au/tutorials onl

ine/matlab/examples/pend/invpen.html. [Cited 2014-09-17].

67

Page 90: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BIBLIOGRAPHY 68

[11] Maia R. Bageant (2011). Balancing a Two-Wheeled Segway Robot.Available: http://dspace.mit.edu/bitstream/handle/1721.1/69500/775672333.pdf. [Cited 2014-09-17].

[12] Victor Vicente Abreu (2009). Balance Bot. Available: http://reposi

torio.uma.pt/bitstream/10400.13/59/1/MestradoVictorAbreu.pdf.[Cited 2014-09-17].

[13] Peltier, Michael D. (2012). Trajectory Control of a Two-Wheeled Robot.Available: http://digitalcommons.uri.edu/cgi/viewcontent.cgi?article=1113&context=theses. [Cited 2014-09-17].

[14] Andrew K. Stimac (1999). Standup and Stabilization of the Inverted Pen-dulum. Available: http://web.mit.edu/2.737/www/extra files/andre

w.pdf. [Cited 2014-09-17].

[15] Bjorn Carlsson, Per Orback (2009). Mobile inverted pendulum, Con-trol of an unstable process using open source real-time operating sys-tem. Available: http://publications.lib.chalmers.se/records/fulltext/99385.pdf. [Cited 2014-09-17].

[16] Olfa Boubaker. The inverted Pendulum: A fundamental Benchmarkin Control Theory and Robotics. National Institute of Applied Sci-ences and Technology. Available: http://arxiv.org/ftp/arxiv/papers/1405/1405.3094.pdf. [Cited 2014-09-17].

[17] Khalil Sultan (2003). Inverted Pendulum Analysis, Design and Implemen-tation. Available: http://www.engr.usask.ca/classes/EE/480/Inverted%20Pendulum.pdf. [Cited 2014-09-17].

[18] Felix Grasser, Aldo D’Arrigo, Silvio Colombi, Member, IEEE, and AlfredC. Rufer, Senior Member, IEEE. JOE: A Mobile, Inverted Pendulum.IEEE TRANSACTIONS ON INDUSTRIAL ELECTRONICS, VOL. 49,NO. 1, FEBRUARY 2002 Available: http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=982254. [Cited 2014-09-17].

[19] Karl Johan Astrom, Richard M. Murray (2012). Feedback Systems 2ndedition p, 37, 69, 100, 108, 118, 121, 128, 130, 276, 337 Avail-able: http://www.cds.caltech.edu/~murray/books/AM05/pdf/am08-complete 30Aug11.pdf. [Cited 2014-09-17].

[20] Alan V. Oppenheim. MIT OpenCourseWare. Lecture 26, Feedback Ex-ample: The Inverted Pendulum, MIT RES.6.007 Signals and Systems,Spring 2011. Available: https://www.youtube.com/watch?v=D3bblng-Kcc. [Cited 2014-09-17].

[21] Segway. Available: http://www.segway.co.nz/patrol/. [Cited 2015-01-15].

[22] Jiyue He (2012). Rotary Inverted Pendulum. Available: http://dasl.mem.drexel.edu/~jiyueHe/rotary inverted pendulum/ind. [Cited 2014-09-17].

Page 91: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BIBLIOGRAPHY 69

[23] Ken Dye. Inverted Pendulum Balancing. Available: http://www.cs.hmc.edu/~dodds/projects/RobS03/Mapping/oldindex.html. [Cited 2014-09-17].

[24] Full inverted pendulum on a cart example. Available: https://www.youtube.com/watch?v=Bxo0 A5Dp3w. [Cited 2014-09-17].

[25] Inverted pendulum. Available: https://www.youtube.com/watch?v=MWJHcI7UcuE. [Cited 2014-09-17].

[26] Control of Inverted Pendulum with Servo Pneumatics. Available: https://www.youtube.com/watch?v=a4c7AwHFkT8. [Cited 2014-09-17].

[27] Mouratis Kiriakos. Development and control of an inverted pendu-lum system. Available: https://www.youtube.com/watch?v=855O9x0Pgf0. [Cited 2014-09-17].

[28] Peter Bergstrom, Karim Gaber, Anders Meurk (2009). Den inverteradependeln med oscillerande fastpunkt. Available: http://www.mech.kth.se/~hanno/InvPendelOscKandExJobb.pdf. [Cited 2014-09-17].

[29] Xu Fei (2014). Video of WLAN application, smart-phone + Acu-men. Available: https://drive.google.com/file/d/0B4WcIfA5sS5lNElYbkU2N0pmaUE/edit. [Cited 2014-09-17].

[30] Xu Fei (2014). Code and documentation for WLAN application, smart-phone + Acumen. Available: https://bitbucket.org/xufeiwaei/acumen-dev. [Cited 2014-09-17].

[31] Quanser QNET Rotary Inverted Pendulum Add-on Board. Available:http://sine.ni.com/nips/cds/view/p/lang/sv/nid/210350. [Cited2014-12-05].

[32] Cyber Physical Systems Design Group at University of California, Irvine.Rotary Inverted Pendulum Example. Available: http://cps.ics.uci.edu/research/rotary-inverted-pendulum-example/. [Cited 2014-12-11].

[33] Andy’s Log (2010). Inverted Pendulum Project. Available: https://an

dreweib.wordpress.com/inverted-pendulum-project/. [Cited 2014-12-05].

[34] Dynamic Systems Modeling. Available: http://www.anylogic.com/anylogic/help/index.jsp?topic=/com.xj.anylogic.help/html/wwanylogic/Dynamic Systems.html. [Cited 2015-01-08].

[35] Courseware NI ELVIS. Available: http://www.ni.com/white-paper/52080/en/. [Cited 2014-12-11].

[36] Derivation of Equations of Motion for Inverted Pendulum Problem.Available: http://www.cas.mcmaster.ca/~qiao/courses/cs4xo3/presentations/InvPend.pdf. [Cited 2014-10-08].

[37] K.J. Astrom, K. Furuta. Swinging up a pendulum by energy control. Vol-ume 36, Issue 2, February 2000, Pages 287–295. Available: http://www.sciencedirect.com/science/article/pii/S0005109899001405. [Cited2015-01-11].

Page 92: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BIBLIOGRAPHY 70

[38] Encoder Measurements: How-To Guide. Available: http://www.ni.com/white-paper/7109/en/. [Cited 2014-10-08].

[39] Rotary Encoder. Available: http://todbot.com/blog/wp-content/uploads/2008/06/180px-basic-rotary.jpg. [Cited 2014-10-09].

[40] Eltra (2005). Absolute Encoders. Available: http://www.esco.be/Download/Documents/Eltra-EN-Absolute 20060418.pdf. [Cited 2014-10-09].

[41] Absolute Encoder Simplified Structure. Available: http://www.tamagawa-seiki.com/english/encoder/rotary02.jpg. [Cited 2014-10-09].

[42] Martin Norden (2002). Elektroniklara: Del 2 - Potentiometer. Avail-able: http://www.nordichardware.se/Guider/elektronikl-del-2/Potentiometer.html#content. [Cited 2014-10-11].

[43] Analog to Digital Converters (A/Ds). Available: http://www.facstaff.bucknell.edu/mastascu/eLessonsHTML/Interfaces/ConvAD.html.[Cited 2014-12-02].

[44] Tutorial by Cytron (2012). Measuring Tilt Angle with Gyro and Ac-celerometer. Available: http://tutorial.cytron.com.my/2012/01/10/measuring-tilt-angle-with-gyro-and-accelerometer/comment-pag

e-1/. [Cited 2014-10-11].

[45] Complementary Filter. Available: http://www.instructables.com/id/PCB-Quadrotor-Brushless/step15/IMU-Part-2-Complementary-Fil

ter/. [Cited 2014-10-14].

[46] Basic construction of a DC motor. Available: http://electrical4u.com/electrical/wp-content/uploads/2013/03/dc-motor-parts.jpg.[Cited 2015-01-06].

[47] Fleming’s left hand rule. Available: http://electrical4u.com/electrical/wp-content/uploads/2013/03/fleming-left-hand-rule-2.png.[Cited 2015-01-06].

[48] Frances Reed. How Servo Motors Work. Available: http://www.jameco.com/jameco/workshop/howitworks/how-servo-motors-work.html.[Cited 2014-12-02].

[49] TCP vs UDP. Available: http://blog.ub.ac.id/hnachan/files/2010/11/UDP-Connections.jpg. [Cited 2015-01-15].

[50] TCP (Transmission Control Protocol) . Available: http://searchnetw

orking.techtarget.com/definition/TCP. [Cited 2015-01-14].

[51] UDP (User Datagram Protocol) . Available: http://searchsoa.techtarget.com/definition/UDP. [Cited 2015-01-14].

[52] Walid Taha. Acumen tutorial. Available: http://www.acumen-language.org/p/tutorials.html. [Cited 2015-01-14].

[53] Walid Taha (2009). Acumen tutorial, Rice University. Available: http:

//www.cs.rice.edu/~taha/Acumen/modeling-with-acumen.pdf. [Cited2015-01-14].

Page 93: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BIBLIOGRAPHY 71

[54] Walid Taha et al. Acumen tutorial. Available: https://docs.google.com/document/d/1Y-whR2zkMNKoLj6YkX4gqwA8sbZ WzdVAnJfdMzBcWo/edi

t?hl=en&authkey=CMvmtuwH. [Cited 2015-01-14].

[55] Herman Kopetz (2011). Real-Time Systems. [Cited 2015-01-14].

[56] Hitec HS-422. Available: http://www.dfrobot.com/wiki/images/3/31/Hitec HS422 Servo.jpg. [Cited 2015-01-14].

[57] Nyquist–Shannon sampling theorem. Available: https://www.princeton.edu/~achaney/tmve/wiki100k/docs/Nyquist%E2%80%93Shannon sam

pling theorem.html. [Cited 2015-01-14].

[58] SAM3U4E, datasheet. Available: http://www.digchip.com/datasheets/parts/datasheet/054/SAM3U4E.php. [Cited 2015-01-13].

[59] SAM3X, datasheet. Available: http://www.atmel.com/images/doc11057s.pdf. [Cited 2015-01-13].

[60] SAM3U-EK. Available: http://www.digikey.com/product-highlights/en/sam3uek-development-board/50476. [Cited 2015-01-14].

[61] Arduino UNO. Available: http://arduino.cc/en/Main/arduinoBoardUno. [Cited 2014-12-11].

[62] Arduino UNO. Available: https://cdn.sparkfun.com//assets/parts/6/3/4/3/11021b-00.jpg. [Cited 2015-01-14].

[63] ModMyPi. Available: https://www.modmypi.com/raspberry-pi-model-b-plus. [Cited 2015-01-14].

[64] Raspberry Pi Model B+. Available: www.element14.com/community/servlet/JiveServlet/showImage/38-16291-199414/BplusLES.jpg. [Cited2015-01-14].

[65] Hengstler encoder, datasheet. Available: http://www.hengstler.de/gfx/file/shop/encoder/RI32/Datasheet RI32 en.pdf. [Cited 2015-01-13].

[66] Using Mechanical Rotary Encoders. Available: //www.mcmanis.com/chuck/robotics/projects/lab-x3/quadratrak.html. [Cited 2015-01-13].

[67] Quadrature Decoder - VHDL. Available: http://www.fpga4fun.com/QuadratureDecoder.html. [Cited 2015-01-13].

[68] Bourns potentiometer, datasheet. Available: http://www.farnell.com/datasheets/1695332.pdf. [Cited 2015-01-13].

[69] Bourns 3590S-6-103L. Available: http://proesi.com.br/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/p/

o/potenciometro-multvoltas 11.jpg. [Cited 2014-12-12].

[70] ADS1286, ADC, datasheet. Available: http://www.ti.com/lit/ds/symlink/ads1286.pdf. [Cited 2015-01-13].

[71] SPI. Available: http://arduino.cc/en/Reference/SPI. [Cited 2014-12-12].

Page 94: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

BIBLIOGRAPHY 72

[72] Raspberry Pi FAQ. Available: http://www.raspberrypi.org/help/faqs/#powerReqs. [Cited 2014-12-11].

[73] Hitec HS-422 Datasheet. Available: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/hs422-31422S.pdf. [Cited 2014-12-11].

[74] Ping Pong Robot. Available: https://ninjaradio.files.wordpress.com/2012/04/pingpongrobo.jpg. [Cited 2015-01-11].

[75] Intertek Academy. IEC/EN 61010-1; Elektrisk utrustning for matning,styrning och laboratorieandamal. Available: http://www.intertek.se/intertek-academy/iec-en-61010-1/. [Cited 2015-01-11].

[76] European Commission. Electromagnetic compatibility (EMC) . Available:http://ec.europa.eu/enterprise/policies/european-standards/harmonised-standards/electromagnetic-compatibility/index en.htm. [Cited 2015-01-11].

[77] European Commission. Radio and telecommunications terminal equipment(R&TTE) . Available: http://ec.europa.eu/enterprise/sectors/rtte/index en.htm. [Cited 2015-01-11].

Page 95: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

A Requirement specification

Motor control

Added Updated Requirement Priority1

20/9-14 Original Control motor speed, from PC. 120/9-14 Original Control motor speed, from

MCU.1

20/9-14 Original Control motor speed, from Acu-men.

1

Comments: A motor control was implemented in the MCU, the motor was alsocontrolled by computer through a Java program. To achieve motor control fromAcumen the Java program must be added to Acumen.

Modeling

To achieve our goals we need to use the modeling language Acumen. To modelthe inverted pendulum we need to understand the physics in this system.

Added Updated Requirement Priority20/9-14 Original Basic physics knowledge. 120/9-14 Original Develop accurate mathematical

model.1

20/9-14 Original Visualize the mathematicalmodel in Acumen.

1

20/9-14 Original Develop inverted pendulum con-troller in Acumen.

1

27/10-14 Original Wi-Fi connection between Acu-men and pendulum

1

Comments: Basic physics knowledge can be found in chapter 3. Mathematicalmodel and basic controller in Acumen, done. Model can be visualized in Acu-men. Work has been done on a more advanced controller, that models jitter. Aserver was implemented in Acumen that communicates with the pendulum.

11- High, 2- Moderate, 3- Low

73

Page 96: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX A. REQUIREMENT SPECIFICATION 74

Sensor system

To read sensor data we need to understand how to establish a connection be-tween sensor and computer. The different technologies must be compared soour choice can be motivated.

Added Updated Requirement Priority20/9-14 29/10-14 Transfer potentiometer values

into a computer.1

20/9-14 29/10-14 Transfer potentiometer valuesinto a MCU.

1

20/9-14 Original Use data in Acumen. 1

Comments: Potentiometer values has been read into the Arduino UNO. Thedata has been transferred to the computer byWLAN. The data has not beenused in Acumen but it is possible to receive data in Acumen.

The construction

Added Updated Requirement Priority20/9-14 Original Evaluate solutions, Furuta pen-

dulum and construction slidingon cart.

1

20/9-14 Original Choose a system. 120/9-14 Original Control system should handle in-

terference on at least 3◦.1

Comments: An inverted pendulum on a cart that slides on a railis easier tomodel as it moves along a linear path while Furuta pendulum moves in a circularmotion. But it is possible to build an Furuta pendulum to a lower cost. Testsshow that it is possible for the control system to handle small interference onat least 3,5◦.

Page 97: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX A. REQUIREMENT SPECIFICATION 75

Specification from customer

Added Updated Requirement27/10-14 Original Pendulum base structure27/10-14 Original Selection and acquisition of pendulum rod material27/10-14 Original Selection and installation of pendulum actuator27/10-14 Original Selection and installation of pendulum sensor27/10-14 Original Familiarize yourself with the embedded controller platform.

The platform for the first prototype will be Raspberry Pi.This has Wi-Fi built in, which is very helpful. But youhave to know Java and Linux. It also does not have a lotof on-board I/O for debugging. But you can connect it toa monitor.

27/10-14 Original Connection and testing of actuator to embedded controllerplatform

27/10-14 Original Connection and testing of sensor to embedded controllerplatform

27/10-14 Original Designing and implementing a TEST embedded controllerand running it on the platform to demonstrate closed loopcontrol. Note: This is NOT the final controller, this isjust a self-test for the hardware. You may also extend itto support some calibration (for example, for your relative-angle sensor).

27/10-14 Original Connect the embedded platform to Acumen through Wi-Fi. For this task, the key thing is to make it possible toconfirm on Acumen that there is a live connection to anembedded platform, and to display the network ID of thatplatform. In this task, it might be good to also display inAcumen how much the network latency are. Note: This isalso a kind of self-test for the connection from the softwareto the hardware, and it will make your life much easier whenyou are debugging other aspects of the software/hardwareconnection.

27/10-14 Original Read sensors into Acumen during a simulation, and con-firm by inspection that these readings are reasonable (forexample, try rotating the pendulum by 2*pi and confirmthat the Acumen reading is consistent with that).

27/10-14 Original Send actuation sensor from Acumen during a simulation.Here, you might want to ramp up force on the actuatorfollowing an obvious pattern to confirm that it is doingwhat you expect it to do.

27/10-14 Original Data to show that the physical pendulum simulation is con-sistent with the completely virtual pendulum simulation

27/10-14 Original A bill of materials (BOM) along with cost

Page 98: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX A. REQUIREMENT SPECIFICATION 76

Page 99: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

B Virtual models in Acumen

Model A

/**

* Virtual prototype of Inverted pendulum controller

*

* Authour:

* Viktor Frimodig

* Martin Gustavsson

*

* 2014-10-25: Created

* 2014-10-30: Comments added

*/

class Pendulum(theta)

private

angle :=theta;angle’ := 0; angle’’ := 0;

len := 0.5;

x:=0;

g := 9.8;

pos:=0;pos’:=0;pos’’:=-0;

K1:=50; K2:=5;

_3D := []

end

_3D =

[["Cylinder",[0,pos+sin(angle),cos(angle)],[0.05,2],yellow,[-angle+pi/2,0,0]],

["Sphere",[0,pos+2*sin(angle),2*cos(angle)],0.15,yellow,[0,0,0]],

["Box",[0,pos,-0.25],[0.5,0.5,0.5],red,[0,0,0]]];

angle’’=

(g * sin(angle)

+ len * x

- pos’’

* cos(angle)

)/len;// - angle’;

end

class Controller(theta, period, resolution, p, d)

private

angle := theta; angle’:= 0;

77

Page 100: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX B. VIRTUAL MODELS IN ACUMEN 78

angle_sample := theta; angle_dt := 0;

k1 := p;

k2 := d;

acceleration :=0;

t :=0;t’:=1;

end

if t >=period

t :=0;

acceleration := k1 * angle + k2 * angle’;

end

end

/**

* Potentiometer

*

* theta = initial displacement of angle

*

* resolution = the resolution the ADC gives

* ex: for 100 values on one turn, 360 degrees (2 Pi radian) -> resolution = 2*pi/100

*

*/

class Mediator(angle)

private

pend := create Pendulum(angle);

ctrl := create Controller(angle,0.06/*0.05*/,2*pi*10/(1024),24,4);

end

ctrl.angle= pend.angle;

ctrl.angle’ = pend.angle’;

pend.pos’’ = ctrl.acceleration;

end

class Main(simulator)

private

mode := "init";

end

switch mode

case "init"

simulator.endTime := 5;

simulator.timeStep := 0.001;

create Mediator(pi/18);

mode := "wait";

case "wait"

end

end

Page 101: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX B. VIRTUAL MODELS IN ACUMEN 79

Model B

/**

* Virtual prototype of Inverted pendulum controller

*

* Authour:

* Viktor Frimodig

* Martin Gustavsson

*

*/

/**

* Model of the pendulum

* Plant and visualization

*

* theta = initial angle displacement, unit rad, ex. 5*(pi/180)

*/

class Pendulum(theta)

private

angle :=theta;angle’ := 0; angle’’ := 0;

len := 0.5;

x:=0;

g := 9.8;

pos:=0;pos’:=0;pos’’:=-0;

_3D := []

end

_3D =

[["Cylinder",[0,pos+sin(angle),cos(angle)],[0.05,2],yellow,[-angle+pi/2,0,0]],

["Sphere",[0,pos+2*sin(angle),2*cos(angle)],0.15,yellow,[0,0,0]],

["Box",[0,pos,-0.25],[0.5,0.5,0.5],red,[0,0,0]]];

angle’’=

(g * sin(angle)

+len * x

-pos’’ * cos(angle)

//-angle’*0.09 //1.1

)/len;

end

/**

* Model of the PD-controller

*

* theta = Initial angle displacement

* period_time = the period, seconds, ex. 0.02

* how often the pd control is applied on the actuator,and angle is sensed

*

* resolution = Sensitivity of modeled sensor, rad, ex 2 * (pi/180)

* p = Constant, proportional

Page 102: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX B. VIRTUAL MODELS IN ACUMEN 80

* d = Constant, derivative

*

*/

class Controller(theta, period_time, resolution, p, d)

// period_time = the time between two samples

private

angle := theta;

angle_sample := theta; angle_dt := 0;

angle_old:=theta;

k1 := p;

k2 := d;

acceleration :=0;

t :=0;t’:=1;

end

// Discretization -

if t >= period_time

// reset timer

t :=0;

// apply control law

acceleration :=

k1 * angle_sample

+ k2 * angle_dt;

// Quantization -

if angle > angle_sample + resolution

// Save old value, needed for calculate the derivative: angle_dt

angle_old := angle_sample;

// Create the modeled sample

angle_sample := angle_sample + resolution;

// Calculate the modeled derivative

angle_dt := (angle_sample - angle_old)/period_time

else if angle < angle_sample - resolution

// Same as above

angle_old := angle_sample;

angle_sample := angle_sample - resolution;

angle_dt := (angle_sample - angle_old)/period_time

end

end

end

end

/**

* Mediator control the flow of information between the models

*/

class Mediator(angle)

private

pend := create Pendulum(angle);

ctrl := create Controller(angle,0.02,0.1*(pi/180),12,2);

end

// Set controllers angle. To create sample

ctrl.angle= pend.angle;

Page 103: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX B. VIRTUAL MODELS IN ACUMEN 81

// Set the input for the plant

pend.pos’’ = ctrl.acceleration;

end

/**

*Main, initialize the simulation

*/

class Main(simulator)

private

mode := "init";

end

switch mode

case "init"

simulator.endTime := 10; // set length of simulation

simulator.timeStep := 0.001; // set time step

create Mediator(5*(pi/180)); // create Mediator, set initial angle

mode := "wait";

case "wait"

end

end

Page 104: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX B. VIRTUAL MODELS IN ACUMEN 82

Page 105: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

C Wiring

Figure C.1: Breadboard view.

83

Page 106: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX C. WIRING 84

Figure C.2: Circuit diagram.

Page 107: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

D Control program

Balance control

#include <VarSpeedServo.h>

double pos = 0;

VarSpeedServo myservo;

float PotValue = 0;

float oldPotValue = 0;

float error = 0;

float old_error =0;

float dt_error =0;

int ctrl_sign =0;

int direction =0;

int kp = 10;

int kd = 1;

int goalValue = 301;

int wait = 5;

void setup() {

Serial.begin(9600);

myservo.attach(9);

myservo.write(105,255,true);

}

void loop() {

PotValue = analogRead(1);

Serial.println((int)PotValue);

// print_info();

delay(wait);

85

Page 108: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX D. CONTROL PROGRAM 86

PotValue = (0.7 * PotValue + 0.3 * oldPotValue)+0.5;

//Control part

error = (int)( goalValue - PotValue );

// derivative ( delta e / delta t )

dt_error = (error - old_error);///(wait*0.001);

// PD ctrl

ctrl_sign = (int) abs( kp * error + kd * dt_error );

direction = kp * error + kd * dt_error;

if(fail_safe(error)){

// set servo speed and direction

set_speed(direction, ctrl_sign);

}

// update old error

old_error = error;

oldPotValue = PotValue;

}

void set_speed(int err,int out){

Serial.println(out);

if( err == 0 ){

//Do nothing

myservo.write(myservo.read(),0,false);

}else{

if(err < -1){myservo.write(170,out,false);}

if(err > 1){myservo.write(10,out,false);}

}

}

int fail_safe(int val){

//error is big

if(val < -10 || val > 10){

myservo.write(105,40,true);

// Serial.println("fail");

return 0;

}else {

return 1;

}

}

void print_info(){

Serial.print("A1=");

Serial.print(PotValue);

Serial.print(" ");

Serial.println(myservo.read());

}

Page 109: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

APPENDIX D. CONTROL PROGRAM 87

Swing-up control

#include <VarSpeedServo.h>

VarSpeedServo servo; // Servo motor to control

const int ctrSignal = 9; // PWM-pin that control the servo

void setup()

{

servo.attach(ctrSignal); // Attach servo to PWM-pin

myservo.write(105,255,true); // Initial position of the servo

}

void loop()

{

// Move servo to position 180 with speed 145 and wait for pendulum

to gain energy

servo.write(180,145,true);

delay(16);

// Move servo to position 20 with speed 145 and wait for pendulum

to gain energy

servo.write(20,145,true);

delay(16);

}

Page 110: BACHELOR - DiVA portal792642/FULLTEXT01.pdf · Abstrakt Arbetet motiveras av m alet att knyta samman verklighet och modell, samt att se om det nns m ojlighet att utveckla ett billigt

PO Box 823, SE-301 18 HalmstadPhone: +35 46 16 71 00E-mail: [email protected]

Martin Gustavsson

Mechatronic Engineering

Viktor Frimodig

Computer System Engineering