153 70 41MB
English Pages 238
books
books
With Raspberry Pi and Arduino Uno The Arduino Uno is an open-source microcontroller development system encompassing hardware, an Integrated Development Environment (IDE), and a vast number of libraries. It is supported by an enormous community of programmers, electronic engineers, enthusiasts, and academics. The libraries in particular really smooth Arduino programming and reduce programming time. What’s more, the libraries greatly facilitate testing your programs since most come fully tested and working. The Raspberry Pi 4 can be used in many applications such as audio and video media devices. It also works in industrial controllers, robotics, games, and in many domestic and commercial applications. The Raspberry Pi 4 also offers Wi-Fi and Bluetooth capability which makes it great for remote and Internet-based control and monitoring applications. This book is about using both the Raspberry Pi 4 and the Arduino Uno in PID-based automatic control applications. The book starts with basic theory of the control systems and feedback control. Working and tested projects are given for controlling real-life systems using PID controllers. The open-loop step time response, tuning the PID parameters, and the closedloop time response of the developed systems are discussed together with the block diagrams, circuit diagrams, PID controller algorithms, and the full program listings for both the Raspberry Pi and the Arduino Uno. The projects given in the book aim to teach the theory and applications of PID controllers and can be modified easily as desired for other applications. The projects given for the Raspberry Pi 4 should work with all other models of Raspberry Pi family. The book covers the following topics: > Open-loop and closed-loop > control systems > Analog and digital sensors > > Transfer functions and continuous-time systems > First-order and second-order > system time responses > Discrete-time digital systems > > Continuous-time PID controllers > Discrete-time PID controllers >
ON-OFF temperature control with Raspberry Pi and Arduino Uno PID-based temperature control with Raspberry Pi and Arduino Uno PID-based DC motor control with Raspberry Pi and Arduino Uno PID-based water level control with Raspberry Pi and Arduino PID-based LED-LDR brightness control with Raspberry Pi and Arduino Uno
Prof Dogan Ibrahim has a BSc, Hons. degree in Electronic Engineering, an MSc degree in Automatic Control Engineering, and a PhD degree in Digital Signal Processing. Dogan has worked in many industrial organizations before he returned to academic life. He is the author of over 70 technical books and has published over 200 technical articles on electronics, microprocessors, microcontrollers, and related fields. The full program listings of all the projects discussed in the book may be downloaded free of charge from the Elektor Store website, www.elektor.com (search for: book title).
Elektor International Media BV www.elektor.com
PID-based Practical Digital Control • Dogan Ibrahim
PID-based Practical Digital Control
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno # d e f in e P h a s e A 2
/ / Phase A
# d e f in e P h a s e B 3
/ / Phase B
# d e f i n e P WM 5
/ / P WM p i n
# d e f i n e DIR 4
/ / DIR p i n
f l o a t s k , K p , T i, T d , p k , T , p k _ 1, e k , e k _ 1, a , b , y k , q k , w k , u k ; v o l a t i l e u n sig n e d l o n g C o u n t = 0;
/ / Encode r coun t
f l o a t c o n v = 15 0.0 / 9 0.0; / / / / C o n f i g u r e P WM p i n a n d I n i t i a l i z e v a r i a b l e s / / v o i d s e t u p () { T C C R 2 B = T C C R 2 B & B 11111 0 0 0 | B 0 0 0 0 0 0 11; p i n M o d e ( D I R , O U T P U T );
/ / Di r e c t i o n i s o u t p u
d i g i t a l W r i t e ( D I R , L O W); p i n M o d e ( P WM, O U T P U T );
/ / P WM i s o u t p u t
p i n M o d e ( P h a s e B , I N P U T );
/ / P h a s e B is in p u t
p i n M o d e ( P h a s e A , I N P U T );
/ / P h a s e A is in p u t
a t t a c h I n t e r r u p t ( d i g i t a l P i n T o I n t e r r u p t ( P h a s e B ), E n c o d e r I S R , R I S
a t t a c h I n t e r r u p t ( d i g i t a l P i n T o I n t e r r u p t ( P h a s e A ), E n c o d e r I S R 2 , R S e r i a l . b e g i n (1 9 2 0 0 );
Dogan Ibrahim
● This is an Elektor Publication. Elektor is the media brand of Elektor International Media B.V.
PO Box 11, NL-6114-ZG Susteren, The Netherlands Phone: +31 46 4389444
● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or
storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication, without the written permission of the copyright holder except in accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be addressed to the publishers.
● Declaration
The Author and Publisher have used their best efforts in ensuring the correctness of the information contained in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from negligence, accident, or any other cause. All the programs given in the book are Copyright of the Author and Elektor International Media. These programs may only be used for educational purposes. Written permission from the Author or Elektor must be obtained before any of these programs can be used for commercial purposes.
● British Library Cataloguing in Publication Data
A catalogue record for this book is available from the British Library
● ISBN 978-3-89576-519-3 ISBN 978-3-89576-520-9
Print eBook
● Second, revised edition
© Copyright 2022: Elektor International Media B.V. Editor: Jan Buiting Prepress Production: D-Vision, Julian van den Berg
Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com
●4
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 4
11/10/2022 13:54
Contents
Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Chapter 1 • Control Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.1 Open-loop and closed-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.2 Microcontroller in the loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.3 Control system design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Chapter 2 • Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.1 Sensors in Computer Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.2 Temperature Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.2.1 Analog Temperature Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.2 Digital Temperature Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.3 Position Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 2.4 Velocity and Acceleration Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.5 Force Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.6 Pressure sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.7 Liquid Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 2.8 Flow Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Chapter 3 • Transfer Functions and Time Response . . . . . . . . . . . . . . . . . . . . . . . . 37 3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.2 First-order Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.2.1 Time Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.3 Second-order Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.3.1 Time Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.4 Time Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 3.5 Transfer Function of a Closed-loop System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Chapter 4 • Discrete Time (Digital) Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.2 The Sampling Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.3 The Z-Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.3.1 Unit step function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.3.2 Unit ramp function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
●5
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 5
11/10/2022 13:54
PID-based Practical Digital Control 4.3.3 Tables of z-Transforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.4 The z-Transform of a function expressed as a Laplace Transform. . . . . . . . . . . . . . 58 4.5 Inverse z-Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.6 Pulse transfer function and manipulation of block diagrams . . . . . . . . . . . . . . . . . 61 4.6.1 Open-loop systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.7 Open-loop time response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4.8 Closed-loop system time response. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Chapter 5 • The PID Controller in Continuous-Time Systems . . . . . . . . . . . . . . . . . 69 5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.2 Proportional-only Controller with a First-Order System. . . . . . . . . . . . . . . . . . . . . 70 5.3 Integral-Only Controller with a First-order System. . . . . . . . . . . . . . . . . . . . . . . . 71 5.4 Derivative-only Controller with a First-order System . . . . . . . . . . . . . . . . . . . . . . 72 5.5 Proportional + Integral Controller with a First-order System . . . . . . . . . . . . . . . . . 73 5.6 Proportional + Integral + Derivative controller with a First-order System . . . . . . . . 74 5.7 Effects of Changing the PID Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.8 Tuning a PID Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.8.1 Open-loop Ziegler and Nichols Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 5.8.2 Open-loop Cohen-Coon PID Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 5.8.3 Closed-loop Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 5.8.4 Practical PID Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 5.9 The Auto-tuning PID Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 5.10 Increasing and Decreasing PID Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 5.11 Saturation and Integral Wind-up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 5.12 Derivative Kick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 5.13 Using the PID Loop Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Chapter 6 • The Digital PID Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.2 Digital PID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.3 Choosing a Sampling Time, T . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.4 Microcontroller Implementation of the PID Algorithm . . . . . . . . . . . . . . . . . . . . . . 91 Chapter 7 • On-Off Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
●6
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 6
11/10/2022 13:54
Contents 7.2 Temperature Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 7.3 Project 1: ON-OFF Temperature Control with Arduino Uno . . . . . . . . . . . . . . . . . . 94 7.4 Project 2: ON-OFF Temperature Control with Hysteresis and Arduino Uno . . . . . . . 99 7.5 Project 3: ON-OFF Temperature Control with Button Control – Arduino Uno . . . . . 101 7.6 Project 4: ON-OFF Temperature Control with Rotary Encoder and Arduino Uno . . . 104 7.7 Project 5: ON-OFF Temperature Control with Raspberry Pi 4 . . . . . . . . . . . . . . . . 109 Chapter 8 • PID Temperature Control with the Raspberry Pi . . . . . . . . . . . . . . . . 119 8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 8.2 Project 1 - Reading the temperature of a thermistor . . . . . . . . . . . . . . . . . . . . . 119 8.3 Project 2: Open-loop Step-input Time Response . . . . . . . . . . . . . . . . . . . . . . . . 123 8.4 Project 3: PI Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.5 Project 4: PID Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 8.6 Using the PID Loop Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Chapter 9 • PID Temperature Control with the Arduino Uno. . . . . . . . . . . . . . . . . 144 9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 9.2 Project 1: Reading the Temperature of a Thermistor . . . . . . . . . . . . . . . . . . . . . 144 9.3 Project 2: PID Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.4 Project 3: PID Temperature Control with Arduino Uno and Timer Interrupts . . . . . 152 9.5 Project 4: PID Temperature Control using the Arduino Uno PID Library . . . . . . . . 155 Chapter 10 • DC Motor Control with Arduino and Raspberry Pi. . . . . . . . . . . . . . . 160 10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 10.2 Types of Electric Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 10.3 Brushed DC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 10.3.1 Permanent-magnet BDC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 10.3.2 Series-wound BDC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 10.3.3 Shunt-wound BDC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 10.3.4 Compound-wound BDC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 10.3.5 Separately-excited BDC Motors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 10.3.6 Servo Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.3.7 Stepper Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.4 Brushless DC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 10.5 Motor Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
●7
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 7
11/10/2022 13:54
PID-based Practical Digital Control 10.6 Transfer Function of a Brushed DC Motor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.7 The DC Motor Used in the Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 10.8 Project 1: Motor Speed and Direction Control Using an H-Bridge Integrated Circuit 170 10.9 Project 2: Displaying the Motor Speed with Arduino Uno. . . . . . . . . . . . . . . . . . 177 10.10 Project 3: Displaying Motor Speed on LCD with Arduino Uno . . . . . . . . . . . . . . 181 10.11 Project 4: Displaying Motor Speed with Raspberry Pi . . . . . . . . . . . . . . . . . . . 184 10.12 Project 5: Displaying Motor Speed on LCD with Raspberry Pi . . . . . . . . . . . . . . 186 10.13 Project 6: Identification of the DC Motor with Raspberry Pi . . . . . . . . . . . . . . . 188 10.14 Project 7: PID Motor Speed control with Raspberry Pi. . . . . . . . . . . . . . . . . . . 191 10.15 Project 8: PID Motor Speed Control with Arduino Uno . . . . . . . . . . . . . . . . . . 195 Chapter 11 • Water Level Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 11.2 Ultrasonic Transmitter-Receiver Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 11.3 Project 1: Measuring Distance using the HC-SR04 Ultrasonic Module with Arduino Uno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 11.4 Project 2: Measuring Distance using the HC-SR04 Ultrasonic Module with Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11.5 Project 3: Step Input Response of the System with Raspberry Pi . . . . . . . . . . . . 206 11.6 Project 4: PID-based Water Level Control with Raspberry Pi . . . . . . . . . . . . . . . 210 11.7 Project 5: PID-based Water Level Control with Arduino Uno . . . . . . . . . . . . . . . 215 Chapter 12 • PID-based LED Brightness Control . . . . . . . . . . . . . . . . . . . . . . . . . . 220 12.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 12.2 Project 1: Step Time Response of LED Brightness Control using the Raspberry Pi 220 12.3 Project 2: PID-Based LED Brightness Control using the Raspberry Pi . . . . . . . . . 224 12.4 Project 3: PID-based LED Brightness Control using the Arduino Uno . . . . . . . . . 229 12.5 Project 4: PID-based LED Brightness Control using the Arduino Uno Library . . . . 232 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
●8
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 8
11/10/2022 13:54
Preface Microcontrollers are highly popular integrated circuits commonly used in many domestic, commercial, and industrial electronic monitoring and control applications. It is estimated that there are more than 50 microcontrollers in every home in developed countries. Domestic equipment having embedded microcontrollers include microwave ovens, printers, keyboards, computers, tablets, washing machines, dishwashers, smart televisions, smartphones, and many more. Arduino Uno is an open-source microcontroller development system incorporating hardware, an Integrated Development Environment (IDE), and a large number of libraries. The Arduino Uno is supported by a large community of programmers, electronic engineers, enthusiasts, and academics. There are many different designs of the basic Arduino Uno board. Although they are intended for different types of applications, they can all be programmed using the same IDE and in general, programs can be transported between different boards. This may be one of the reasons for the popularity of the Arduino family, which is also supported by countless software libraries for many peripherals that can easily be included in your programs. These libraries make programming a doddle and speed up the programming time. Using libraries also make it easier to test your programs since most of them come as fully tested and working. The Raspberry Pi 4 is one of the latest credit-card sized popular computers that can be used in many applications such as in audio and video media centers, as a desktop computer, in industrial controllers, robotics, games, and many domestic and commercial applications. In addition to rich set of features found in other Raspberry Pi computers, the Raspberry Pi 4 also offers Wi-Fi and Bluetooth capability which makes it highly desirable for incorporation in remote and Internet-based control and monitoring applications. This book is about using both the Raspberry Pi 4 and the Arduino Uno in PID-based automatic control applications. The book starts with basic theory of the control systems and feedback control. Working and tested projects are given for controlling real systems using PID controllers. The open-loop step time response, tuning the PID parameters, and the closed-loop time response of the developed systems are discussed in depth together with the block diagrams, circuit diagrams, PID controller algorithms, and the full program listings for the Raspberry Pi as well as the Arduino Uno. The projects given in the book should teach the theory and applications of PID controllers. They can be modified easily as desired for other applications. The projects given for Raspberry Pi 4 should work with all other models of Raspberry Pi family. It is expected that the readers have some programming experience with the Arduino Uno using the Arduino IDE. The same for the Raspberry Pi with the Python 3 programming language. Some basic electronic hardware experience and knowledge of basic mathematics will also be useful.
●9
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 9
11/10/2022 13:54
PID-based Practical Digital Control
All programs discussed in the book are contained in an archive file you can download free of charge from the Elektor website. Head to: www.elektor.com/books and enter the book title in the Search box. I hope that you enjoy reading the book and at the same time learn the theory and practical applications of the PID controllers. Dogan Ibrahim London, 2022
● 10
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 10
11/10/2022 13:54
Chapter 1 • Control Systems
Chapter 1 • Control Systems 1.1 Open-loop and closed-loop Control engineering covers all aspects of governing a dynamic system, also called a plant or a process. A plant can be a mechanical system, an electrical system, a thermal system, a fluid system, or a combination of such systems. A plant can have one or more inputs and one or more outputs. The dynamic behavior of a plant is described by differential equations. Given the model (or the differential equations), inputs, and initial conditions of a plant we can easily calculate its outputs. Generally, a plant is a continuous-time system with its inputs and outputs also continuous in time. For example, an electromagnetic motor is a continuous-time plant whose input (e.g., voltage or current) and its output (e.g., speed or position) are also continuous in time. Control engineering is based on the theories of system modelling, feedback, system response, and stability. As a result, control engineering is not limited to only one engineering discipline, but is equally applicable to mechanical, chemical, aeronautical, civil, and electrical engineering disciplines. A plant is normally an open-loop system (Figure 1.1) where an actuating device is used to control the plant directly without using feedback. For example, a motor is expected to rotate when a voltage is applied across its input terminals, but we do not know by how much the motor rotates since there is no knowledge about its output. If the motor shaft is loaded and the motor slows down, there is no knowledge about this. As shown in Figure 1.1, a plant may also have external disturbances affecting its behavior, and in an open-loop system there is no way of knowing or minimizing such disturbances.
Figure 1.1: Open-loop system In contrast to open-loop control system, in a closed-loop control system (Figure 1.2) the actual plant output is measured and compared with what we would like to see at the plant output. The measure of the output is called feedback signal. The difference between the desired output value and the actual output value is called the error signal. The error signal is used to force the system output to a point such that the desired output value and the actual output value are equal, i.e., the error signal is zero. One of the advantages of closed-loop control, or feedback control is the ability to compensate for disturbances and yield the correct output even in the presence of disturbances. Also, the plant output settles
● 11
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 11
11/10/2022 13:54
PID-based Practical Digital Control
and remains at the desired value. For example, in a motor speed control system the speed of the motor remains the same when load is applied to the motor shaft. A controller (or compensator) is usually used to read the error signal and drive the plant in such a way that the error tends to zero. Sensors are devices which measure the plant output. For example, a thermistor is a sensor used to measure the temperature and it can be used in a closed-loop thermal plant control. Similarly, a tachometer or an encoder can be used to measure the rotational speed of a motor and they can be used in closed-loop motor speed control applications. Notice that in electrical systems a power amplifier may be required after the DAC to drive the plant.
Figure 1.2: Closed-loop system As you'll discover in a later Chapter, most sensors are analog devices giving analog voltage or current outputs. These sensors can be used directly in analog systems where the inputs, controller, plant, and the outputs are all analog variables.
1.2 Microcontroller in the loop Nowadays, practically all control systems are microcontroller based, where a microcontroller is used as the central control device. Some sensors (e.g., temperature, pressure, humidity etc.) provide digital outputs and can be connected directly to a microcontroller. Analog sensors cannot be connected directly to a microcontroller. An analog-to-digital converter (ADC) is needed to convert the analog signal into digital form so that it can be fed to a microcontroller. Figure 1.3 shows a digital control system where the input and the output of the sensor are assumed to be analog. An ADC is used to periodically convert the error signal into digital form and this is fed to a digital controller which is usually a microcontroller. The microcontroller implements a control algorithm (e.g., PID algorithm) and its output is converted into analog form using a digital-to-analog converter (DAC) so that it can drive the plant to set the plant output to the desired value.
Figure 1.3: Digital control system.
● 12
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 12
11/10/2022 13:54
Chapter 1 • Control Systems
Figure 1.4 shows the block diagram of a digital control system where the ADC is shown as a sampler. Most microcontrollers incorporate ADC and DAC modules and these are shown as part of the microcontroller in Figure 1.4.
Figure 1.4: Block diagram of a digital control system. In Figure 1.4 the input and the sensor output are analog signals. A variation of this system is shown in Figure 1.5 where the input is digital and is either hardcoded to the microcontroller software or is input using a suitable input device such as a keypad. Here, a sensor with digital output is used and is connected directly to the microcontroller.
Figure 1.5: Another variation of digital control. Figure 1.6 shows a typical analog speed control system. Here, the desired speed is set using a potentiometer. The speed of the motor is measured using a tachometer and is fed back to a difference amplifier. The output of this amplifier is the error signal which is input to an analog controller consisting of operational amplifiers. The output of the controller drives the motor through a power amplifier to achieve the desired speed.
Figure 1.6: Analog speed control system.
● 13
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 13
11/10/2022 13:54
PID-based Practical Digital Control
Figure 1.7 shows the digital equivalent of Figure 1.6. Here, a digital encoder is used to measure the motor speed and this is fed to the microcontroller together with the desired speed where the speed is set using a keypad. The microcontroller implements the control algorithm and sends its output to the power amplifier in the form of a Pulse Width-Modulated (PWM) signal which in turn provides power to the motor to set the speed at the desired value.
Figure 1.7: Digital speed control system. Since a plant can be controlled using an analog approach, you might be tempted to ask why use digital control? In the 1960s, computers and microcontrollers were bulky and very expensive devices and their use as digital controllers was not justified. They were only used in large and expensive plants, such as large chemical processing sites or oil refineries. Since the introduction of microcontrollers in 1970s, the cost and size of digital controllers have dropped dramatically. As a result of this, also from the drop in the price of other digital components such as memories, interest in using digital control has soared in the past few decades. Digital controllers have several advantages compared to analog controllers: • Improved user interface. Digital controllers can display the system parameters and response graphically on a monitor. • Digital controllers can be configured to be adaptive. Complex controller algorithms can easily be implemented using digital controllers. • The cost of digital controllers are lower than the analog ones, especially if additional control loops have to be added to the system. • It is easy to tune digital controllers. All that is required is to change pertinent parameters in software. • Digital controllers are more dependable than the analog ones and they are not affected by environmental factors such as component aging, component tolerances, etc. • Digital controllers can be modified easily through software. Modification of an analog controller on the other hand usually require re-wiring or the use of different or additional components. • Almost all analog controllers have been replaced over time by digital ones.
● 14
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 14
11/10/2022 13:54
Chapter 1 • Control Systems
1.3 Control system design Control system design is an engineering process and it must be carried out systematically. The major steps to design a physical control system can be summarized by the following steps: • • • • • • • • • • • •
Define the system input and output Define the variable to be controlled Derive a mathematical model (differential equations) of the system Decide whether analog or digital control is to be used Choose a suitable sensor Choose a microcontroller (if digital control is to be used) Choose other components such as power supply, op-amp, power amplifier etc. Draw a block diagram of the system Describe the controller to be used and develop the control algorithm Adjust the parameters of the chosen controller Simulate the overall system (if simulation tools such as MATLAB are available) Assemble the system and observe its behavior. If the system response is as desired, that concludes the project. If on the other hand the system does not behave as required, go back to choose a different controller or to re-adjust the controller parameters, re-simulate and re-test.
● 15
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 15
11/10/2022 13:54
PID-based Practical Digital Control
Chapter 2 • Sensors
Chapter 2 • Sensors 2.1 Sensors in Computer Control Sensors are important parts of all closed-loop systems. A sensor is a device that outputs a signal which is related to the measurement (i.e., is a function of) a physical quantity, such as temperature, humidity, speed, force, vibration, pressure, displacement, acceleration, torque, flow, light or sound. Sensors are used in closed-loop systems in the feedback loops, and they provide information about the actual output of the plant they are attached to. For example, a speed sensor gives a signal proportional to the speed of a motor and this signal is subtracted from the desired speed reference input in order to obtain the error signal. Similarly, a liquid level sensor gives a signal proportional to the level of liquid in a container. Such a sensor is used in controlling the level of a liquid in a container. Sensors can be divided into two groups: analog or digital. Analog sensors are widely used and their outputs are analog signals (e.g., voltage or current) proportional to the physical quantity to be measured. Most environmental variables in the world are analog by nature, for example the temperature, humidity, pressure etc. An analog temperature sensor gives an analog voltage directly proportional to the measured temperature. Analog sensors can only be connected to microcontrollers using ADC converter modules. Digital sensors are not very common and they give digital logic level outputs which can be directly connected to a computer. The advantage of using digital sensors is that they are more accurate and stable than the analog ones and they can directly be connected to a computer. Digital sensors also tend to me more expensive than their analog equivalents. The choice of a sensor for a particular application depends on several factors such as the availability, cost, accuracy, precision, resolution, range, and linearity of the sensor. Some important sensor related parameters are described below. Range: The range of a sensor specifies the upper and lower limits that can be measured by the sensor. For example, if the range of a temperature sensor is specified as 10 – 60 ºC then the sensor should only be used to measure temperatures within this range. Resolution: The resolution of a sensor is specified as the largest change in measured value that will not result in a change in sensor's output. i.e., the measured value can change by the amount quoted by the resolution before this change can be detected by the sensor. In general, the smaller this amount the better the sensor is, and sensors with a wide range have less resolution. For example, a temperature sensor with a resolution of 0.01 ºC is better than a sensor with a resolution of 0.1 ºC. Sensitivity: The sensitivity of a sensor is defined as the slope of the output characteristic curve. More generally, it is the minimum input of physical parameter that will create a detectable output change. For example, a typical temperature sensor may have a sensitivity rating of 1 ºC. This means that the output voltage will not change if the temperature change is less than 1 ºC .
● 16
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 16
11/10/2022 13:54
Chapter 2 • Sensors
Accuracy: The accuracy of a sensor is the maximum difference that will exist between the actual value and the indicated value at the output of the sensor. The accuracy can be expressed either as a percentage of full scale or in absolute terms. Repeatability: The repeatability of a sensor is the variation of output values that can be expected when the sensor measures the same physical quantity with the same conditions. For example, if the voltage across a resistor is measured at the same time several times you may get slightly different results. Linearity: An ideal sensor is expected to have a linear transfer function. i.e., the sensor output is expected to be exactly proportional to the measured value. For example, the LM35 temperature sensor chip output is linear and is specified as 10mV/ºC. At 10 ºC the output voltage is 100 mV, at 20 ºC it is 200 mV and so on. In practice all sensors exhibit some amount of nonlinearity depending upon the manufacturing tolerances and the measurement conditions. Offset error: The offset error of a sensor is defined as the output that will exist when it should be zero. For example, the output of a force sensor should be zero if there is no force applied to the sensor. Dynamic response: The dynamic response of a sensor specifies the limits of the sensor characteristics when the sensor is subject to a sinusoidal frequency change. For example, the dynamic response of a microphone may be expressed in terms of the 3-dB bandwidth of its frequency response. Response time: Sensors do not change their output states immediately when an input parameter change occurs. For example, a temperature sensor does not give new reading as soon as the temperature changes, but rather, it will take some time before the output changes. The response time can be in microseconds, milliseconds, or seconds depending upon the sensor used. Sensors with short response times, although more expensive, are preferred in most applications. Self-heating: The internal temperatures of some sensors may increase when used tinuously for long times and this is called self-heating. Self-heating is not desirable may cause the output of the sensor to change. For example, a temperature sensor self-heating feature may give wrong and fluctuating outputs as the sensor is used time.
conas it with over
Physical size: The physical size of a sensor can be important in some applications. Users should check the dimensions of a sensor before it is considered for use. Operating voltage: This is also an important factor to consider before a sensor is used. The operating voltage, as well as the minimum and maximum voltages that can be applied to the sensor should be known before a sensor is used. For example, if the operating voltage is specified as +3.3 V then this value must not be exceeded.
● 17
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 17
11/10/2022 13:54
PID-based Practical Digital Control
In the remainder of this Chapter, the operation and characteristics of some popular sensors are discussed.
2.2 Temperature Sensors Temperature is one of the fundamental physical variables in most chemical and process control applications. Accurate and reliable measurement of the temperature is important in all process control applications. The choice of a temperature sensor depends on the required accuracy, temperature range, response time, cost, and the environment where it will be used (e.g., chemical, electrical, mechanical, environmental etc.). Temperature sensors are available as either analog or digital. Both sensor types are described briefly in the following sections.
2.2.1 Analog Temperature Sensors Some of the most commonly used analog temperature sensors are: thermocouples, resistance temperature detectors (RTDs), thermistors, and sensors in te form of chips (integrated circuits). Table 2.1 shows the basic characteristics of different types of analog temperature sensors. Sensor
Temperature range ( ºC )
Accuracy (± ºC )
Cost
Robustness
Thermocouple
–270 to +2600
1
Low
Very high
RTD
–200 to +600
0.2
Medium
High
Thermistor
–50 to +200
0.2
Low
Medium
Integrated circuit
–40 to +125
1
Low
Low
Table 2.1: Analog temperature sensors. Thermocouples Thermocouples (Figure 2.1) are best suited to very low and very high temperature measurements. They have the advantages that they are low-cost, very robust, and they can be used in chemical environments. The typical accuracy of a thermocouple is ±1 ºC. Thermocouple temperature sensors can be made with various conductor materials for different temperature ranges and output characteristics. Thermocouple types are identified with single letters of the alphabet. Figure 2.1 shows the temperature ranges of various thermocouples. Notice that lead color codes are used to identify thermocouples. The materials used to form thermocouples is shown in Figure 2.2. For example, one of the commonly used low-cost thermocouples is Type K which is made from chromel/alumel junction, identified with green lead color, and has temperature range of –180 ºC to +1300 ºC .
● 18
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 18
11/10/2022 13:54
Chapter 2 • Sensors
Figure 2.1: Thermocouple types.
Figure 2.2: Materials used in different thermocouples. To get the temperature from a thermocouple a thermocouple amplifier is generally used. The temperature output from the thermocouple amplifier depends on the voltage of the reference junction. The voltage at the reference junction depends on the temperature difference between the reference junction and the thermal junction. Therefore, you need to know the temperature at the reference junction. The MAX6675 thermocouple amplifier module (Figure 2.3) comes with an on-board temperature sensor to measure temperature at the reference junction and also amplifies the small thermocouple voltage at the reference junction so that you can read it using a microcontroller.
● 19
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 19
11/10/2022 13:54
PID-based Practical Digital Control
Figure 2.3: MAX6675 thermocouple amplifier module. Thermocouples are available in various shapes and forms. Some sensors are equipped with 2-way plugs for ease of connecting to a measuring device. Figure 2.4 shows some of the commonly available thermocouples.
Figure 2.4: Some thermocouples. RTDs RTDs (Resistance Temperature Detector) are sensors whose resistance changes with temperature. The resistance increases as the temperature of the sensor increases. The resistance vs temperature relationship is well known and repeatable over time. RTDs are passive devices and they do not produce any output. Usually, the resistance of an RTD is measured by passing a small electrical current through it and then measuring the voltage across the sensor. Care should be taken not to pass large currents as self-heating of the sensor may occur. Typically, 1 mA or less current is passed through the sensor. Figure 2.5 shows some RTD sensors. RTDs have excellent accuracies over a wide temperature range and some RTDs have accuracies better than 0.001 ºC . another advantage of the RTDs is that they drift less than 0.1 ºC /year.
Figure 2.5: Some RTDs.
● 20
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 20
11/10/2022 13:54
Chapter 2 • Sensors
In order to achieve high stability and accuracy, RTD sensors must be contamination free. Below about 250 ºC the contamination is not much of a problem, but above this temperature, special manufacturing techniques are used to minimize the contamination. RTD sensors are usually manufactured in two forms: wire wound, or thin film. Wire-wound RTDs are made by winding a very fine strand of platinum wire into a coil shape around a non-conducting material until the required resistance is obtained. Thin-film RTDs are made by depositing a layer of platinum in a resistance pattern on a ceramic substrate. The most commonly used RTD standard is the IEC 751 which is based on platinum with a resistance of 100 Ω at 0 ºC. For high accuracy it is recommended to use an RTD-to-digital converter module like the MAX31865 module (Figure 2.6). This chip is optimized for platinum RTDs. An accurate reference resistor is used to set the sensitivity for the RTD. An on-chip ADC returns the ratio of the RTD resistance to the reference resistance in digital form. Knowing the reference resistance, you can easily calculate the RTD resistance and hence the measured temperature either from temperature-resistance tables or using a library function.
Figure 2.6: MAX31865 RTD converter module. Thermistors The name thermistor derives from the words thermal and resistor. Thermistors are temperature sensitive passive semiconductors which exhibit a large change in electrical resistance when subjected to a small change in body temperature. Thermistors are manufactured in a variety of sizes and shapes (Figure 2.7). beads, discs, washers, wafers, and chips are the most widely used thermistor sensor types.
● 21
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 21
11/10/2022 13:54
PID-based Practical Digital Control
Figure 2.7: Different shapes of thermistors. Thermistors are generally available in two types: Negative Temperature Coefficient (NTC) and Positive Temperature Coefficient (PTC). PTC thermistors are generally used in power circuits for inrush current protection. NTC thermistors exhibit many desirable features for temperature measurement. Their electrical resistance decreases with increasing temperature (Figure 2.8) and the resistance-temperature relationship is very nonlinear. The resistance of a thermistor is referenced to 25 ºC and for most applications the resistance at this temperature is between 100 Ω and 100 kΩ.
Figure 2.8: Typical thermistor R/T characteristic. The advantages of NTC thermistors are: Sensitivity: One of the advantages of thermistors compared to thermocouples and RTDs is their large change in resistance with temperature, typically –5% per ºC. Small size: Thermistors have very small sizes and this makes for a very rapid response to temperature changes. This feature is very important in temperature feedback control systems where a fast response may be required. Ruggedness: Most thermistors are rugged and can handle mechanical and thermal shock and vibration better than other types of temperature sensors.
● 22
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 22
11/10/2022 13:54
Chapter 2 • Sensors
Remote measurement: Thermistors can be used to sense the temperature of remote locations via long cables because the resistance of a long cable is insignificant compared to the relatively high resistance of a thermistor. Low-cost: Thermistors cost less than most other types of temperature sensors. Interchangeability: Thermistors can be manufactured with very close tolerances. As a result, it is possible to swap thermistors without having to recalibrate the measurement system. Thermistors can suffer from self-heating problems as a result of current passing through them. When a thermistor self-heats, the resistance reading drops relative to its true value and this causes errors in the measured temperature. It is therefore important to minimize the electrical current through a thermistor. Thermistors can be used in circuits in series with a known accurate fixed resistor. By measuring the voltage across the thermistor, you can calculate its resistance. Alternatively, constant current, bridge, or operational amplifier circuits can be designed to measure the resistance of a thermistor. After finding the resistance of a thermistor, you can calculate the temperature using tables (if available), or a library function (if available), or use the standard Steinhart-Hart equation given below:
or
Where T0 is the room temperature in K (298.15), B is the thermistor temperature constant, R0 is the thermistor resistance at room temperature, and R is the measured resistance of the thermistor. An example is given below. Example The temperature constant of a thermistor is B = 2910. Also, its resistance at room temperature (25 ºC ) is 1 kΩ. This thermistor is used in an electrical circuit to measure the temperature and it is found that the resistance of the thermistor is 800 Ω. Calculate the measured temperature. Solution Here, you know that B = 2910, T0 = 298.15, R = 800 Ω, and R0 = 1000 Ω
● 23
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 23
11/10/2022 13:54
PID-based Practical Digital Control
Kelvin or T = 310.24 – 273.15 = 37.09 ºC Integrated circuits Integrated circuit analog sensors are semiconductor devices. they differ from other sensors in some fundamental ways: • • • • •
They have relatively small physical sizes. Their outputs are linear. The temperature range is relatively limited. The cost is relatively low. They often lack good thermal contacts with the outside world and as a result it is usually more difficult to use them other than measuring the air temperature. • A power supply is required to operate these sensors. Analog integrated circuit temperature sensor can be voltage output or current output. In this section you will look at the characteristics of some commonly used sensors. LM35DZ This is a popular 3-pin temperature sensor (Figure 2.9) chip whose output voltage is linear, given by 10 mV/ ºC . For example, at 10 ºC the output voltage is 100 mV, at 20 ºC it is 200 mV and so on. this sensor has the range 0 ºC to +100 ºC (the CZ version of this sensor has a wider temperature range like –20 ºC to +120 ºC ). The accuracy of this sensor is ±1.5 ºC and the operating voltage is 4 to 30 V.
Figure 2.9: The LM35DZ temperature sensor. The LM34 is similar to the LM35DZ but it measures in degrees Fahrenheit. The LM134, AD590, and AD592 are current-output temperature sensors where the output current is directly proportional to the measured temperature. For example, the output of AD590 (Figure 2.10) is given as 1 µA/K.
● 24
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 24
11/10/2022 13:54
Chapter 2 • Sensors
Figure 2.10: AD590 temperature sensor. TMP36 This is another popular analog integrated circuit temperature sensor chip. The size and configuration of the sensor is same as in Figure 2.9. The output of TMP36 is linear with the measured temperature given by: Vo – 500 /10, where Vo is the sensor output voltage in millivolts.
2.2 Digital Temperature Sensors These sensors produce digital outputs and therefore they can be directly connected to microcontrollers. The outputs are non-standard and the measured temperature can be extracted in software by using a suitable algorithm. Table 2.2 gives a list of some popular digital output temperature sensors. Sensor
Output
Maximum error
Temperature range
LM75
I2C
±3 ºC
–55 ºC to +125 ºC
TMP03
PWM
±4 ºC
–25 ºC to +100 ºC
DS18B20
1-Wire
±0.5 ºC
–55 ºC to +125 ºC
AD7814
SPI
±2 ºC
–55 ºC to +125 ºC
MAX6575
1-Wire
±0.8 ºC
–40 ºC to +125 ºC
DHT11
Serial 1 wire
±2 ºC
0 ºC to +50 ºC
DHT22
Serial 1 Wire
±0.5 ºC
–40 ºC to +80 ºC
Table 2.2: Some digital-output temperature sensors. DHT11 and DHT22 (Figure 2.11) are highly popular 3-terminal digital output sensors. Both devices can measure temperature as well as relative humidity. Arduino and Raspberry Pi libraries are available for both sensors for reading the temperature and humidity data easily.
● 25
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 25
11/10/2022 13:54
PID-based Practical Digital Control
Figure 2.11: The DHT11 and DHT22 sensors.
2.3 Position Sensors Position sensors are used to measure the position of moving objects. These sensors are basically of two types: sensors to measure linear movement, and sensors to measure angular movement. The simplest position sensor is a potentiometer. Potentiometers are available in linear and rotary forms. In a typical application, a fixed voltage is applied across the potentiometer and the voltage across the potentiometer arm is measured. This voltage is proportional to the position of the arm, and hence by measuring the voltage you know the position of the arm. Figure 2.12 shows a linear potentiometer. If the applied voltage is Vi , the voltage across the arm is given by:
Va = k Vi y where y is the position of the arm from the beginning of the potentiometer, and k is a constant.
Figure 2.12: Linear potentiometer.
● 26
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 26
11/10/2022 13:54
Chapter 2 • Sensors
Figure 2.13 shows a rotary potentiometer which can be used to measure angular position. If Vi is again the applied voltage, the voltage across the arm is given by:
Va = k Vi θ where θ is the arm angle and k is a constant.
Figure 2.13: Rotary potentiometer. Other types of position sensors are capacitive sensors, inductive sensors, linear variable differential transformers (LVDTs), magnetic linear encoders, optical encoders, ultrasonic sensors etc. Capacitive position sensors rely on the fact that the capacitance of a parallel-plate capacitor changes as the distance between the plates is changed. These sensors are used in micrometer and millimeter applications where their resolution can be in nanometers (e.g., the MicroSense Model 4810). LVDT sensors (Figure 2.14) consist of one primary and two secondary windings on a hollow cylinder. A magnetic core which measures the position moves inside the cylinder, and the movement of this core varies the magnetic field linking the primary winding to the secondary windings. The movement of the core to one position increases the induced voltage in one secondary coil and decreases the induced voltage in the other secondary coil. The net voltage difference is proportional to the position of the core inside the cylinder. Thus, by measuring the induced voltage you know the position of the core. The advantages of LVDT are: • • • • • •
low cost robust design no hysteresis effect fast response time; no friction resistance long life
● 27
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 27
11/10/2022 13:54
PID-based Practical Digital Control
To be fair, the main disadvantage of the LVDT is that the core must have direct contact with the measured surface, which may not always be possible.
Figure 2.14: LVDT position sensor. A magnetic linear encoder system uses a magnetic sensor head and a magnetic scale to produce analog or digital output. As the magnetic sensor head passes along the magnetic scale, the sensor detects the change in magnetic field and outputs a signal to indicate the position of the head. Optical encoders are sensors commonly used for measuring the position or speed of a rotating body. There are several different types of optical encoders. In its simplest application, the device consists of a shaft connected to a circular disc with holes on it (Figure 2.15). A light beam shines from one side and a light detector is used at the other side. By counting the holes passing in-front of the sensor you can tell the position or the speed of the rotating shaft. Other types of optical encoders use the Hall-effect principle where one or more small magnets are attached to the rotor and the magnetic field is detected as the rotor rotates. Using two such magnets you can determine the direction of rotation of the rotor.
Figure 2.15: Optical encoder.
2.4 Velocity and Acceleration Sensors One of the widest used rotary velocity sensors is the tach generator. A tachometer (Figure 2.16) is connected to the shaft of a rotating device (e.g., a motor) and produces an analog DC voltage which is proportional to the speed of the shaft. If ω is the angular velocity of the shaft, the output voltage of the tachometer is given by:
● 28
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 28
11/10/2022 13:54
Chapter 2 • Sensors
Vo = k ω where k is the gain constant of the tachometer. Another popular velocity sensor is the optical encoder as shown in Figure 2.15 and described earlier.
Figure 2.16: Commercially available tachogenerator. Acceleration is the differentiation of velocity, or the double differentiation of position. Thus, in general, position or velocity sensors can be used to measure acceleration. The differentiation can be done either by using operational amplifiers or by a computer program. For accurate measurement of the acceleration, semiconductor accelerometers can be used. For example, the ADXL203 is an accelerometer chip manufactured by Analog Devices Inc. The chip is tiny (5 × 5 × 2 mm) and it is available as a module on a small board (see Figure 2.17). This is a low-cost 8-pin chip with two outputs to measure the acceleration in two dimensions. The outputs are digital signals whose duty cycles are proportional to the acceleration in each of the two axes. These outputs can be connected directly to a microcontroller and the acceleration can be measured very easily, requiring no A/D converter. The measurement range of the ADXL203 is ±1.7 g to ±18 g, where g is acceleration due to gravity, and the device can measure both dynamic acceleration (e.g., vibration), and static acceleration (e.g., gravity).
Figure 2.17: ADXL203 accelerometer module.
● 29
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 29
11/10/2022 13:54
PID-based Practical Digital Control
2.5 Force Sensors Load cells are commonly used in force sensor applications. Load cells can use different technologies to produce an output. Some load cell types are: hydraulic, pneumatic, inductive, capacitive, piezoelectric, strain gauge et. Strain gauges can be used to measure force accurately. There are many different types of strain gauges. A strain gauge can be made from capacitors and inductors, but the most widely used types are made from resistors. A wire strain gauge is made from a resistor, in the form of a metal foil. The principle of operation is that the resistance of a wire increases with increasing strain and decreases with decreasing strain. In order to measure strain with a strain gauge, it must be connected to an electrical circuit, and a Wheatstone bridge is commonly used to detect the small changes in the resistance of the strain gauge. Strain gauges can be used to measure force, load, weight pressure, torque or displacement. Force can also be measured using the principle of piezoelectricity. A piezoelectric sensor produces voltage when a force is applied to its surface. The disadvantage of this method is that the voltage decays after the application of the force and thus piezoelectric sensors are only useful for measuring dynamic force. Some of the popular force sensors used in microcontroller applications are the FlexiForce sensors. For example, the A201 is a variable resistance flexible force sensor (Figure 2.18) that can be used to measure force from 4.4N to up to 440N. This is a 191mm long, 14mm wide flexible sensor. The sensor is usually used with an operational amplifier where the output voltage is proportional to the measured force.
Figure 2.18: A201 force sensor.
2.6 Pressure sensors Pressure sensors are used to measure the pressure in air, liquid or gas. There are basically three types of pressure sensors: relative (or gauge) pressure sensors, absolute pressure sensors, differential pressure sensors.
● 30
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 30
11/10/2022 13:54
Chapter 2 • Sensors
Relative pressure sensors measure the pressure relative to the ambient atmospheric pressure. It is positive for pressures higher than atmospheric, or negative for lower pressures. These sensors have two ports to allow the reference pressure and the pressure to be measured. Absolute pressure sensors give the result relative to perfect vacuum (i.e., zero pressure). These sensors have one port for the pressure to be measured. These sensors can be used to measure the atmospheric pressure (e.g., for determining the altitude). Differential pressure sensors measure the difference in pressure between two points, similar to relative sensors, but here the reference pressure may not have to be the atmospheric pressure. There are many pressure sensors available that can be used with microcontrollers. For example, the Adafruit MPRLS 3965 module (Figure 2.19) uses the I2C bus and includes a 24-bit ADC, operating at 3-5V. This sensor can measure the absolute pressure from 0 to 25 PSI. this is a small module measuring only 3.7 mm long and 2.5 mm diameter. Arduino and Raspberry Pi libraries are available for this module.
Figure 2.19: MPRLS 3965 pressure sensor. SparkFun MPL3115A2 is another popular pressure sensor module (Figure 2.20) for microcontrollers. This sensor module also provides altitude data to within 30 cm. Interface to the module is through the I2C bus. The device also contains a 12-bit temperature sensor. Operating with 1.95 to +3.6 V, pressure output is in Pascals and altitude in meters. The sensor can measure pressures from 20 to 110 kPa. The temperature sensor range is –40 ºC to +85 ºC with an accuracy of ±3 ºC across the whole temperature range.
● 31
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 31
11/10/2022 13:54
PID-based Practical Digital Control
Figure 2.20: MPL3115A2 pressure sensor. The BMP280 is another popular pressure sensor frequently used in microcontroller applications. This is an absolute barometric pressure sensor. This sensor, based on piezo-resistive technology has been developed by Bosch and features high accuracy and linearity as well as long term stability. The sensor is available as a module as shown in Figure 2.21. pressure range of this sensor is 300 to 1100 hPa with an accuracy of ±1 hPa. The module operates with the I2C interface and provides temperature measurement as well in the range –40 ºC to +85 ºC with an accuracy of ±1 ºC .
Figure 2.21: BMP280 pressure sensor module.
2.7 Liquid Sensors There are many different types of liquid sensors. These sensors are used to: • detect the presence of liquid; • measure the level of liquid; • measure the flow rate of liquid, for example through a pipe. The presence of a liquid can be detected by using optical, ultrasonic, change of resistance, change of capacitance or similar techniques. For example, optical technique is based on using an LED and a photo-transistor, both housed within a plastic dome and at the head of the
● 32
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 32
11/10/2022 13:54
Chapter 2 • Sensors
device. When no liquid is present, light from the LED is internally reflected from the dome to the photo-transistor and the output is designed to be off. When liquid is present the dome is covered with liquid and the refractive index at the dome–liquid boundary changes, allowing some light to escape from the LED. As a result of this, the amount of light received by the photo-transistor is reduced and the output is designed to switch on, indicating the presence of liquid. The level of liquid in a tank can be measured using immersed sensor techniques, or non-touching ultrasonic techniques. The simplest technique is to immerse a rod in the liquid with a potentiometer placed inside the rod. The potentiometer arm is designed to move as the level of the liquid is changed. The change in the resistance can be measured and hence the level of the liquid is obtained. Ultrasonic transmitter-receiver pair modules are often used to measure the level of liquid in a container. An ultrasonic signal is transmitter by the transmitter module. This signal reflects back from the surface of the liquid and is detected by the receiver module. The time difference between sending and receiving the signal is used to determine the distance to the surface of the liquid. Knowing the height of the container you can easily calculate the height of the liquid in the container. Pressure sensors are also used to measure the level of liquid in a tank. Typically, the pressure sensor is mounted at the bottom of the tank where change of pressure is proportional to the height of the liquid. These sensors usually give an analog output voltage proportional to the height of the liquid inside the tank. Non-touching ultrasonic level measurement is very accurate, but more expensive than the other techniques. Basically, an ultrasonic beam is sent to the surface of the water and the echo of the beam is detected. The time difference between sending the beam and the echo is proportional to the level of the liquid in the tank. The liquid flow rate can be measured by several techniques: • paddlewheel sensors; • displacement flow meters; • magnetic flow meters. Paddlewheel sensors are cost-effective and very popular for the measurement of liquid flow rate. A wheel is mounted inside the sensor whose speed of rotation is proportional to the flow rate. As the wheel rotates a voltage is produced which indicates the flow rate. Displacement flow meters measure the flow rate of a liquid by separating the flow into known volumes and counting them over time. These meters provide good accuracy. Displacement flow meters have several types such as sliding vane meters, rotary piston meters, helix flow meters and so on.
● 33
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 33
11/10/2022 13:54
PID-based Practical Digital Control
Magnetic flow meters are based on Faraday's law of magnetic induction. Here, the liquid acts as a conductor as it flows through a pipe. This induces a voltage which is proportional to the flow rate. The faster the flow rate, the higher is the voltage. This voltage is picked up by the sensors mounted in the meter tube and electronic means are used to calculate the flow rate based on the cross-sectional area of the tube. The advantages of magnetic flow rates are as follows: • Corrosive liquids can be used. • The measurement does not change the flow stream. • Corrosive liquids can be used. The e-Tape Liquid Level Sensor (Figure2.22) is a low-cost solid-state sensor with a resistive output that varies with the level of the fluid and it is used in liquid level control applications as liquid level sensor. The sensor's resistive output is inversely proportional to the height of the liquid: the lower the liquid level, the higher the output resistance; the higher the liquid level, the lower the output resistance. The length and width of the sensor are 257 mm and 25.4 mm respectively. Sensor output is 1500 Ω when empty, and 300 Ω when full. The resolution of the sensor is 0.25 mm.
Figure 2.22: e-Tape liquid level sensor. The LV170 device from Omega is a liquid sensor switch (Figure 2.23) based on optical technology. This electro-optical sensor contains an infrared LED and a light receiver. Continuous light from the LED is directed into a prism which forms the tip of the sensor. With no liquid present, light from the LED is reflected within the prism to the receiver. When a rising liquid immerses the prism, the light is refracted out into the liquid, leaving little or no light to reach the receiver. Sensing this change, the receiver actuates electronic switching within the unit to operate an external alarm or control circuit.
Figure 2.23: The LV170 liquid sensor switch. The low-cost float switch (Figure 2.24) can be mounted at the edge of a tank and used to detect the level of liquid in a tank. The switch provides normally-open/normally-closed
● 34
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 34
11/10/2022 13:54
Chapter 2 • Sensors
contacts so that external equipment can be switched on or off depending on the level of the liquid.
Figure 2.24: Liquid float switch. The mini liquid level sensor (Figure 2.25) from Parallax can be used to detect water level in a small tank by inserting it vertically into the tank. Liquid levels from 0 to 48mm can be detected by the sensor. The sensor has 2 to 5 V analog output and therefore ADC is needed to connect it to a microcontroller. With an operating voltage of 2 to 5 V, the sensor can be used in non-toxic, non-corrosive liquids such as water.
Figure 2.25: Mini liquid level sensor.
2.8 Flow Sensors Flow sensors are used to measure the flow rate of liquid, gas, or air. For example, a liquid or gas flow rate sensor measures the rate of liquid or gas passing through a pipe. The low-cost YF-S201 can be used to measure the liquid flow rate (Figure 2.26). This sensor operates with 5 to 18 V and provides TTL output with 450 pulses per liter. The range of the sensor is 1 to 30 liters/minute, with an accuracy of ±10%. This sensor can directly be connected to the Arduino. Connection to Raspberry Pi required the output voltage to be dropped to 3.3 V, e.g., using a resistive potential divider circuit.
● 35
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 35
11/10/2022 13:54
PID-based Practical Digital Control
Figure 2.26: YF-S201 liquid flow rate sensor. The FT-210 series is also a popular liquid flow rate sensor, although more expensive than the YF-S201. This sensor operates with 5 to 24V and provides open-collector output with 22,000 pulses/liter, at an accuracy of ±3% of reading.
Figure 2.27: The FT-210 liquid flow rate sensor. The Renesas type FS2012 sensor can be used to measure the flow rate of both liquid and gas (Figure 2.28). Operating at 5 V, the sensor output is 0 to 5 V analog or I2C digital. It is resistant to vibration and pressure shock. Gas flow range of the sensor is 0.015 to 2 SLPM (Standard Liters Per Minute), with a flow accuracy of ±2% of the reading. Liquid flow range is 0.025 to 0.5 SLPM, with an accuracy of ±2% of the reading.
Figure 2.28: The FS2012 gas/liquid flow rate sensor.
● 36
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 36
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
Chapter 3 • Transfer Functions and Time Response 3.1 Overview In the previous Chapter, you had a look at some of the sensors that can be used in microcontroller based digital control applications. In this Chapter, you will learn the theory and time response of the first-order and second-order systems. They are important as most control structures can be reduced to simple first or second-order systems. The aim of this book is to minimize the theory and mathematical derivation as much as possible, and yet learn the fundamental properties and the design of microcontroller based control. In this Chapter, only continuous-time systems are considered since it is necessary to learn the fundamental aspects of continuous-time systems before moving to digital systems. Digital systems will be covered in a later Chapter.
3.2 First-order Systems Example 1 Let's consider a simple electrical system consisting of a resistor (R) and an inductor (L) as shown in Figure 3.1, where v(t) is the applied voltage and i(t) is the current in the circuit.
Figure 3.1: Electrical system with R and L. You can write the loop equation as a differential equation:
(3.1) Taking the Laplace transform with the initial conditions, you have
(3.2) With zero initial conditions, the transfer function relating the current to the applied voltage is given by:
(3.3)
● 37
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 37
11/10/2022 13:54
PID-based Practical Digital Control
or
(3.4) Figure 3.2 shows the open-loop block diagram of the system with V(s) as input and I(s) as output.
Figure 3.2: Open-loop block diagram. Example 2 Let's now consider a liquid level system (Figure 3.3) where liquid enters a tank at the rate of qi and leaves at the rate of qo through an orifice. Derive the mathematical model for the system, showing the relationship between the height h of the liquid and the input flow rate qi.
Figure 3.3: Liquid level control. Assuming V is the volume and A is the area of the liquid tank,
(3.5) or
(3.6)
● 38
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 38
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
But the pressure in a tank is given by: (3.7) Hence, (3.6) becomes:
(3.8) If R is the hydraulic resistance. (3.9) So that
(3.10) Substituting in (3.8) gives
(3.11) Taking the Laplace transform gives:
(3.12) And the transfer function can be written as:
(3.13) or conclusively:
(3.14)
3.2.1 Time Response Notice that equation (3.4) and (3.14) are very similar since they are both first-order systems. In general, you can write the transfer function of a first-order open-loop system as follows:
● 39
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 39
11/10/2022 13:54
PID-based Practical Digital Control
(3.15) If you now apply a unit step input R(t) to the system, where R(s) = 1/s, the Laplace transform of the overall open-loop system C(s) becomes:
(3.16) The time response of the open-loop system is given by taking the inverse Laplace transform of (3.16), which gives: (3.17) The response is clearly an exponential rise. Initially at t = 0, system output c(t) = 0. The output then rises to 1 in an exponential manner. Parameter 1/a is known as the time constant of the system. At t = 1/a, the response becomes: (3.18) You can therefore say that when a step input is applied to a first-order system, the system output rises to 63% of its final value at the time equal to the time constant of the system. Notice that the time constant 1/a has the unit of time. Figure 3.4 shows the output response of the system graphically.
Figure 3.4: Output response of a first-order system.
● 40
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 40
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
In reference to Figure 3.4, you can write the following: • The response rises exponentially from 0 to 1. • The initial slope can be used to find the time constant 1/a. find the point of intersection of the initial slop and final value and then read the time constant from the horizontal axis. • The rise time Tr is the point where the response rises to 90% of its final value, and is given by: Tr = 2.2/a. • The settling time Ts is defined the time where the final response settles within 2% of its final value, and is given by: Ts = 4/a. Question The transfer function of a first-order system is given by:
Calculate the time response if a unit step input is applied to the system. Solution With a unit step input the open-loop transfer function is:
or
From inverse Laplace transform tables, you find that the time response is given by:
At t = 0 the output is 0, and the final value of the output is (for very large t) equal to K/a. Question The unit step time response of a first-order system is found to be as shown in Figure 3.5. Calculate the transfer function of this system.
● 41
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 41
11/10/2022 13:54
PID-based Practical Digital Control
Figure 3.5: First-order system response. Solution The final value of the system is clearly 2.5. Time constant is when the curve reaches 63% of its final value. Therefore, the time constant occurs at the y axis point 2.5 × 0.63 = 1.575. Drawing a horizontal line from this point, you find on the horizontal axis that the time constant is 1/a = 0.25. Therefore, a = 1/0.25 = 4. You now have to find K. The final value is K/a = 2.5, therefore K = 4 × 2.5 = 10. The required transfer function of the system is:
Question The unit step time response of a first-order system is found to be as shown in Figure 3.6, where the initial value of the output is 4. Calculate the transfer function of this system.
Figure 3.6: First-order system response.
● 42
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 42
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
Solution The final value of the system is 9, where its initial value is 4. The time constant occurs when the curve reaches 63% of its final value, i.e., at the y axis point 4 + (9 – 4) × 0.63 = 7.15. Drawing a horizontal line from this point, you find that the time constant on the horizontal axis is 1/a = 0.5. Therefore, a = 1/0.5 = 2. You now have to find K. The final value is K/a = (9 – 4), therefore K = 5 × 2 = 10. The required transfer function of the system is:
3.3 Second-order Systems Example 1 Consider the mechanical system shown in Figure 3.7, consisting of a mass, spring, and dashpot, where force F is applied to the system.
Figure 3.7: Mechanical system with mass, spring, and dashpot. The net force on the mass is the applied force minus the forces exerted by the spring and the dashpot. Applying Newton's second law, you can write:
(3.19) or,
(3.20) Taking the Laplace transform gives:
The transfer function is then given by:
(3.21)
● 43
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 43
11/10/2022 13:54
PID-based Practical Digital Control
Which is usually written in the standard form as a second-order open-loop system transfer function:
(3.22) Example 2 Consider the electrical system given in Figure 3.8, consisting of a resistor (R), inductor (L), and a capacitor (C). Let's derive the model of this system.
Figure 3.8: Electrical circuit. Applying Kirchhoff's voltage law, you can write: (3.23) or,
(3.24) For the capacitor, you can write
(3.25) Substituting into (3.24), you obtain
(3.26) Taking the Laplace transform gives
● 44
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 44
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
The transfer function is therefore given by:
Which can be written in the form:
(3.27) Equation (3.27) is similar to (3.22) as both systems are second-order. In fact, the general form of a second-order open-loop transfer function is of the following format:
(3.28) Where,
is the natural frequency and
is the damping ratio.
3.3.1 Time Response You will now investigate the output response of a second-order system when a unit step input is applied. There four solutions to equation (3.28) depending on the value of the damping ratio. Case 1:
Undamped
This is an oscillatory response. Case 2:
Critically damped
This is an exponentially rising response. Case 3:
Overdamped
Case 4:
Underdamped
● 45
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 45
11/10/2022 13:54
PID-based Practical Digital Control
Where,
is the damped natural frequency
and Figure 3.9 shows the time response for all four cases.
Figure 3.9: Time response of a second-order system. In controlling a plant, you are mainly interested in the underdamped case where the damping ratio is less than one. As shown in Figure 3.10, as the damping ratio gets smaller you get higher overshoots in the response. You should aim for a damping ratio of about 0.7 whish gives a very slight overshoot and a fast rise time.
Figure 3.10: Second-order system response as damping ratio changes. Some important parameters that define a second-order underdamped response are given below (see Figure 3.11)
● 46
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 46
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
Figure 3.11: Second-order system parameters. Peak time (Tp) : This is the time required for the system response to reach its first overshoot and is given by:
Rise time (Tr): This is the time required for the system to reach the final value first time. It is given by:
where Maximum overshoot (Mp): This is the difference between the maximum overshoot and the final value, given by:
Settling time (ts): This is the time required for a response to become steady. It is usually defined as the time required by the response to reach within specified range of 2% to 5% of its final value, given by:
to 2%
to 5%
● 47
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 47
11/10/2022 13:54
PID-based Practical Digital Control
Example Given the following open-loop transfer function of a system with unit step input applied, calculate the Tp, Tr, Mp, and ts to 2%.
Solution is 10,
is 10, or
is 0.5
Therefore:
or
seconds
or
B = 59.9
degrees or 1.045 radians
seconds
or 16.3%
seconds
Hence,
seconds,
seconds,
,
seconds.
Example Sometimes you have a DC gain and the transfer function (3.28) becomes:
● 48
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 48
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
An example is given below. Draw the unit step time response for the following two transfer functions:
and Solution Figure 3.12 shows the two step functions next to each other. Notice that in the second response the gain is 4 and therefore the final state of the time response settled at 4.
Figure 3.12: Step responses. Example The unit step time response of a second-order system is shown in Figure 3.13. Derive the transfer function of this system.
Figure 3.13: Unit step time response. Solution In reference to Figure 3.14, you can read the following:
● 49
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 49
11/10/2022 13:54
PID-based Practical Digital Control
Figure 3.14: Finding the parameters. seconds
Therefore,
, which gives
Also,
, which gives
And
, hence
, or
The required transfer function is:
or
3.4 Time Delay In some systems, especially in thermal systems the response of the system is slow when an input is applied and it takes some time for the output to change. This is called time delay and is represented with the following transfer function:
● 50
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 50
11/10/2022 13:54
Chapter 3 • Transfer Functions and Time Response
Where T is the delay in seconds. As an example, the transfer function of a first-order system with time delay is given below.
Figure 3.15 shows the unit step response of this system.
Figure 3.15: Step response with time delay.
3.5 Transfer Function of a Closed-loop System A control system may include a number of blocks interconnected together. In this section you will derive the transfer function of a basic feedback control system. Figure 3.16 shows the block diagram of a feedback control system with the forward transfer function G(s) and the feedback transfer function H(s), and input and outputs I(s) and O(s), respectively. It can be shows that the transfer function of this closed-loop system is given by:
Figure 3.16: Feedback control system.
● 51
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 51
11/10/2022 13:54
PID-based Practical Digital Control
When the blocks are in series to each other you can multiply them to find the overall transfer function (interested readers can find lots of information on the Internet on block diagram manipulation). Example Find the overall transfer function of the system shown in Figure 3.17.
Figure 3.17: Block diagram of the example system. Solution The overall transfer function is given by:
● 52
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 52
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
Chapter 4 • Discrete Time (Digital) Systems 4.1 Overview A digital system operates on discrete-time rather than continuous-time signals. A digital computer (e.g. a microcontroller) is used as the controller in such a system. A DAC converter is usually connected to the output of the computer to drive the plant. Let's assume that all the signals enter and leave the computer at the same fixed times, known as the sampling times. A typical sampled data control system is shown in Figure 4.1. The digital computer performs the controller or the compensation function within the system. The ADC converts the error signal, which is a continuous signal, into digital form so that it can be processed by the computer. At the computer output the DAC converts the digital output of the computer into a form which can be used to drive the plant. It is also common to use some form of power amplifier circuit before the plant in electrical systems such as electromechanical motors.
Figure 4.1: A digital control system.
4.2 The Sampling Process An ADC is used as a sampler which is basically like a switch that closes every T seconds, as shown in Figure 4.2. When a continuous signal r(t) is sampled at regular intervals T, the resulting discrete-time signal is shown in Figure 4.3, where q represents the amount of time the switch is closed. Notice that signal r(t) is shown as r*(t) after it is sampled. In practice the closure time q is much smaller than the sampling time T, and the pulses can be approximated by flat-topped rectangles as shown in Figure 4.4. In control applications the switch closure time q is much smaller than the sampling time T and can be neglected. This leads to the ideal sampler with output as shown in Figure 4.5.
Figure 4.2: A sampler.
● 53
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 53
11/10/2022 13:54
PID-based Practical Digital Control
Figure 4.3: Signal r(t) after the sampling operation.
Figure 4.4: Sampled signal with flat-topped pulses.
● 54
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 54
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
Figure 4.5: Signal r(t) after ideal sampling. A DAC converts the sampled signal r ∗(t) into a continuous signal y(t). The DAC can be approximated by a zero-order hold (ZOH) circuit as shown in Figure 4.6. This circuit remembers the last information until a new sample is obtained, i.e. the zero-order hold takes the value r(nT) and holds it constant for nT ≤ t < (n + 1)T, and the value r(nT) is used during the sampling period.
Figure 4.6: A sampler and zero-order hold. A sampler and zero-order hold can accurately follow the input signal if the sampling time T is small compared to the transient changes in the signal. The response of a sampler and a zero-order hold to a ramp input is shown in Figure 4.7 for two different values of sampling period.
● 55
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 55
11/10/2022 13:54
PID-based Practical Digital Control
Figure 4.7: Response of a sampler and a zero-order hold for a ramp input. Example Figure 4.8 shows an ideal sampler followed by a zero-order hold. Assuming the input signal r(t) is as shown in the figure, show the waveforms after the sampler and also after the zero-order hold.
Figure 4.8: Ideal sampler and zero-order hold. Solution The signals after the ideal sampler and the zero-order hold are shown in Figure 4.9.
Figure 4.9: Solution of the example.
● 56
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 56
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
4.3 The Z-Transform The z-transform is used in manipulating, designing and testing digital systems just like the Laplace transform is used in continuous-time systems. The z-transform of the function r (t) is Z [r (t)] = R(z) and is given by:
(4.1) Notice that the z-transform consists of an infinite series in the complex variable z, and (4.2) are the coefficients of this power series at different sampling instants. The rei.e. sponse of a sampled data system can be determined easily by finding the z-transform of the output and then calculating the inverse z-transform.
4.3.1 Unit step function Consider a unit step function as shown in Figure 4.10, defined as:
From (4.1),
or,
for
Figure 4.10: Unit step function.
● 57
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 57
11/10/2022 13:54
PID-based Practical Digital Control
4.3.2 Unit ramp function Consider a unit ramp function as shown in Figure 4.11, defined as:
From (4.1),
Or,
for
Figure 4.11: Unit ramp function.
4.3.3 Tables of z-Transforms A table of z-transforms for the commonly used functions is freely available on the Internet. As with the Laplace transforms, you are interested in the output response y(t) of a digital system and you must find the inverse z-transform to obtain y(t) from Y(z).
4.4 The z-Transform of a function expressed as a Laplace Transform It is important to realize that although you denote the z-transform equivalent of G (s) by G (z), G (z) is not obtained by simply substituting z for s in G (s). You can use one of the following methods to find the z-transform of a function expressed in Laplace transform format: Given G (s), calculate the time response g(t) by finding the inverse Laplace transform of G(s). Then find the z-transform either from the first principles, or by looking at the z-transform tables. Given G(s), find the z-transform (z) by looking at the tables which give the Laplace transforms and their equivalent z-transforms.
● 58
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 58
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
Example Let
Determine
by the methods described above.
Solution 1 - By finding the inverse Laplace transform You can express G(s) as a sum of its partial fractions:
The inverse Laplace transform of this transfer function is given by:
From the z-transform tables you obtain:
or,
Solution 2 - By using the z-transform transform tables for the partial product
From the z-transform tables, the z-transform of
is
. Therefore,
or,
● 59
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 59
11/10/2022 13:54
PID-based Practical Digital Control
4.5 Inverse z-Transforms The inverse z-transform is obtained in a similar way to the inverse Laplace transforms. Generally, the z-transforms are the ratios of polynomials in the complex variable z, with the numerator polynomial being of order no higher than the denominator. By finding the inverse z-transform you find the sequence associated with the given z-transform polynomial. As in the case of inverse Laplace transforms, you are interested in the output time response of a system. Therefore, you use an inverse transform to obtain y(t ) from Y (z). There are several methods to find the inverse z-transform of a given function as described below: • Power series (long division); • Expanding Y (z) into partial fractions and using z-transform tables to find the inverse transforms; • Obtaining the inverse z-transform using an inversion integral. In this section you will look at an example using the power series method. This method involves dividing the denominator of Y (z) into the numerator. Example Find the inverse z-transform (time function) for the following transfer function:
Solution Dividing the denominator into the numerator is shown in Figure 4.12.
Figure 4.12: Dividing the denominator into numerator.
● 60
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 60
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
The coefficients of the power series are:
The required output time sequence is:
Where
represent delay by T samples.
Figure 4.13 shows the first few samples of the time sequence y(t).
Figure 4.13: First few samples of y(t).
4.6 Pulse transfer function and manipulation of block diagrams The pulse transfer function is the ratio of the z-transform of the sampled output and the input at the sampling instants. Suppose you wish to sample a system with output response given by:
As illustrated in Figure 4.14. You sample the output signal to obtain:
or,
● 61
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 61
11/10/2022 13:54
PID-based Practical Digital Control
Figure 4.14: Sampling a system.
4.6.1 Open-loop systems An example of manipulating the open-loop block diagram is given in this section. Example Figure 4.15 shows an open-loop digital system. Derive an expression for the z-transform of the output of the system, where
and
Figure 4.15: Open-loop system. Solution The following expressions can be written for the system:
or,
and, where, substituting the values gives:
from z-transform tables you obtain:
● 62
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 62
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
and the z-transform of the output is given by:
4.7 Open-loop time response The open-loop time response of a digital system can be obtained by finding the inverse z-transform of the output function. Two examples are given below. Example A unit step signal is applied to the electrical RC system shown in Figure 4.16. Calculate and draw the output response of the system, assuming a sampling period of T = 1 s.
Figure 4.16: RC system with unit step input. Assume that the transfer function of the RC system is:
Solution For this system you can write:
and giving
the z-transform of a unit step function is
and the z-transform of G(s) is
● 63
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 63
11/10/2022 13:54
PID-based Practical Digital Control
thus, the output z-transform is given by:
T = 1 s and e-1 = 0.368, you get
The output time response is obtained by finding the inverse z-transform of y(z). You can either use an inverse z-transform table, divide the numerator by the denominator, or find the partial fractions as follows:
Calculating A and B you find:
And finally, From the inverse z-transform tables you find the time function as:
The first few output samples are:
And the output time response is (see Figure 4.17) given by:
● 64
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 64
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
It is important to notice that the response is only known at the sampling instants. For example, in Figure 4.17 the capacitor discharges through the resistor between the sampling instants, and this causes an exponential decay in the response between the sampling intervals. But this behaviour between the sampling instants cannot be determined by the z-transform method of analysis.
Figure 4.17: RC system output response. Example Assume that the system in Example 4.16 is used with a zero-order hold (see Figure 4.18). What will the system output response be if a unit step input is applied.
Figure 4.18: RC system with zero-order hold. Solution The transfer function of the zero-order hold is
And that of the RC system is
For this system you can write
And or, taking the z-transforms.
● 65
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 65
11/10/2022 13:54
PID-based Practical Digital Control
Now, T = 1 s and
Which can be written as: From the z-transform tables you find that
For a unit step input, And the system output response becomes
From inverse z-transform tables you find that
Where a is the unit step function. Thus
The time response is shown in Figure 4.19
● 66
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 66
11/10/2022 13:54
Chapter 4 • Discrete Time (Digital) Systems
Figure 4.19: Step input response of the system.
4.8 Closed-loop system time response An example of manipulating the closed-loop system block diagram is given in this section. Example A unit step signal is applied to the sampled data digital system shown in Figure 4.20. Calculate and plot the output response of the system. Assume that T = 1 s.
Figure 4.20: Closed-loop system.
Solution The transfer function of the system is found as
Or
e*(s)=r*(s)-G*(s)e*(s)
Solving for e*(s) , you obtain
● 67
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 67
11/10/2022 13:54
PID-based Practical Digital Control
And therefore The z-transform of the output is given by
In our example,
and
Therefore, the output z-transform is
Simplifying and setting T = 1 gives:
After long division of the numerator to the denominator gives
The first 10 samples of the output response are shown in Figure 4.21
Figure 4.21: First 10 output samples.
● 68
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 68
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Chapter 5 • The PID Controller in Continuous-Time Systems 5.1 Overview A PID controller (sometimes called three-term controller) is an algorithm that is widely used in industrial process control systems, and in many other control systems where zero error is required in the final system output. It is important to realize that PID is not the only controller type used in control systems. There are many other types such as lead, lag, lead-lag, pole assignment, dead-beat, Dahlin, etc. In a PID control algorithm, the controller receives the error value which is the difference between the desired and the actual measured value, and then applies correction to the plant in order to force the error value to zero and obtain a successful, stable response. In PID control, P is the proportional control action, I is the integral control action, and D is the derivative control action. As you will learn in this Chapter, P is proportional to the error and if the error is large then the value applied to the plant will also be large. Using proportional control on its own results in error between the desired and the actual measured values. Integral action provides an integral of the error value over time to the plant. As a result, any error value will be eliminated and the integral term will cease to grow. The objective of using the integral control action is to force the error value to zero. Derivative action provides the derivative of the error value to the plant. This action tends to reduce the error value as well as the inevitable overshoot. The derivative action is not used in all systems. The continuous-time PID controller is expressed mathematically as follows:
Where, u(t) is the controller output, and e(t) is the error value which is input to the controller. Also, Kp, Ki, and Kd are known as the proportional, integral, and derivative constants of the PID controller. The Laplace transform of the PID controller is:
(5.1)
or
(5.2)
● 69
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 69
11/10/2022 13:54
PID-based Practical Digital Control
Sometimes the PID controller is expressed in an alternative way:
(5.3) One of the problems in PID controller design is tuning the values of the P, I, and D coefficients or parameters (Kp, Ki, and Kd) so that the required output response is obtained from the system. There are many methods for doing this and you will explore some popular ones in this Chapter. In the remaining sections of this Chapter, you will discover details of the PID controller by using it with a first-order continuous-time system.
5.2 Proportional-only Controller with a First-Order System Consider the first order closed-loop system shown in Figure 5.1 with this proportional-only controller transfer function:
and the plant transfer function:
Figure 5.1: First-order closed-loop system with proportional only controller. The closed-loop transfer function is given by:
giving
Which has the time constant 1/11 = 0.09. The closed-loop system without the proportional only controller had the time constant 1/2 = 0.5. You can see that with the proportional only controller the time constant has decreased. i.e., the system response became faster. Figure 5.2 shows the unit time response of the closed-loop system with and without the proportional only controller. It is also interesting to notice that there is steady state error in system response with proportional only controller. i.e., the final state of the system is at
● 70
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 70
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
0.9 and not 1.0. You can reduce the error with larger proportional constant Kp but this will require very large value (theoretically infinite value).
Figure 5.2: Unit step response with and without controller.
5.3 Integral-Only Controller with a First-order System Let's look at the first-order closed-loop system shown in Figure 5.3 with this integral-only controller transfer function:
and the plant transfer function
.
Figure 5.3: First-order closed-loop system with integral only controller. The closed-loop transfer function:
giving
Figure 5.4 shows the unit step, closed-loop system response with and without the integral-only controller. It is interesting to note that the closed-loop system response with the integral-only controller is fast but exhibits overshoots. Also, there is no steady state error, i.e., the final state of the system is at 1.0. The overshoot can be reduced by reducing the integral amount. Figure 5.5 shows the response when the integral controller is 0.5/s. Notice that the overshoot is reduced considerably and also the steady state error is zero. You can
● 71
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 71
11/10/2022 13:54
PID-based Practical Digital Control
conclude here that integral action is very important in systems where you want the steady state error to be zero.
Figure 5.4: Unit step response with and without controller.
Figure 5.5 System response with the integral-only controller set to 0.5/s.
5.4 Derivative-only Controller with a First-order System Consider the first-order closed-loop system shown in Figure 5.6 with the integral-only controller transfer function:
and the plant transfer function:
● 72
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 72
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Figure 5.6: First-order closed-loop system with derivative-only controller. The closed-loop transfer function is given by:
giving Figure 5.7 shows the closed-loop system response. Notice that the derivative action does not track the error. Instead, it tracks the rate of change of the error and is not useful on its own.
Figure 5.7: Unit step response with derivative-only.
5.5 Proportional + Integral Controller with a First-order System View the first-order closed-loop system shown in Figure 5.8 with the proportional and integral controller transfer function:
and the plant transfer function:
.
● 73
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 73
11/10/2022 13:54
PID-based Practical Digital Control
Figure 5.8: First-order, closed-loop system with proportional+integral controller. The closed-loop transfer function is given by:
giving Figure 5.9 shows the closed-loop unit step response with and without the controller. Notice that this is an acceptable response since there is little overshoot and the steady state error is zero.
Figure 5.9: First-order, closed-loop system response with and without P+I controller.
5.6 Proportional + Integral + Derivative controller with a First-order System You will now add derivative action to our controller. Consider the first-order closed-loop system shown in Figure 5.10 with the PID controller transfer function:
and the plant transfer function:
.
● 74
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 74
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Figure 5.10: First-order, closed-loop system with proportional+integral+derivative controller. The closed-loop transfer function is given by:
giving Figure 5.11 shows the system response with the PID in action. Compare this response with Figure 5.9. Notice that by adding a derivative action, the system now has slightly higher overshoot and higher rise time meaning you have not gained a better response. The importance of setting the PID parameters is very important as you have seen in these example plots. This is called tuning the controller and you will look at different methods of tuning a system.
Figure 5.11: First-order closed-loop unit step response with PID controller.
5.7 Effects of Changing the PID Parameters You will now use the system with transfer functions as given in the previous section and examine the effects of changing the PID parameters. The system's closed-loop transfer function is:
● 75
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 75
11/10/2022 13:54
PID-based Practical Digital Control
and with the PID transfer function:
The closed-loop unit step time response with the above parameters is pictured in Figure 5.12a. It shows the response after doubling Kp. PID parameters were put back to what they were and Figure 5.12c shows the response after Ki is doubled. Finally, the parameters were put back to what they were again and Figure 5.12d is the response after Kd is doubled. Notice that the steady state error is zero in all cases. Increasing the integral parameter makes the system faster but at the same time oscillatory before it settles down.
Figure 5.12: Effects of changing the PID parameters.
5.8 Tuning a PID Controller One of the commonly used methods for tuning the PID parameters is known as the Ziegler and Nichols tuning method. This method can be applied to both open-loop and closed-loop systems. The method involves observing the unit time response of a system and then estimating the PID parameters based on the time response.
● 76
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 76
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
You will use the following form of the PID controller in tuning the controller:
which has the transfer function:
5.8.1 Open-loop Ziegler and Nichols Tuning For open-loop tuning, you first find the plant parameters by applying a step input to the open-loop system. The plant parameters Kp , Td and Ti are then found from the result of the step test as shown in Figure 5.13. Notice that TD is the time delay of the system (see section 3.4). You can also use the method described in Chapter 3 to find the open-loop transfer function of a system from its unit step time response. The transfer function of the system is then found to be:
Ziegler and Nichols then suggest using the PID controller settings given in Table 5.1 when the loop is closed. These parameters are based on the concept of minimizing the integral of the absolute error after applying a step change to the set-point. An example is given here to illustrate the method used.
Figure 5.13: Finding the plant parameters. The Ziegler and Nichols method has these advantages: • simple to implement • very little knowledge required about the system dynamics
● 77
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 77
11/10/2022 13:54
PID-based Practical Digital Control
On the down side: • response results in large (25%) overshoot • tuning is sensitive to system dynamics, especially to the delay time • tuning is sensitive to non-linearities
5.8.2 Open-loop Cohen-Coon PID Tuning This method is based on the Ziegler and Nichols method but provides significantly better control performance especially for systems with large delay times. The settings of the Cohen-Coon tuning are as shown in Table 5.1.
Table 5.2: Cohen-Coon PID tuning settings. Where L is the delay time, T is the system time constant, and Kprocess is the gain of the process. This method can only be used offline. Cohen-Coon tuning has these advantages: • works well with systems with large delay time • gives quicker response than the Ziegler and Nichols method Example Figure 5.14 shows the open-loop unit step time response of a system with time delay. Your task is to derive the Ziegler and Nichols tuning parameters for this system and draw the time response of the closed system with the PI controller. Soluti on With reference to Figure 5.14, the open-loop system parameters are given as follows:
K = 10,
TD = 2, T1 = 4
● 78
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 78
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Therefore, the open-loop system transfer function is:
With reference to Table 5.1, the PI parameters are:
Figure 5.14: Open-loop time response. The required PI transfer function is:
The block diagram of the system is shown in Figure 5.15.
Figure 5.15: Block diagram of the system.
● 79
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 79
11/10/2022 13:54
PID-based Practical Digital Control
The unit step time response of the closed-loop system is shown in Figure 5.16. Notice that the system has high overshoot which is the characteristic of the design using Ziegler & Nichol method. If you reduce Kp to 0.15 the transfer function of the controller becomes:
And the closed-loop system response becomes as shown in Figure 5.17.
Figure 5.16: Unit step time response of the closed system.
Figure 5.17: System response with reduced Kp. There are several other PID tuning algorithms used in practice, such as modified Ziegler and Nichols, Lambda, Chien-Hrones-Reswick, the Tyreus-Luyben method, Ciancone-Marline method, Internal Model Control (IMC), and others. You will now proceed to designing a Lambda type controller for your example system.
● 80
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 80
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Example Let's design a Lambda PI controller for the plant whose transfer function is found to be:
Solution Like the Ziegler and Nichols tuning, lambda tuning involves a set of formulas or tuning rules that dictate the values of the PI parameters required to achieve the desired controller performance. The tuning rules for the Lambda PI controller are as follows:
Where is the process time constant. In order to obtain a closed-loop system with a non-oscillatory setpoint response that will settle out in approximately 4λ seconds. These tuning rules require the user to specify only one performance parameter: λ. This simplifies the calculations considerably. In or example,
K=10 and
Setting
(i.e.,
which gives
) you find: and
The transfer function of the PI controller then becomes: The closed-loop system response with this controller is shown in Figure 5.18.
● 81
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 81
11/10/2022 13:54
PID-based Practical Digital Control
Figure 5.18: Closed-loop time response. Lambda tuning has the following advantages: • • • •
works well for systems with large delay time largely insensitive to system non-linearities response has no overshoot the closed-loop time constant can be chosen
The disadvantages of the Lambda tuning are: • only available for PI type controllers • slow rejection of disturbances
5.8.3 Closed-loop Tuning The Ziegler & Nichols closed-loop tuning algorithm is based on plant closed-loop tests. The procedure is as follows: • Disable any derivative and integral action in the controller and leave only the proportional action. • Carry out a set-point step test and observe the system response. • Repeat the set-point test with increased (or decreased) controller gain until a stable oscillation is achieved (see Figure 5.19). This gain is called the ultimate gain, Ku. • Read the period of the steady oscillation and define it as Pu. • Calculate the controller parameters according to the following formulae: Kp = 0.45Ku, Ti = Pu/1.2 in the case of the PI controller; and Kp = 0.6Ku, Ti = Pu/2, Td = Tu/8 in the case of the PID controller.
● 82
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 82
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Figure 5.19: Ziegler and Nichols closed-loop test. Example Let's go ahead and design a PI controller for a system whose open-loop transfer function is given by:
Solution Increasing the gain of the system, you find that the system output starts to oscillate when the gain is 3.803. The period of the oscillations was found to be 7.5 seconds (Figure 5.20).
Figure 5.20: System oscillating with increased gain.
Therefore,
, and
Therefore, from the Ziegler and Nichol settings, and
● 83
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 83
11/10/2022 13:54
PID-based Practical Digital Control
The transfer function of the PI controller is: Figure 5.21 shows the closed-loop time response of the system. There is about 18% overshoot in the response which is expected from the Ziegler and Nichol type tuning.
Figure 5.21: Closed-loop time response of the system. Note that most systems can easily be controlled using just the PI controller without the derivative action. The derivative action is exceedingly sensitive to noise and it must not be used unless the system time constant is very slow. Filters are commonly used with the derivative action to cancel out the noise.
5.8.4 Practical PID Tuning In most cases, you can tune a PID system by performing some practical observations. The steps are: • Use only Proportional Control (set the integral and derivative to zero) and apply step input to the system. Vary the proportional parameter until a good response is obtained. Then decrease the proportional parameter slightly. • Keep the proportional parameter found and now vary the integral parameter until a good response is obtained and the steady state error is zero. • Keep the proportional and integral parameters found and vary the derivative parameter until a good response is obtained. It is interesting to note that most systems do not require the derivative action. Figure 5.22 shows how a system can be tuned practically.
● 84
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 84
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
Figure 5.22: Effect of PID parameter changes.
5.9 The Auto-tuning PID Controller Many controller manufacturers nowadays offer intelligent PID controllers which can automatically tune themselves depending on the plant characteristics to find the optimum controller parameters.
5.10 Increasing and Decreasing PID Parameters The effects of increasing the PID parameters are summarized in Table 5.3. Response
Rise Time
Overshoot
Settling Time
SS Error
Kp
Decrease
Increase
No change
Decrease
Ti
Increase
Decrease
Decrease
Eliminate
Td
No change
Decrease
Decrease
No change
Table 5.3: Effect of increasing the PID parameters.
5.11 Saturation and Integral Wind-up In practical applications, the output value of a control action is limited by physical constraints. For example, the maximum voltage output from a device is limited. Similarly, the maximum flow rate that a pump can supply is limited by the physical capacity of the pump.
● 85
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 85
11/10/2022 13:54
PID-based Practical Digital Control
As a result of this physical limitation, the error signal does not return to zero and the integral term keeps adding up continuously. This effect is called integral wind-up (or integral saturation). As a result of it, long periods of overshoot can occur in the plant response. A simple example of what happens is the following. Suppose you wish to control the position of a motor and a large setpoint change occurs, resulting in a large error signal. The controller will then try to reduce the error between the set-point and the output. The integral term will grow by summing the error signals at each sample and a large control action will be applied to the motor. But because of the physical limitation of the motor electronics, the motor will not be able to respond linearly to the applied control signal. If the set-point now changes in the other direction, then the integral term is still large and will not respond immediately to the set-point request. Consequently, the system will have a poor response when it comes out of this condition. The integral wind-up problem affects positional PID controllers. With velocity PID controllers, the error signals are not summed up and as a result integral wind-up will not occur, even though the control signal is physically constrained. Many techniques have been developed to eliminate integral wind-up from the PID controllers, and some of the popular ones are as follows: • Stop the integral summation when saturation occurs. This is also called conditional integration. The idea is to set the integrator input to zero if the controller output is saturated and the input and output are of the same sign. • Fix the limits of the integral term between a minimum and a maximum.
• Reduce the integrator input by some constant if the controller output is saturated. Usually, the integral value is decreased by an amount proportional to the difference between the unsaturated and saturated (i.e., maximum) controller output. • Use the velocity form of the PID controller.
5.12 Derivative Kick Another possible problem when using PID controllers is caused by the derivative action of the controller. This may happen when the set-point changes sharply, causing the error signal to change suddenly. Under such a condition, the derivative term can give the output a kick, known as a derivative kick. This is usually avoided in practice by moving the derivative term to the feedback loop. The proportional term may also cause a sudden kick in the output and it is common to move the proportional term to the feedback loop.
5.13 Using the PID Loop Simulator The PID Loop Simulator from the website Engineers-Excel.com is a very useful computer-aided to properly simulate processes with PID controllers. It is invaluable for tuning the PID parameters of a given system. The simulator can be used after you obtain the openloop transfer function of our system from a step-input time response.
● 86
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 86
11/10/2022 13:54
Chapter 5 • The PID Controller in Continuous-Time Systems
The PID Loop Simulator software application for PC is available free of charge from the following website: https://view.officeapps.live.com/op/view.aspx?src=http%3A%2F%2Fwww.engineersexcel.com%2FApps%2FPID_Simulator%2FPID_scrollbar.xls&wdOrigin=BROWSELINK Figure 5.23 shows the PID Loop Simulator software application. In the middle part of the screen, the general simulation block diagram is shown with the PID controller and a first-order plant with time delay. The transfer function of the plant (gain, time constant, and delay time) are entered at the top left under heading Process. The controller parameters (proportional, integral and derivative) are entered under the heading Controller. The unit step output time response of the plant as well as the output time response of the controller are shown at the bottom of the screen. System output is shown in blue while the controller output is shown in green.
Figure 5.23: The PID Loop Simulator. As an example, let's consider the following plant transfer function:
and the PID controller's transfer function:
● 87
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 87
11/10/2022 13:54
PID-based Practical Digital Control
The controller transfer function in "PID Loop Simulator" is specified as: Therefore,
C = 2, I = 10, and D = 1.2
Entering the plant and controller values into the simulator produces the theoretical system time response shown in Figure 5.23. The system has a small overshoot and the steady state error is zero for all practical purposes. You can easily change the controller parameters and view the output time response immediately.
● 88
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 88
11/10/2022 13:54
Chapter 6 • The Digital PID Controller
Chapter 6 • The Digital PID Controller 6.1 Overview This Chapter discusses the digital form of the continuous-time PID controller as well as ways of using it in a computer system like a microcontroller.
6.2 Digital PID The continuous-time transfer function of the PID controller was found to be:
(6.1) The digital form of the PID controller can be found by taking the z-transform of the above transfer function:
(6.2) This transfer function can be implemented as a parallel structure by summing the proportional, integral, and derivative terms. Let
and
(6.3)
Then, equation (6.2) can be written as:
(6.4) It can be shown that equation (6.4) can be implemented as shown in Figure 6.1 with the following sets of equations. PID: For the proportional section: For the integral section: For the derivative section: The output is given by:
● 89
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 89
11/10/2022 13:54
PID-based Practical Digital Control
Figure 6.1: PID controller implementation as a parallel structure.
Variables
and
are the memory variables of the controller.
PI: For the case of PI-only controller, you have the following equations: For the proportional section: For the integral section: The output is given by: The PI implementation is pictured in Figure 6.2 as a parallel structure.
Figure 6.2: PI-only controller implementation as a parallel structure.
6.3 Choosing a Sampling Time, T Before implementing a digital PID algorithm, you have to choose a sampling time T (or sampling interval). Choosing a large sampling time has destabilizing effects on the system. In addition, information loss occurs when large sampling times are selected. Also, the errors that occur when a continuous system is discretized increase as the sampling interval increases.
● 90
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 90
11/10/2022 13:54
Chapter 6 • The Digital PID Controller
You may think that decreasing the sampling interval towards zero will make a discrete system converge towards an equivalent continuous system. However, in practice this is not the case. As the sampling interval is reduced, the change between the successive data values becomes less than the resolution of the system, leading to loss of information. In general, if a shorter sampling interval is to be used then the word length of the system should be increased so that the difference between adjacent samples can be resolved. It has been found from practical applications in the process industry that a sampling interval of 1 second is generally short enough for most applications such as pressure control, temperature control and flow control. Systems with fast responses such as electromechanical systems (e.g., motors) require much shorter sampling intervals, usually of the order of milliseconds. Various empirical rules have been suggested by many researchers for the selection of the sampling interval. These rules are based on practical experience and simulation results. Among them are the following: If the plant has the dominant time constant Tp, then the sampling interval T for the closedloop system should be selected such that T < Tp/10. Assuming that the process has a Ziegler–Nichols open-loop model:
then the sampling interval should be selected such that T < T1/4. If the closed-loop system is required to have a settling time Tss or a natural frequency of ωn then choose the sampling interval T such that T < Tss/10 and ωs > 10ωn, where ωs is the sampling frequency, i.e., ωs = 2π/T.
6.4 Microcontroller Implementation of the PID Algorithm The final stage of a digital control system design is the implementation of the controller algorithm (set of difference equations) on a digital computer — nowadays, usually a microcontroller. In this section, you learn about the implementation of the PID digital controller algorithm on microcontrollers. Microcontrollers have traditionally been programmed using the assembly language of the target hardware. Assembly language has several important disadvantages and is currently less popular than it used to be. One important disadvantage is that the code generated using the assembly language can only run on the specific target hardware. For example, the assembly program developed for a PIC microcontroller cannot be used, say, on an Intel 8051 microcontroller. Assembly language programs also tend to be more difficult to develop, test and maintain. In the projects in this book, you will be using C programs for the Arduino, and Python programs for the Raspberry Pi.
● 91
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 91
11/10/2022 13:54
PID-based Practical Digital Control
There are several methods that can be used to implement the controller algorithm on a microcontroller. One of the most common methods with the advantage of accurate implementation involves a timer interrupt to generate the required loop delay (or the sampling interval). In this method, the software consists of two parts: the main program and the timer interrupt service routine (ISR). As shown in Figure 6.3 in the form of a Program Description Language (PDL), in the main program various variables such as the setpoint value, PID controller parameters, as well as the A/D converter and the timer interrupt mechanism are initialized. The setpoint value can either be hardcoded into the software or a keypad & pushbutton combination can be used to set it. The timer is set to interrupt at an interval equivalent to the chosen sampling interval of the system. The main program then enters a loop waiting for the timer interrupts to occur. Whenever a timer interrupt occurs, the program jumps the interrupt service routine where the PID controller algorithm is implemented in software. The error signal is obtained by calculating the difference between the setpoint value and measured output value. The algorithm is then implemented and the output sample for the current sampling time is obtained. A pre-processing step is then performed by updating the variables for the next sample. On return from the ISR, the program waits in the main program until the next sampling interval, while the above process repeats forever. MAIN:BEGIN Initialize PID parameters Initialize other variables used Set/Read setpoint value, sk Initialize ADC Initialize Timer interrupts, interrupt at T intervals DO FOREVER Wait for timer interrupts ENDDO MAIN:END
ISR:BEGIN Get setpoint, sk Read output, yk Calculate error, ek Calculate controller output, uk (section 6.2) Limit
uk to
avoid interrupt windup
Update controller memory variables, pk-1 and ek-1 Return from interrupt ISR:END
Figure 6.3: Controller implementation on a microcontroller.
● 92
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 92
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Chapter 7 • On-Off Temperature Control 7.1 Overview Temperature control is used to control the temperature of a gas (e.g., air) in a closed space, or the temperature of liquid in a container, or for example to control the temperature of an oven. Here, the aim is to design a controller which will force the measured temperature to be the same as the desired SetTemp temperature. Thus, if for example the measured temperature changes then the controller will take the necessary steps to force the output temperature to be same as the SetTemp value. Also, if the SetTemp value is changed then again the controller will make sure that the SetTemp and the measured values are the same. The controller takes inputs from temperature sensors and provides output that is usually connected to a heater or a fan.
7.2 Temperature Controllers Basically, three types of temperature controllers are in common use as described below. ON-OFF temperature control This is perhaps the simplest form of temperature controller, where the output from the controller is either on or off. A heater is usually connected to a relay in on-off control. If the measured temperature is above the SetTemp value, then the relay and consequently the heater is turned off. If on the other hand, the measured temperature is below the SetTemp value, then the relay and hence the heat are turned on. One disadvantage of this method is that the temperature is not controlled closely, and also the rapid cycling of the relay can shorten its life and can cause damage to it. One technique used in On-Off control is to add hysteresis to the controller operation. With the hysteresis, the measured temperature is allowed to exceed the SetTemp value by some amount before the relay is turned off. Similarly, the measured temperature is allowed to drop below the SetTemp value by some amount before the relay is turned back on. For example, if the SetTemp value is 20 ºC, a 2 ºC hysteresis can be used such that the relay turns off when the temperature reaches 22 ºC, and it turns on when the temperature falls below 18 ºC. Although this technique will eliminate the rapid cycling of the relay, it has the disadvantage that the output temperature will fluctuate between the two limits of the hysteresis points. The response will show overshoot and undershoot from the setpoint value. The On-Off type control is used in applications where precise control of the temperature is not required, or in temperature alarm systems such that an alarm is generated if the temperature goes above or below pre-specified values. Proportional temperature control This control method is similar to On-Off but here the power supplied to the heater is decreased as the measured temperature approaches the SetTemp value. This way, the measured temperature will not overshoot the SetTemp value, and therefore a closely controlled temperature output can be obtained. Way below the SetTemp value, full power is applied to the heater as is the case with On-Off control.
● 93
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 93
11/10/2022 13:54
PID-based Practical Digital Control
PID temperature control This is by far the best temperature controller method as enables precise control of the temperature. As you have seen in previous Chapters, the PID parameters must be selected correctly for successful control of the plant. i.e., the PID must be tuned correctly. PID control is used in temperature applications, such as in ovens, furnaces, and chemical plants, where close control of the temperature is required with quick action to the SetTemp or measured temperature changes. In the remaining sections of this Chapter, you'll examine ON-OFF temperature controllers using the Arduino Uno and the Raspberry Pi computers.
7.3 Project 1: ON-OFF Temperature Control with Arduino Uno Description: In this project you will be implementing an ON-OFF type control algorithm to control the temperature in a room. In this project, the desired temperature (SetTemp) is fixed in the program for simplicity. Block diagram: Figure 7.1 shows the block diagram of the project. A relay is controlled from the Arduino Uno which turns the heater power on/off. A red LED indicates when the relay (i.e., the heater) is ON. The room temperature is sensed using an analog TMP36 type semiconductor temperature sensor chip.
Figure 7.1: Block diagram of the project. Circuit diagram: The circuit diagram of the project is shown in Figure 7.2. An I2C type LCD is used in this project with the on-board PCF8574T type I2C controller chip. The interface between the Arduino Uno and the external components are as follows (Ground and power supply pins are not shown): External component TMP36 RELAY (Pin S) LED LCD
Arduino Uno port A0 2 3 SDA, SCL
● 94
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 94
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.2: Circuit diagram of the project. I2C LCD: The Arduino Uno has one I2C bus at the following pins: A4
SDA
also marked near AREF pin
A5
SCL
also marked near AREF pin
As shown in Figure 7.3, the I2C address of the PCF8574T chip is selected by 3 jumpers labeled A0, A1, and A2 on the controller board. By default, the address is set to 0x27 (i.e., no jumper connections), but your LCD address may be different.
Figure 7.3: LCD I2C address selection. Before using the I2C LCD, you have to add the I2C library to our IDE. Libraries are often distributed as a ZIP file or folder where the name of the folder is the name of the library. Inside the folder, there is a .cpp file, a .h file, a keywords.txt file, examples folder, and other files that may be required by the library. You should not unzip the library. The steps to add the I2C LCD library are as follows: • Browse to the following website to locate the library file (the file is also available in the support software package for the book): https://www.arduinolibraries.info/libraries/liquid-crystal-i2-c • Download this file: LiquidCrystal_I2C-1.1.2,zip to a folder on your PC.
● 95
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 95
11/10/2022 13:54
PID-based Practical Digital Control
• Start the IDE. • Click Sketch Include Library Add .ZIP Library. • Select the saved library file and click Open. • Return to Sketch Include Library menu and you should see the new library at the bottom of the drop-down menu. • To test that the library has been added successfully, enter the following lines in a newly created program: #include #include void setup() { } void loop() { }
• Compile the program. There should be no errors. The I2C LCD library supports many functions. Some most commonly used functions are: init(): clear(): home(): noBlink(): blink(): noCursor(): cursor(): scrollDisplayLeft(): scrollDisplayRight(): noBacklight(): backlight(): setCursor(column, row): print(): write():
initialize LCD (This must be the first function call) clear the screen home the cursor stop blinking cursor enable blinking cursor hide cursor display cursor scroll display left scroll display right disable backlight enable backlight set cursor position (0, 0) is the top-left position print data on LCD write to LCD
The address of the I2C LCD must be defined at the beginning of the program. For example, if the address is 0x3F and the LCD is 16 columns by 2 rows (i.e., 16×2), then:
● 96
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 96
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
LiquidCrystal_I2C lcd(0x3F, 16, 2);
Following the above statement, you can call the LCD functions by indexing them with the keyword lcd. For example, to initialize the LCD: lcd.init();
// initialize the lcd
or, for example to enable the backlight, use: lcd.backlight();
// Enable backlight
Program listing: Figure 7.4 shows the program listing (Program: AONOFF1). At the beginning of the program, SetTemp is set to 20.0 degrees C, and the LED and RELAY are assigned to port numbers 3 and 2, respectively. Inside the setup() function, both the RELAY and LED are configured as outputs and are deactivated to start with. The output voltage of the TMP36 temperature sensor chip is proportional to the temperature and is given by:
T = (Vo – 500) / 10 Where T is the measured temperature in Degrees C, and Vo is the sensor output voltage is millivolts. Inside the main program loop the room temperature is read by the ADC channel A0 and subsequently compared to the desired temperature. If the room temperature is lower than the desired temperature then both the LED and RELAY are activated so that the heater is turned ON, otherwise they are deactivated to turn OFF the heater. The program checks the temperature every 10 seconds. The SetTemp and RoomTemp are displayed on the LCD as shown in Figure 7.5. //---------------------------------------------------------------------//
ON-OFF TEMPERATURE CONTROL
//
==========================
// // This is an ON-OFF temperature controller project. The ambient temperature // is read and compared to the desired set value. If it is less than the set // value then the relay and LED are activated, otherwise they are deactivated // // Author: Dogan Ibrahim // File
: AONOFF1
// Date
: June, 2022
//---------------------------------------------------------------------#include #include LiquidCrystal_I2C lcd(0x27, 16, 2);
● 97
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 97
11/10/2022 13:54
PID-based Practical Digital Control
float SetTemp = 20.0;
// Desired temperature
#define TMP36 A0
// TMP36 at port A0
int raw; int LED = 3;
// LED at port 3
int RELAY = 2;
// RELAY at port 2
void setup() { pinMode(LED, OUTPUT);
// LED is output
pinMode(RELAY, OUTPUT);
// RELAY is output
digitalWrite(LED, LOW);
// LED OFF at beginning
digitalWrite(RELAY, LOW);
// RELAY OFF at beginning
lcd.init();
// Initialize LCD
lcd.backlight();
// Backlight ON
} void loop() { raw = analogRead(TMP36);
// Read temperature
float mV = 5000.0 * raw / 1023.0;
// in mV
float RoomTemp = (mV-500.0) / 10.0;
// Room temperature in C
lcd.clear();
// Clear LCD
lcd.setCursor(0, 0); lcd.print(" SetTemp = ");
// Display SetTemp =
lcd.print(SetTemp);
// Display SetTEmp
lcd.setCursor(0, 1); lcd.print("RoomTemp = ");
// Display RoomTemp =
lcd.print(RoomTemp);
// Display RoomTemp
if(SetTemp > RoomTemp)
// If cold
{ digitalWrite(LED, HIGH);
// LED ON
digitalWrite(RELAY, HIGH);
// RELAY ON
} else { digitalWrite(LED, LOW);
// LED OFF
digitalWrite(RELAY, LOW);
// RELAY OFF
} delay(10000);
// Wait 10 seconds
}
Figure 7.4: Program: AONOFF1.
● 98
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 98
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.5: The LCD display.
7.4 Project 2: ON-OFF Temperature Control with Hysteresis and Arduino Uno Description: This project is very similar to Project 1, but here the temperature is kept between two values TLOW and THIGH. In this project TLOW and THIGH are set to 25 ºC and 27 ºC respectively. The block diagram and circuit diagram of the project are as in Figure 7.1 and 7.2, respectively. Program listing: Figure 7.6 shows the program listing (Program: AONOFF2). This program is very similar to the one given in Figure 7.4 but here the temperature is kept between TLOW and THIGH. If the room temperature is equal to or lower than TLOW then the relay is activated. If on the other hand the room temperate higher or equal to THIGH then the relay is deactivated. Figure 7.7 shows the LCD output. //-------------------------------------------------------------------------//
ON-OFF TEMPERATURE CONTROL WITH HYSTERESIS
//
==========================================
// // This is an ON-OFF temperature controller project. The ambient temperature // is read and compared to TLOW. If it is lower than or equal to TLOW then the // relay is activated. If on the other hand it is higher than or equal to THIGH // then the relay is deactivated. // // Author: Dogan Ibrahim // File
: AONOFF2
// Date
: June, 2022
//--------------------------------------------------------------------------#include #include LiquidCrystal_I2C lcd(0x27, 16, 2); float TLOW = 25.0;
// Low limit
float THIGH = 27.0;
// High limit
#define TMP36 A0
// TMP36 at port A0
int raw; int LED = 3;
// LED at port 3
int RELAY = 2;
// RELAY at port 2
● 99
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 99
11/10/2022 13:54
PID-based Practical Digital Control
void setup() { pinMode(LED, OUTPUT);
// LED is output
pinMode(RELAY, OUTPUT);
// RELAY is output
digitalWrite(LED, LOW);
// LED OFF at beginning
digitalWrite(RELAY, LOW);
// RELAY OFF at beginning
lcd.init();
// Initialize LCD
lcd.backlight();
// Backlight ON
} void loop() { raw = analogRead(TMP36);
// Read temperature
float mV = 5000.0 * raw / 1023.0;
// in mV
float RoomTemp = (mV-500.0) / 10.0;
// Room temperature in C
lcd.clear();
// Clear LCD
lcd.setCursor(0, 0); lcd.print("TLH=");
// Display TLH=
lcd.print(TLOW);
// Display TLOW
lcd.print("-");
// Display -
lcd.print(THIGH);
// Display THIGH
lcd.setCursor(0, 1); lcd.print("RoomTemp = ");
// Display RoomTemp =
lcd.print(RoomTemp);
// Display RoomTemp
if(RoomTemp = THIGH)
// If greater or equal
{ digitalWrite(LED, LOW);
// LED OFF
digitalWrite(RELAY, LOW);
// RELAY OFF
} } delay(10000);
// Wait 10 seconds
}
Figure 7.6: ON-OFF control with hysteresis.
● 100
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 100
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.7: The LCD output.
7.5 Project 3: ON-OFF Temperature Control with Button Control – Arduino Uno Description: This project is similar to Project 1, but here the desired SetTemp is set using buttons. Three buttons named as UP, DOWN, and START are used. SetTemp is set to 20 ºC to start with. Pressing UP increments SetTemp, while pressing DOWN decrements it. When the user is satisfied with the desired SetTemp, the START button should be pressed to start the temperature controller. Block diagram: Figure 7.8 shows the block diagram of the project.
Figure 7.8: Block diagram of the project. Circuit diagram: The circuit diagram of the project is shown in Figure 7.9. The control buttons UP, DOWN, and START are connected to Arduino Uno port pins 4, 5, and 6, respectively. The output state of the buttons is at logic 1 and go to logic 0 when pressed. The LCD, relay, and the LED are connected as in Project 1.
Figure 7.9:Circuit diagram of the project.
● 101
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 101
11/10/2022 13:54
PID-based Practical Digital Control
Program listing: Figure 7.10 shows the program listing (Program: AONOFF3). Function Desired() controls the button actions. When the program runs, the default value of the SetTemp (20 ºC) is displayed. Pressing button UP will increment the SetTemp by one, while pressing button DOWN will decrement it by one. Pressing the START button will launch the controller. The control action is as in Project 1 where the SetTemp value is compared to the measured value (RoomTemp) and the relay is turned ON or OFF to control the heater. At this point, the program will have to be restarted in order to set another SetTemp value. The control action is implemented at every 10 seconds. //-------------------------------------------------------------------------//
ON-OFF TEMPERATURE CONTROL - SetTemp with buttons
//
=================================================
// // This is an ON-OFF temperature controller project. In this version of the // project the SetTemp is set using buttons // // Author: Dogan Ibrahim // File
: AONOFF3
// Date
: June, 2022
//--------------------------------------------------------------------------#include #include LiquidCrystal_I2C lcd(0x27, 16, 2); float SetTemp = 20.0;
// Initial SetTEmp
#define TMP36 A0
// TMP36 at port A0
int raw; int LED = 3;
// LED at port 3
int RELAY = 2;
// RELAY at port 2
int UP = 4;
// UP at 4
int DOWN = 5;
// DOWN at 5
int START = 6;
// START at 6
int ExitFlag = 0; void setup() { pinMode(LED, OUTPUT);
// LED is output
pinMode(RELAY, OUTPUT);
// RELAY is output
pinMode(UP, INPUT);
// Button is input
pinMode(DOWN, INPUT);
// Button is input
pinMode(START, INPUT);
// Button is input
digitalWrite(LED, LOW);
// LED OFF at beginning
digitalWrite(RELAY, LOW);
// RELAY OFF at beginning
lcd.init();
// Initialize LCD
lcd.backlight();
// Backlight ON
Desired();
● 102
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 102
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
} // // This function sets the desired temperature using buttons // void Desired() { lcd.clear(); while(ExitFlag == 0) { lcd.setCursor(0, 0); lcd.print("SetTemp = "); lcd.print(SetTemp); while(digitalRead(UP) == 1 && digitalRead(DOWN) == 1 && digitalRead(START)== 1); if(digitalRead(UP) == 0) { SetTemp++; while(digitalRead(UP) == 0); } else if(digitalRead(DOWN) == 0) { SetTemp--; while(digitalRead(DOWN) == 0); } delay(10); if(digitalRead(START) == 0)ExitFlag = 1; } } void loop() { raw = analogRead(TMP36);
// Read temperature
float mV = 5000.0 * raw / 1023.0;
// in mV
float RoomTemp = (mV-500.0) / 10.0;
// Room temperature in C
lcd.clear();
// Clear LCD
lcd.setCursor(0, 0);
// Cursor at 0,0
lcd.print("SetTemp = ");
// Display SetTemp
lcd.print(SetTemp); lcd.setCursor(0, 1);
// Cursor at (0,1
lcd.print("RoomTemp= ");
// Display RoomTemp =
lcd.print(RoomTemp);
// Display RoomTemp
if(RoomTemp < SetTemp)
// If lower
● 103
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 103
11/10/2022 13:54
PID-based Practical Digital Control
{ digitalWrite(LED, HIGH);
// LED ON
digitalWrite(RELAY, HIGH);
// RELAY ON
} else { digitalWrite(LED, LOW);
// LED OFF
digitalWrite(RELAY, LOW);
// RELAY OFF
} delay(10000);
// Wait 10 seconds
}
Figure 7.10: Program: AONOFF3.
7.6 Project 4: ON-OFF Temperature Control with Rotary Encoder and Arduino Uno Description: This project is similar to the previous temperature control projects, but here a rotary encoder is used to set the SetTemp. Initially SetTemp is set to 20ºC and rotating the arm of the rotary encoder you can increase or decrease the SetTemp value. Block diagram: Figure 7.11 shows the block diagram of the project.
Figure 7.11 Block diagram of the project. A rotary encoder (Figure 7.12) is a device that looks like a potentiometer and it senses the rotation and direction of its knob. The device has two internal contacts that make and break a circuit as the knob is turned. As the knob is turned, a click is felt that indicates that the know has been rotated by one position. With a simple logic you can determine the direction of rotation. A rotary encoder has the following pins: GND: power supply ground Vcc (+): power supply
● 104
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 104
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
CLK: This is an output pin used to determine the amount of rotation. Each time the knob is rotated by one click in either direction, the CLK output goes to HIGH and then LOW DT: This is an output similar to CLK pin, but it lags the CLK by 90 degrees. This output is used to determine the direction of rotation SW: This is an active LOW push button. When the knob is pushed, the voltage goes LOW
Figure 7.12: Rotary encoder. In our project each rotation (i.e., click) of the knob will increment (or decrement) the SetTemp by 1ºC. Turning the knob in one direction will increment by one, while turning it in the other direction will decrement it by one. When the required value is reached, the user has to push the knob so that the controller action. Circuit diagram: the connections between the Arduino Uno and the external components are as follows (power supply and GND connections are not shown): External component LED Relay LCD TMP36 Encoder CLK Encoder DT Encoder SW
Arduino Uno port 3 2 SCL, SDA A0 4 5 6
The circuit diagram of the project is shown in Figure 7.13.
● 105
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 105
11/10/2022 13:54
PID-based Practical Digital Control
Figure 7.13: Circuit diagram of the project. Program listing: Figure 7.14 shows the program listing (Program: AONOFF4). At the beginning of the program the interface between Arduino Uno and external components are defined and the variables used in the program are initialized. Inside the setup() function, LED and RELAY ae configured as outputs, and the rotary encoder pins are configured as inputs. The LED and RELAY are turned OFF at the beginning of the program and the LCD is initialized. The program then calls function Rotary(). This function senses when the user turns the encoder arm and increments or decrements variable SetTemp depending on which direction the arm is rotated. When the user is happy with the SetTemp value, the rotary encoder shaft should be pushed in. After reading the SetTemp value, the remainder of the program is same as in Project 1. //-------------------------------------------------------------------------//
ON-OFF TEMPERATURE CONTROL - SetTemp with Rotary Encoder
//
========================================================
// // This is an ON-OFF temperature controller project. In this version of the // project the SetTemp is set using a rotary encoder // // Author: Dogan Ibrahim // File
: AONOFF4
// Date
: June, 2022
//--------------------------------------------------------------------------#include #include LiquidCrystal_I2C lcd(0x27, 16, 2); float SetTemp = 20.0;
// Initial SetTEmp
#define TMP36 A0
// TMP36 at port A0
int raw; int LED = 3;
// LED at port 3
int RELAY = 2;
// RELAY at port 2
● 106
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 106
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
int CLK = 4;
// CLK pin
int DT = 5;
// DT pin
int SW = 6;
// SW pin
int flag = 1; int ClkState, ClkOldState, DTState, SWState; void setup() { pinMode(LED, OUTPUT);
// LED is output
pinMode(RELAY, OUTPUT);
// RELAY is output
pinMode(CLK, INPUT);
// CLK is input
pinMode(DT, INPUT);
// DT is input
pinMode(SW, INPUT_PULLUP);
// SW is input
digitalWrite(LED, LOW);
// LED OFF at beginning
digitalWrite(RELAY, LOW);
// RELAY OFF at beginning
lcd.init();
// Initialize LCD
lcd.backlight();
// Backlight ON
Rotary(); } // // This functon reads the rotary encoder value as the encoder arm // is rotated. The SetTemp value in changes by 1 (incremented or // decremented at each click of the rotary encoder). // void Rotary() { ClkOldState = digitalRead(CLK); lcd.clear();
// Clear LCD
lcd.setCursor(0, 0);
// Cursor at 0,0
lcd.print("SetTemp:");
// Display SetTemp
lcd.setCursor(0, 1);
// Cursor at 0,1
lcd.print(SetTemp);
// Display initial value
while(flag == 1) { ClkState = digitalRead(CLK); DTState = digitalRead(DT); if(ClkState != ClkOldState && ClkState == 1) { if(DTState != ClkState) SetTemp++;
// Increment SetTemp
else { SetTemp--;
// Decrement SetTemp
if(SetTemp == 0)SetTemp = 20;
// Back to 20 if 0
● 107
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 107
11/10/2022 13:54
PID-based Practical Digital Control
} lcd.setCursor(0, 1);
// Cursor at 0,1
lcd.print("
// Delete
");
lcd.setCursor(0, 1);
// Cursor back at 0,1
lcd.print(SetTemp);
// Display SetTEmp
} ClkOldState = ClkState; SWState = digitalRead(SW);
// Read stste of SW button
if(SWState == 0)flag = 0;
// Exit Rotary() function
} }
void loop() { raw = analogRead(TMP36);
// Read temperature
float mV = 5000.0 * raw / 1023.0;
// in mV
float RoomTemp = (mV-500.0) / 10.0;
// Room temperature in C
lcd.clear();
// Clear LCD
lcd.setCursor(0, 0);
// Cursor at 0,0
lcd.print("SetTemp = ");
// Display SetTemp
lcd.print(SetTemp); lcd.setCursor(0, 1);
// Cursor at (0,1
lcd.print("RoomTemp= ");
// Display RoomTemp =
lcd.print(RoomTemp);
// Display RoomTemp
if(RoomTemp < SetTemp)
// If lower
{ digitalWrite(LED, HIGH);
// LED ON
digitalWrite(RELAY, HIGH);
// RELAY ON
} else { digitalWrite(LED, LOW);
// LED OFF
digitalWrite(RELAY, LOW);
// RELAY OFF
} delay(10000);
// Wait 10 seconds
}
Figure 7.14: Program: AONOFF4. Figure 7.15 shows the LCD display when the program is first run, where the default temperature value 20 ºC is displayed before the rotary encoder arm is rotated.
● 108
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 108
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.15: Initial LCD display.
7.7 Project 5: ON-OFF Temperature Control with Raspberry Pi 4 Description: In this project, you will be using the Raspberry Pi 4 for ON-OFF temperature control. As in Project 1, you will hardcode the desired SetTemp value in software. Block diagram: Figure 7.16 shows the block diagram of the project. This figure is very similar to Figure 7.1, but here you have used an external ADC chip to convert the analog temperature output of the TMP36 sensor into digital form. This is because the Raspberry Pi does not have any ADC channels and external ADC chips must be used to interface analog devices to Raspberry Pi.
Figure 7.16: Block diagram of the project. Circuit diagram: In this project, the MC3002 ADC chip is used (Figure 7.17). This chip has the following features: • • • • • • •
10-bit resolution (0 to 1023 quantization levels) On-chip sample and hold SPI bus compatible Wide power supply range (+2.7 to +5.5V) 75 ksps sampling rate 8-pin package 5 nA standby current, 50 µA active current
The MCP3002 is a successive approximation 10-bit ADC with on-board sample and hold circuitry. The chip is programmable to operate as either a differential-input pair or as dual single-ended inputs. The pin definitions are as follows:
● 109
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 109
11/10/2022 13:54
PID-based Practical Digital Control
Vdd/Vref: CH0: CH1: CLK: DIN: DOUT: CS/SGDN:
Power supply and reference voltage input Channel 0 analog input Channel 1 analog input SPI clock input SPI serial data in SPI serial data out Chip select/shutdown input
In this project, the supply voltage and the reference voltage are both set to +3.3 V. Thus, the digital output code is given by: Digital output code = 1024 × Vin / 3.3 or Digital output code = 310.30 × Vin Each quantization level corresponds to 3300 mV/1024 = 3.22 mV. Thus, for example, digital input data "00 00000001" corresponds to 3.22 mV, "00 00000010" corresponds to 6.44 mV, and so on. The MCP3002 has two configuration bits: SGL/DIFF and ODD/SIGN. These bits follow the sign bit and are used to select the input channel configuration. The SGL/DIFF is used to select single-ended or differential mode. The ODD/SIGN bit selects which channel is used in single-ended mode and is used to determine polarity in differential mode. In this project, you are using channel CH0 in single-ended mode. According to the MCP3002 datasheet, SGL/DIFF and ODD/SIGN must be set to 1 and 0 respectively.
Figure 7.17: The MCP3002 ADC chip. Notice that Raspberry Pi pins are not +5 V tolerant, but the I2C LCD operates with +5 V where its SDA and SCL pins are pulled to +5 V. It is generally not a good idea to connect the LCD directly to the Raspberry Pi as it can damage its I/O circuitry. There are several solutions here. On solution is to remove the I2C pull-up resistors on the LCD module. The other option is to use an I2C which operates with +3.3 V. The other solution is to use a bidirectional +3.3 V to +5 V logic level converter chip. In this project, you will use the TXS0102 bidirectional logic level converter chip like the one shown in Figure 7.18.
● 110
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 110
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.18: Logic level converter. The circuit diagram of the project is shown in Figure 7.19. The interface between the Raspberry Pi 4 and the external devices are as follows (power and ground connections are not shown): External device RELAY ADC DIN ADC CLK ADC DOUT ADC CS LED LCD SCL LCD SDA
Raspberry Pi 4 port GPIO17 GPIO10 GPIO11 GPIO9 GPIO8 GPIO27 GPIO3 GPIO2
Raspberry Pi pin no 11 19 23 21 24 13 5 3
Figure 7.19: Circuit diagram of the project. Enabling the SPI and I2C buses on your Raspberry Pi You have to enable the SPI bus since the MC3002 uses it. Also, the I2C bus must be enabled to use the I2C LCD. The steps are:
● 111
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 111
11/10/2022 13:54
PID-based Practical Digital Control
• Start your Raspberry Pi in command mode. • Enter sudo raspi-config. • Scroll down to Interface Options (Figure 7.20).
Figure 7.20: Scroll down to Interface Options. • • • • • • •
Select SPI. Select to enable the bus and select . Select Interface Options again. Select I2C. Select to enable the bus and select . Move the cursor to and press Enter to exit. Enter the following command:
sudo apt install -y i2c-tools python3-smbus
• Restart your Raspberry Pi by typing: sudo reboot
Checking the LCD I2C address After building the hardware, you should enter the following command to check the address of the I2C LCD: sudo i2cdetect –y 1
you should see display as shown in Figure 7.21. The address of the LCD author is using was: 0x27.
● 112
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 112
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
Figure 7.21: Checking the I2C LCD address. Installing the I2C library Before you start developing our controller software, you have to install an I2C LCD library. There are several libraries available on the Internet. The one chosen by the author is named RPLCD and it can be installed as follows: sudo pip3 install RPLCD
The I2C LCD library supports the following functions (see the RPLCD I2C LCD library documentation for more details): lcd_clear() cursor_pos = (row, column) lcd.write_string(text) lcd.write_string(text\r\n) lcd.home() lcd.cr() lcd.lf() lcd.crlf()
clear LCD and set to home position position cursor display text display text followed by new line home cursor insert carriage-return insert line-feed insert carriage-return and line-feed
Testing the I2C bus and LCD It is worthwhile to test the LCD display before developing our controller program. Create the simple test program shown in Figure 7.22 (Program: lcdtest.py) which send the text MY LCD to the LCD. If you have used a text editor (e.g., nano) to create the program, you can run it by entering the following command: python3 lcdtest.py
If on the other hand you have used the Thonny IDE, then just run the program. #--------------------------------------# #
LCD TEST PROGRAM
#
================
#
● 113
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 113
11/10/2022 13:54
PID-based Practical Digital Control
# Author: Dogan Ibrahim # File
: lcdtest.py
# Date
: June, 2022
#--------------------------------------from RPLCD.i2c import CharLCD lcd=CharLCD('PCF8574', 0x27) lcd.clear() lcd.home lcd.write_string("MY LCD")
Figure 7.22: LCDtest program. Testing the SPI bus To test the SPI bus, enter the command: sudo ls –l /dev/spidev*
You should get the display shown in Figure 7.23.
Figure 7.23: Testing the SPI bus. SPI bus functions Python supports the following SPI bus functions: Function
Description
open (0, 0): open (0, 1): close(): writebytes([array of bytes]): readbytes(len): xfer2([array of bytes]):
Open SPI bus 0 using CE0 Open SPI bus 0 using CE1 disconnect the device from the SPI bus Write an array of bytes to SPI bus device Read len bytes from SPI bus device Send an array of bytes to the device with CEx asserted at all times Send an array of bytes de-asserting and asserting CEx with every byte transmitted
xfer([array of bytes]):
You are now ready to develop our controller program. Program listing: Figure 7.24 shows the Raspberry Pi Python program listing (Program: AONOFF5.py). At the beginning of the program the library modules used in the program are imported to the program. SetTemp is set to 33 ºC and the LED and RELAY ports are defined. The function Setup() configures LED and RELAY as outputs and deactivates them at the beginning of the program.
● 114
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 114
11/10/2022 13:54
Chapter 7 • On-Off Temperature Control
The function Get_ADC_Data() is used to read the analog data from the temperature sensor chip, where the channel number (channel_no) is specified in the function argument as 0 or 1. Notice that you have to send the start bit, followed by the SGL/DIFF and ODD/SIGN bits and the MSBF bit to the MCP3002 ADC chip. It is recommended to send leading zeroes on the input line before the start bit. This is often done when using microcontroller based systems required to send 8 bits at a time. The following data can be sent to the ADC (SGL/DIFF = 1 and ODD/SIGN = channel_no) as bytes with leading zeroes for more stable clock cycle. The general data format is: 0000 000S DCM0 0000 0000 0000 Where, S = start bit, D = SGL/DIFF bit, C = ODD/SIGN bit, and M = MSBF bit. For channel 0: 0000 0001 1000 0000 0000 0000 (0x01, 0x80, 0x00) For channel 1: 0000 0001 1100 0000 0000 0000 (0x01, 0xC0, 0x00) Notice that the second byte can be sent by adding 2 to the channel number (to make it 2 or 3) and then shifting 6 bits to the left as shown above to give 0x80 or 0xC0. The chip returns 24-bit data (i.e., 3 bytes) and you must extract the correct 10-bit ADC data from this 24-bit data. The 24-bit data is in the following format ("X" is don't care bit): XXXX DDDD DDDD DDXX Assuming that the returned data is stored in 24 bit variable ADC, you have: ADC[0] = "XXXX" ADC[1] = "XXXX DDDD" ADC[2] = "DDDD DDXX" Thus, you can extract the 10-bit ADC data with the following operations: (ADC[2] >> 2)
so, low byte = "00DD DDDD"
and (ADC[1] & 15) 100.0:
# Limit uk for PWM
uk = 100.0 if uk < 0.0:
# Limit uk for PWM
uk = 0.0 pwm.ChangeDutyCycle(uk)
# To PWM
pk_1 = pk
# Update pk_1
return
Init()
# Init LCD
SetupPlot()
# Setup plot
i = 0 pwm.start(0) while i < 400:
# Do Forever
yk = Calc_Temperature() PI() i = i + 1 plt.scatter(i, yk,color='red') plt.pause(0.00001) EndTime = time.time() + 1 while time.time() - EndTime < 0: pass pwm.stop()
Figure 8.18: Program: PItemp.py. Figure 8.19 shows the closed-loop output time response of the system where the SetTemp (desired temperature) was set to 50 ºC. Notice that even though the steady-state error is zero and the response settles down at 50 ºC, the response shows a large overshoot which is not acceptable in many process control systems. Large overshoot is one of the results of tuning a system using the Ziegler and Nichol algorithm.
● 135
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 135
11/10/2022 13:55
PID-based Practical Digital Control
Figure 8.19: Closed-loop system time response. The integral time Ti was increased and the proportional constant reduced in order to decrease the overshoot and get a more acceptable result. Figure 8.20 shows the result when Kp = 2.0 and Ti = 35.0.
Figure 8.20: Improved response. Finally, an acceptable and nice response was obtained by increasing Ti further. Figure 8.21 shows the response with Kp = 2.0 and Ti = 50. In this response, the overshoot is small and the system settles down at the desired temperature quickly.
● 136
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 136
11/10/2022 13:55
Chapter 8 • PID Temperature Control with the Raspberry Pi
Figure 8.21: Nice response! Notice that the acceptable PI parameters were found after a few trial and error rounds. The Ziegler and Nichol tuning parameters gave us a starting point for tuning the system.
8.5 Project 4: PID Temperature Control Description: This project is similar to Project 2 but here you add the derivative term to your controller to make a PID controller. Notice that in many process control applications only the PI algorithm is used and the benefit of adding a derivative term is very little. This is especially true if the system has noise which can make the response unacceptable if derivative term is used. The desired temperature is set to 50 ºC as in the previous project. Block diagram and circuit diagram: The block diagram and circuit diagram of the project are as shown in Figure 8.16 and Figure 8.17, respectively. Proportional + Integral + Derivative (PID) controller parameters In reference to Figure 8.15 and the Ziegler and Nichols PID table of settings, you find the following P, I, and D controller parameters:
The parallel-PID realization shown in Figure 6.1 was used in this project. Program listing: Figure 8.22 shows the program listing (Program: PIDtemp.py). As in the previous program, at the beginning of the program the libraries used are imported
● 137
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 137
11/10/2022 13:55
PID-based Practical Digital Control .
to the program, and the I2C LCD and the SPI bus get initialized. Then the thermistor parameters are defined and PWM output is assigned to GPIO12 where the MOSFET switch is connected to. The only change from Figure 8.18 is the controller algorithm. Here, function PI() is replaced with function PID() and the derivative term is added to the controller. #---------------------------------------------------------# #
PID TEMPERATURE CONTROLLER
#
==========================
# # This is the PID temperature controller program # # Author: Dogan Ibrahim # File
: PIDtemp.py
# Date
: June, 2022
#---------------------------------------------------------import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import RPi.GPIO as GPIO import time from RPLCD.i2c import CharLCD import spidev import math GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) lcd=CharLCD('PCF8574', 0x27)
# Init LCD
spi = spidev.SpiDev()
# Init SPI
spi.open(0, 0)
# Using CE0
spi.max_speed_hz=4000
# SPI speed
B = 3950
# Thermistor B
R0 = 100000
# Thermistor R0
Rs = 100000
# Rs
T0 = 298.15
# T0
MOSFET = 12
# MOSFET
GPIO.setup(MOSFET, GPIO.OUT) pwm = GPIO.PWM(MOSFET, 100)
# PWM port
global sk, Kp, T, Ti, pk, pk_1, ek_1, a, b, yk #
● 138
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 138
11/10/2022 13:55
Chapter 8 • PID Temperature Control with the Raspberry Pi
# Setup real time plot # def SetupPlot(): plt.axis([0,400, 0,100])
# Axes limits
plt.title('Temperature')
# Title
plt.xlabel('Time (seconds')
# X label
plt.ylabel('Temperature')
# Y label
plt.ion() return # # This function returns the ADC result in variable rcv # def Get_ADC_Data(channel_no): ADC = spi.xfer2([1, (2 + channel_no) 2) return rcv # # This function calculates and returns the temperature in C # def Calc_Temperature(): adc = Get_ADC_Data(0)
# Get ADC value
Vo = adc * 3300.0 / 1024.0
# in millivolts
Rt = Rs * (3300 - Vo) / Vo
# Calculate Rt
R = math.log(Rt / R0) R = R / B T = R + 1 / T0 T = 1 / T
# T in Kelvin
T = T - 273.15
# In Degrees C
return T # # This function initializes the LCD and displays SetTemp # def Init(): global sk, a, b, Kp, T, Ti, pk, pk_1, ek_1 sk = 50
# SetTemp
Kp = 2.0 T = 1.0 Ti = 45.0 Td = 5.0 a = Kp*T/Ti b = Kp*Td/T pk = 0.0 pk_1 = 0.0
● 139
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 139
11/10/2022 13:55
PID-based Practical Digital Control
ek_1 = 0.0 lcd.clear()
# Clear LCD
lcd.home()
# Home cursor
lcd.cursor_pos = (0, 0)
# At 0,0
lcd.write_string("SetTemp:")
# Heading
lcd.cursor_pos = (1, 0)
# At 1,0
lcd.write_string(str(sk))
# SetTEmp
return # # This is the Proportional+Integral+Derivative algorithm function # def PID(): global yk, pk_1, ek_1 ek = sk - yk pk = a*ek + pk_1 wk = Kp*ek qk = b*(ek-ek_1) uk = wk + pk + qk
# PID output
if uk > 100.0:
# Limit uk for PWM
uk = 100.0 if uk < 0.0:
# Limit uk for PWM
uk = 0.0 pwm.ChangeDutyCycle(uk)
# To PWM
pk_1 = pk
# Update pk_1
ek_1 = ek
# Update ek_1
return
Init()
# Init LCD
SetupPlot()
# Setup plot
i = 0 pwm.start(0) while i < 400:
# Do Forever
yk = Calc_Temperature() PID() i = i + 1 x = i plt.scatter(x, yk,color='red') plt.show() plt.pause(0.0001) time.sleep(1) pwm.stop()
Figure 8.22: Program: PIDtemp.py.
● 140
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 140
11/10/2022 13:55
Chapter 8 • PID Temperature Control with the Raspberry Pi
Figure 8.23 shows the closed-loop output time response of the system where the SetTemp (desired temperature) was set to 50 ºC. Notice that even though the steady state error is zero and the response settles down at 50 ºC, the response shows a large overshoot which is not acceptable in many process control systems. Large overshoot is one of the results of tuning a system using the Ziegler and Nichol algorithm.
Figure 8.23: Closed-loop system time response. The integral time Ti was increased and the proportional constant reduced in order to decrease the overshoot and get a more acceptable result. At the same time, the derivative term was increased to overcome any overshoot. Figure 8.24 shows the result when Kp = 2.0 and Ti = 45.0, Td = 3.
Figure 8.24: Improved response. Finally, a disturbance response was plotted by removing the controller for a short while and then reconnecting it. Figure 8.25 shows the disturbance recovery response of the system. The steady-state response settled back at 50 ºC after the disturbance is removed.
● 141
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 141
11/10/2022 13:55
PID-based Practical Digital Control
Figure 8.25: Response to disturbance. Notice that the acceptable PID parameters were found after a few trial and error rounds. The Ziegler and Nichol tuning parameters gave us a starting point for tuning the system. Figure 8.26 shows the project built on a breadboard.
Figure 8.26: Project built on a breadboard. The sample time of the PID is based on using the Python built-in delay function time. sleep(). The delay introduced by this function is not very accurate. As a result, the real-time plots drawn in this Chapter are not very accurate. More accurate sample times and more accurate real-time plots can be obtained if the PID algorithm is implemented inside a timer iterrupt service routine.
8.6 Using the PID Loop Simulator The PID Loop Simulator described in Chapter 5 can be used to verify the time response of our closed loop system with the PID controller. The simulator can also be used to estimate the initial values of the PID parameters. Various parameters can be tried on the simulator
● 142
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 142
11/10/2022 13:55
Chapter 8 • PID Temperature Control with the Raspberry Pi
until a good response is obtained. Next, these parameters can be used on the actual controller. The PID controller parameters you have chosen are: Kp = 2.0 and Ti = 45.0, Td = 3.0
Therefore, the controller transfer function is:
Comparing with the simulator transfer function of: you have: C = 2, I = 22.5, and D = 6. Entering the plant and the controller parameters into the simulator gives the response as in Figure 8.27, which is very similar to the response you obtained in Figure 8.24.
Figurse 8.27: Simulator response.
● 143
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 143
11/10/2022 13:55
PID-based Practical Digital Control
Chapter 9 • PID Temperature Control with the Arduino Uno 9.1 Overview In the previous Chapter you absorbed how to read the temperature of a thermistor, and how to design a PID controller for a temperature control system using a Raspberry Pi. In this Chapter, you will learn how to design PID based temperature control systems using an Arduino Uno.
9.2 Project 1: Reading the Temperature of a Thermistor Description: In this Chapter, you will be using the hotbed that you used in the previous Chapter. This hotbed has a built-in NTC type 3950 thermistor temperature sensor. In this section you will develop a project to read and display the temperature of this thermistor. Circuit diagram: Although a resistive potential divider circuit is formed using the thermistor as shown in Figure 8.3, a +5 V power supply is used. The circuit diagram of the project is shown in Figure 9.1. Arduino Uno has built-in ADC meaning you do not need an external ADC. The thermistor is connected to analogue input A0 of the Arduino Uno. As shown in the previous Chapter, using a 100 kΩ series resistor, the resistance of the thermistor is given by:
,
where
is in millivolts
You can then use the Steinhart-Hart equation to find the temperature as described in the previous Chapter:
Figure 9.1: Circuit diagram to measure temperature using a thermistor.
● 144
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 144
11/10/2022 13:55
Chapter 9 • PID Temperature Control with the Arduino Uno
Program listing: Figure 9.2 shows the program listing (Program: thermistor2). At the beginning of the program, the Thermistor is assigned to analog port A0. Next, the thermistor parameters and series resistor value are defined. Inside the setup() function, the Serial Monitor is configured at 9600 baud. The function Calc_Temperature() calculates the thermistor temperature and returns it to the main program where the temperature is displayed every second on the Serial Monitor, as shown in Figure 9.3. //-------------------------------------------------------------------------//
READING THE TEMPERATURE OF A THERMISTOR
//
=======================================
// // This program reads and displays the temperature of a thermistor // // Author: Dogan Ibrahim // File
: thermistor2
// Date
: June, 2022
//--------------------------------------------------------------------------int Thermistor = A0; int B = 3950;
// Thermistor B
float R0 = 100000.0;
// Thermistor R0
float Rs = 100000.0;
// Series resistor
float Vo, Rt, R, T, Temperature, T0 = 298.15; unsigned int adc; // // Configure the Serial Monitor at 9600 BAud // void setup() { Serial.begin(9600); } // // This function calculates and returns the temperature in C // float Calc_Temperature() { adc = analogRead(Thermistor);
// Read voltage
Vo = adc * 5000.0 / 1024.0; Rt = Rs * (5000.0 - Vo) / Vo;
// Thermistor resistance
R = log(Rt / R0); R = R / B; T = R +1 / T0; T = 1 / T; T = T - 273.15;
// Temperature in C
return T;
● 145
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 145
11/10/2022 13:55
PID-based Practical Digital Control
}
void loop() { Temperature = Calc_Temperature();
// Read temperature
Serial.println(T);
// Display temperature
delay(1000);
// Wait 1 seconds
}
Figure 9.2: Program: thermistor2.
Figure 9.3: Displaying the temperature.
9.3 Project 2: PID Temperature Control Description: This is the Arduino Uno program PID temperature controller which controls the temperature of the 3D printer hot bed shown in Figure 8.1. Block diagram: Figure 9.4 shows the block diagram of the project. The temperature of the hotbed is measured with the built-in thermistor as described in Project 1. This temperature value is fed back to the Arduino Uno where the PID algorithm is implemented to control the temperature so that it is at the SetTemp. In this project, SetTemp is set to 50 ºC. The MOSFET switch is driven by the Raspberry Pi PWM (Pulse Width Modulated) output signal and it provides the high current required by the hotbed by switching he external power supply.
● 146
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 146
11/10/2022 13:55
Chapter 9 • PID Temperature Control with the Arduino Uno
Figure 9.4: Block diagram of the project. Circuit diagram: Figure 9.5 shows the circuit diagram of the project. Notice that because the output port voltages of the Arduino Uno are +5 V, there is no need to use logic level convertor chip. On Arduino Uno, the PWM pins are numbers 3, 5, 6, 9, 10, and 11. The frequency of the PWM signal at pins 5 and 6 will be about 980 Hz and 490 Hz on the other pins. The PWM pins are labeled with the tilde (~) sign.
Figure 9.5: Circuit diagram of the project. Proportional + Integral (PI) controller parameters A PID-type controller was designed, but initially the derivative term was set to 0 so that you had a PI controller. The following PI controller parameters were chosen since the system is similar to the one given in the previous Chapter, but the PWM range is different:
The parallel PI realization shown in Figure 6.1 was used in this project.
● 147
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 147
11/10/2022 13:55
PID-based Practical Digital Control
Program listing: In Arduino Uno the PWM duty cycle range is 0 to 255, where 0 corresponds to 0% and 255 corresponds to 100% duty cycle. The statement analogWrite(pin, duty cycle) sets the duty cycle on the specified pin. Figure 9.6 shows the program listing (Program: PIDtemp2). Inside the setup() function, the Serial Monitor was initialized to 19200 baud, the MOSFET switch is configured as an output, and finally the PID parameters are defined. The function Calc_Temperature() calculates and returns the thermistor temperature to the main program loop. The function PID() is where the PID algorithm is implemented. Inside the main program loop, the temperature is read and function PID() is called. The time response of the system is plotted using the Tools Serial Plotter of the Arduino IDE. It is important to make sure that the loop time of the program does not exceed 1 second since the sample time is set to one second. The time response is plotted in real time as it happens. If the required sample time is very small as the plotting may affect the sample time. It is also possible to store the response time values in an array and then plot them offline. //-------------------------------------------------------------------------//
TEMPERATURE PID CONTROLLER
//
==========================
// // This is teh Arduino Uno PID temperature controller. The desired temperature // is set to 50 Degrees C // // Author: Dogan Ibrahim // File
: PIDtemp2
// Date
: June, 2022
//--------------------------------------------------------------------------int Thermistor = A0; int B = 3950;
// Thermistor B
float R0 = 100000.0;
// Thermistor R0
float Rs = 100000.0;
// Series resistor
float Vo, Rt, R, T, Temperature, adcconv, T0 = 298.15; float sk, Kp, Ti, Td, pk, pk_1, ek, ek_1, a, b, yk, qk, wk, uk; unsigned int adc; int MOSFET = 3; // // Configure PWM pin and Initialize variables // void setup() { Serial.begin(19200); pinMode(MOSFET, OUTPUT); sk = 50.0; Kp = 6.5;
// Proportional
● 148
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 148
11/10/2022 13:55
Chapter 9 • PID Temperature Control with the Arduino Uno
T = 1.0;
// Sample time
Ti = 70.0;
// Integral
Td = 0.0;
// Derivative
a = Kp*T/Ti; b = Kp*Td/T; pk = 0.0; pk_1 = 0.0; ek_1 = 0.0; adcconv = 5000.0 / 1024.0; } // // This function calculates and returns the temperature in C // float Calc_Temperature() { adc = analogRead(Thermistor);
// Read voltage
Vo = adc * adcconv; Rt = Rs * (5000.0 - Vo) / Vo;
// Thermistor resistance
R = log(Rt / R0); R = R / B; T = R +1.0 / T0; T = 1.0 / T; T = T - 273.15;
// Temperature in C
return T; } // // This is the PID function // void PID() { ek = sk - yk; pk = a*ek + pk_1; wk = Kp*ek; qk = b*(ek - ek_1); uk = wk + pk + qk; if(uk > 255.0) uk = 255; if(uk < 0) uk = 0; analogWrite(MOSFET, uk); pk_1 = pk; ek_1 = ek; }
● 149
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 149
11/10/2022 13:55
PID-based Practical Digital Control
void loop() { yk = Calc_Temperature(); PID(); Serial.println(yk); delay(1000);
// Wait 1 seconds
}
Figure 9.6: Program: PIDtemp2. Figure 9.7 shows the time response of the system with the PI controller, where the desired SetTemp was set to 50 ºC. The response shows a small overshoot and settles down to 50 ºC.
Figure 9.7: Time response with PI controller in action. Figure 9.8 shows the time response of the system with:
By adding the following derivative action, the response is shown in Figure 9.9:
● 150
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 150
11/10/2022 13:55
Chapter 9 • PID Temperature Control with the Arduino Uno
Here again, you have some overshoot and the response settled at 50 ºC.
Figure 9.8: Time response with PI controller.
Figure 9.9: Time response with PID controller. Notice that the sample time is set to 1 second, but this is not very accurate since the delay() function is not accurate and the code executed before the delay() function is not considered.
● 151
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno 220802 v3 UK.indd 151
11/10/2022 13:55
PID-based Practical Digital Control
9.4 Project 3: PID Temperature Control with Arduino Uno and Timer Interrupts Description: The delay time of the Arduino is not very accurate and this affects the sample time of the PID. For accurate sample timing you can use timer interrupts and execute the PID algorithm inside the timer interrupt service routine. In this project, you have modified the program and introduced 1 second timer interrupts and moved the PID algorithm to within the interrupt service routine. The block diagram and circuit diagram of the project are as before. Program listing: Figure 9.10 shows the program listing (Program: PIDtemp3). Parts of the program are similar to Figure 9.6, but here timer interrupts are enabled. In this project, you want to generate timer interrupts every second. i.e., the frequency of the interrupts is 1 Hz. Using a Prescaler value of 1024, the value of the compare match register is calculated to be: Compare match register = [16,000,000/ (1024 * 1)] – 1 = 15624 Timer 1 interrupts are enabled inside the setup() function with the following code: TCCR1A = 0;
// Set to 0
TCCR1B = 0;
// Set to 0
TCNT1
// Set counter to 0
= 0;
OCR1A = 15624;
// Compare reg value
TCCR1B |= (1 Analog and digital sensors > > Transfer functions and continuous-time systems > First-order and second-order > system time responses > Discrete-time digital systems > > Continuous-time PID controllers > Discrete-time PID controllers >
ON-OFF temperature control with Raspberry Pi and Arduino Uno PID-based temperature control with Raspberry Pi and Arduino Uno PID-based DC motor control with Raspberry Pi and Arduino Uno PID-based water level control with Raspberry Pi and Arduino PID-based LED-LDR brightness control with Raspberry Pi and Arduino Uno
Prof Dogan Ibrahim has a BSc, Hons. degree in Electronic Engineering, an MSc degree in Automatic Control Engineering, and a PhD degree in Digital Signal Processing. Dogan has worked in many industrial organizations before he returned to academic life. He is the author of over 70 technical books and has published over 200 technical articles on electronics, microprocessors, microcontrollers, and related fields. The full program listings of all the projects discussed in the book may be downloaded free of charge from the Elektor Store website, www.elektor.com (search for: book title).
Elektor International Media BV www.elektor.com
PID-based Practical Digital Control • Dogan Ibrahim
PID-based Practical Digital Control
PID-based Practical Digital Control With Raspberry Pi and Arduino Uno # d e f in e P h a s e A 2
/ / Phase A
# d e f in e P h a s e B 3
/ / Phase B
# d e f i n e P WM 5
/ / P WM p i n
# d e f i n e DIR 4
/ / DIR p i n
f l o a t s k , K p , T i, T d , p k , T , p k _ 1, e k , e k _ 1, a , b , y k , q k , w k , u k ; v o l a t i l e u n sig n e d l o n g C o u n t = 0;
/ / Encode r coun t
f l o a t c o n v = 15 0.0 / 9 0.0; / / / / C o n f i g u r e P WM p i n a n d I n i t i a l i z e v a r i a b l e s / / v o i d s e t u p () { T C C R 2 B = T C C R 2 B & B 11111 0 0 0 | B 0 0 0 0 0 0 11; p i n M o d e ( D I R , O U T P U T );
/ / Di r e c t i o n i s o u t p u
d i g i t a l W r i t e ( D I R , L O W); p i n M o d e ( P WM, O U T P U T );
/ / P WM i s o u t p u t
p i n M o d e ( P h a s e B , I N P U T );
/ / P h a s e B is in p u t
p i n M o d e ( P h a s e A , I N P U T );
/ / P h a s e A is in p u t
a t t a c h I n t e r r u p t ( d i g i t a l P i n T o I n t e r r u p t ( P h a s e B ), E n c o d e r I S R , R I S
a t t a c h I n t e r r u p t ( d i g i t a l P i n T o I n t e r r u p t ( P h a s e A ), E n c o d e r I S R 2 , R S e r i a l . b e g i n (1 9 2 0 0 );
Dogan Ibrahim