Implementing an Arduino based Temperature Controller with PID algorithm Seyedreza Fattahzadeh
© 2015 Seyedreza Fattahzadeh
[email protected] [email protected] No part of this book maybe reproduced, in any form or by any means, without permission in writing from the author / publisher.
NOTICE TO THE READER All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher. Every effort has been made to ensure our books are as accurate as possible. However, there may be mistakes, both typo and in content. This content should be used as a general guide and not as the solution. The author does not warrant or guarantee any of the products described herein. Also, the author does not warrant or guarantee any of the equipment or programs described herein or accept liability for any damages resulting from their use. The reader is warned that both electricity and the construction of electrical equipment can be dangerous. It is the responsibility of the reader to use common sense and safe electrical and mechanical practices. ATmega8, AVR® 8- and 32-bit microcontrollers are trademarks of Atmel Corporation. CodeVisionAVR compiler software is trademark of DELCOMp Company. Arduino software and Arduino board are trademarks of Arduino Company. Altium Designer ® is a registered trademark of Altiume Company. Proteus is software for microprocessor simulation, schematic capture, and printed circuit board (PCB) design. It is developed by Lab center Electronics Ltd. Please be informed that: This book contains many images. Since eReaders don’t always display images well, upon request, I will provide you with the PDF file which contains the complete e-Book, including the images, if you need an easier-to-read format. To receive a PDF version of this e-book or any other software which is mentioned in the content of this text, you can email me the proof of your purchase of the kindle version of the book from Amazon.com to
[email protected]. Upon receipt of that proof, a PDF version will be sent to your email address.
Table of Contents Preface About the Author How to use this book Read me first Chapter 1: Microcontroller systems Abstract Resistance Temperature Detector (RTD) Temperature Sensors Microcontroller based RTD temperature measurement Microcontroller systems ATmega8 microcontroller Application of CodeVisionAVR C Compiler Chapter 2: Temperature and its Measurement Abstract The design of the controller system with a single board microcontroller Microcontroller's controlling method An On-Off controller The microcontroller's system specifications Structure of the microcontroller program Integrated Circuit Temperature Sensors Replacing PT100 sensor with LM35 temperature sensor Chapter 3: Explanation on how to design hardware and software Abstract Design and simulation of hardware using Proteus 7.8 software. Using CodeVisionAVR V 2.05 software to generate the control program. Brief explanation of the solution software Using Proteus 7.8 software to simulate the control program. Uploading the control program into the ATmega8 microcontroller (hex file) Using Altium Designer software to build the PCB of the controller Chapter 4: PID Controller with an Arduino board Project specification of the system Generating the main Control Code for the Arduino Microcontroller
Getting to manufacturing the PCBs of the project Uploading the control program into the Arduino board Questions and answers related to these projects Conclusion Good informative links Appendix A – Slope of a straight line Appendix B – PID (Proportional Integral Circuit) My product list
Preface The purpose of a temperature control system is to maintain a device at a constant temperature. Two types of actuators are commonly used to precisely control the temperature. One is a thermoelectric and the other is a resistive heater. A precision temperature controller uses a current or voltage source to drive power through these actuators based on feedback from a temperature sensor. Temperature sensors come in many different forms and a number of techniques have evolved for the measurement of temperature. The majority of sensors still require the solid, liquid, or the gas whose temperature is to be measured. Four technologies are currently in use: thermocouples (TCs), thermistors, resistance temperature detectors (RTDs), and IC sensors. This book is an engineer's guide to planning, designing, and implementing a temperature based control system using a microcontroller. ATmega8 microcontrollers and Arduino Mega2560 board will be used in our project. The book will also prove invaluable for students and experimenters seeking real-world project work involving the use of microcontroller. Engineers involved in the use of microcontrollers in measurement and control system, will find it an invaluable practical guide, providing design principles and application case studies back up with sufficient control theory and electronics to develop their own systems. Pre-requisites for the book are knowledge of mathematics, a programming language, some classical control theory and a good familiarity with the programming and hardware structure of any kind of a typical microcontroller, which is usually possessed by most engineers during their undergraduate studies. The programs in this manual were written for ATmega8 micro controller using CodeVision software and also Arduino software for Arduino Mega2560 board. But the ideas and program layouts are universal to any micro controller. The final aspect of this experiment was to organize a main control code in C language to control the whole system hardware intelligently. Hence the purpose behind developing a manual like this is an attempt to make learning microcontroller more enjoyable!
About the Author Seyedreza Fattahzadeh holds a Bachelor of Science in Electrical Engineering from the University of Texas at Arlington. His main expertise is in digital systems, electronics, and computer engineering. Seyedreza has extensive experience in the field of programmable controllers. He worked for a few industrial manufacturers as a programmable controller consulting firm. His industrial experience includes designing and implementing mid - class automation systems, based upon PLC. Seyedreza has authored several other books about programmable controllers. You can find more info on these at the end of this book.
How to use this Book This book details the generation of code for an ATmega8 Microcontroller and Arduino board to control a temperature process in general. This book has been prepared for those who are already familiar with basic instructions related to any brand of Microcontroller and may have already developed some Microcontroller -based programs for different purposes. Therefore, this text is prepared for those who want to challenge their programming knowledge to generate even more complex programs with extra features. The project specification will be presented to you. It contains all goals, functionality, and details required for a development of this controller system to fulfill the project's typical minimum requirements. Study the project requirements presented in this text carefully. Your job is to generate the main control program to satisfy the project's requirements. Take as much time as you think it is needed. You can use a pen and paper, any typical simulator software to develop the control program. When you have completed your project, review and compare it with the one presented in this text. If your solution is working properly, then you can celebrate your accomplishment and perhaps go on to learn something new about your level of capability where it comes to Microcontroller programming. If the solution you came up with has some problem(s), and somehow it is not functioning as it is supposed to, then you can compare your solution against mine. In this case, you know that you did your best, and tried it on your own and you can use my solution to find out what is wrong with yours. When you find out what went wrong, then you can resolve the issue to make it function correctly. That is the whole purpose of this text; to give you enough motivation and make you enthusiastic to complete a relatively complex Microcontroller based program. The main control program solution is prepared in C language using CodevisionAVR and Arduino software. In addition, the schematic of all the hardware used in this project is provided. The amount of effort you want to place on doing this project is completely up to you and your interest. If you wish, you can build your own controller hardware similar to the one presented in this text or even tailor it to the one with more features as you prefer. In either case, even by simulating the presented program and checking its performance, you can improve your programming knowledge and ultimately, from my side, this the overall purpose behind developing the text.
Read me first – The software developed for the project Chapter 2 and 3 are devoted to the design and implementation of a Temperature Controller system using an AVR Microcontroller (e.g. Atmega8). You can use the following link to see its performance: http://youtu.be/mIyixludYaE Chapter 4 is devoted to redesigning the same controller system using the Arduino Mega 2560 board. You can use the following link to see the performance of this project with Arduino board: http://youtu.be/i2nxqLs9wBg Table below explains the files developed for this project explained in this text. These files are not included in the text. To get these files emailed to your address, please contact me as you are directed in the 'Please be informed' section of this text'. Files related to AVR project Simulation Proteus based file: tc.DSN Codvision based generated file: tempc.c pcb_temp.PcbDoc (Main Controller board layout) Files related to Arduino project PIDtempController_LCD.ino (Main controller file) TC-Arduino.PcbDoc (Main controller board layout)
Chapter 1: Microcontroller systems Abstract This text analyzes the temperature control system of a simplified dyeing machine in the textile industry, adapts the technology of a single board computer to automatically control the temperature. The spot test of the usage of the controller proved that it could fulfill the basic requirement of the dyeing machine in terms of the temperature. The parameters of the textile technology are numerous, which generally includes temperature, pressure, flux, liquid position, length, speed and displacement. The dyeing technology of the textile has strict requirements of the temperature, and the temperature ascending process, keeping process, descending process of the dyeing trough must be in accordance with the technical requirements, and the manual control is very difficult. Therefore, the automatic temperature control of the dyeing machine is very important. The control system is required to freely set up the temperature ascending curve, temperature keeping curve, temperature descending curve, and the operation time, actual temperature and process temperature in the work process can be displayed to ensure the right implementation of the technology.
Resistance Temperature Detector (RTD) Temperature Sensors RTD's Principle of Operation An RTD (resistance temperature detector) is a temperature sensor that operates on the measurement principle that a material’s electrical resistance changes with temperature (Figure 1.1). The relationship between an RTD’s resistance and the surrounding temperature is highly predictable, allowing for an accurate and consistent temperature measurement. By supplying an RTD with a constant current and measuring the resulting voltage drop across the resistor, the RTD’s resistance can be calculated, and the temperature can be determined.
Figure 1.1: A typical RTD sensor used in the project
RTD Materials Different materials used in the construction of RTDs offer a different relationship between resistance and temperature. Temperature sensitive materials used in the construction of RTDs include platinum, nickel, and copper; platinum being the most commonly used. Important characteristics of an RTD include the temperature coefficient of resistance (TCR), the nominal resistance at 0° Celsius, and the tolerance classes. The TCR determines the relationship between the resistance and the temperature. The nominal resistance of the sensor is the resistance that the sensor will have at 0° Celsius. Although almost any value can be achieved for nominal resistance, the most common is the platinum 100 ohm (PT100) which is the type used in this project. Finally, the tolerance class determines the accuracy of the sensor, usually specified at the nominal point of 0° Celsius. There are different industry standards that have been set for accuracy.
RTD Configurations In addition to different materials, RTDs are also offered in two major configurations: wire wound and thin film. Wire wound configurations feature either an inner coil RTD or an outer wound RTD. An inner coil construction consists of a resistive coil running
through a hole in a ceramic insulator, whereas the outer wound construction involves the winding of the resistive material around a ceramic or glass cylinder, which is then insulated. The thin film RTD construction features a thin layer of resistive material deposited onto a ceramic substrate through a process called deposition. A resistive meander is then etched onto the sensor, and laser trimming is used to achieve the appropriate nominal values of the sensor. The resistive material is then protected with a thin layer of glass, and lead wires are welded to pads on the sensor and covered with a glass dollop.
Operations of RTD An RTD takes a measurement when a small DC current is supplied to the sensor. The current experiences the impedance of the resistor, and a voltage drop is experienced over the resistor. Depending on the nominal resistance of the RTD, different supply currents can be used. To reduce self-heating on the sensor the supply current should be kept low. In general, around 1mA or less of current is used. An RTD can be connected in a two (Figure 1.2), three (Figure 1.3), or four-wire (Figure 1.4) configuration. The two-wire configuration is the simplest and also the most error prone. In this setup, the RTD is connected by two wires to a Wheatstone bridge circuit and the output voltage is measured. The disadvantage of this circuit is that the two connecting lead wire resistances add directly to the RTD’s resistance and an error is introduced.
Figure 1.2 Two-wire configuration
Figure 1.3: Three-wire configuration is the one used in this project
Figure 1.4: Four-wire configuration When long leads are used (e.g. greater than about 5 meters), it is necessary to compensate for the lead wires. In the four –wire measurement method, one pair of wires carry the current through the RTD, the other pair senses the voltage across the RTD. Since only a negligible current flows through the sensing wires carrying the current, RL2 and RL3 are the lead wires for measuring the voltage across the RTD. This configuration is ideal for canceling the lead wire resistances in the circuit as well as eliminating the effects of different lead resistances, which is a likely problem with the three-wire configuration. The four-wire configuration is commonly used when a highly accurate measurement is required for the application. For purposes of linearity, it is important that the current generation circuit supplies a stable excitation to the RTD. Once a stable excitation current is applied to the RTD, the
signal conditioning path of the circuit cancels lead resistances, amplifies the signal and converts the signal to the digital form using an ADC, which can then be read by a controller.
Microcontroller based RTD temperature measurement RTDs give analogue output voltage and the measured temperature can simply be displayed using an analogue meter (e.g. voltmeter). Although this may be acceptable for some applications, accurate temperature measurement and display require digital techniques. Figure 1.5 shows how the temperature can be measured using an RTD and a microcontroller. The temperature is sensed by the RTD and a voltage is produced which is proportional to the actual temperature. This voltage is filtered using a low-pass filter to remove any unwanted high frequency noise components. The output of the filter is then amplified using an operational amplifier so that this output can be fed to an A/D converter. The digitized voltage is then read by the microcontroller and the resistance of the RTD is calculated. After this the measured temperature can be calculated using an equation. Finally, the temperature is displayed on a suitable display (e.g. 7-segment display).
Figure 1.5: Measuring temperature
Microcontroller systems Microcontrollers are general purpose microprocessors which have additional parts that allow them to control external devices. Basically, a microcontroller executes a user program which is loaded in its memory. Under the control of this program, data is received from external devices (inputs), manipulated and then data is sent to external output devices. A microcontroller is a very powerful tool that allows a designer to create sophisticated I/O data manipulation algorithms. Microcontrollers are classified by the number of bits in a data word. 8-bit microcontrollers are the most popular ones and are used in many applications. 16-bit and 32-bit microcontrollers are much more powerful, but usually more expensive and not required in many small to medium general purpose applications where microcontrollers are used.
ATmega8 microcontroller ATmaga8 is one of the microcontrollers that we shall be using in our project. The prime important and summarized features of this controller are:
Pin configuration The ATmega8 has many features similar to that of ATmega32. But it has reduced its number of features and capabilities, yet it has enough features to work with. In Figure 1.6 you can find the pin diagram of Atmega8 microcontroller
Figure 1.6: ATmega8 microcontroller The following items are the main features of ATmega8. Memory: It has 8 Kb of Flash program memory (10,000 Write/Erase cycles durability), 512 Bytes of EEPROM (100,000 Write/Erase Cycles). 1Kbyte Internal SRAM. I/O Ports: 23 Input lines can be obtained from three ports; namely Port B, Port C and Port D. Interrupts: Two External Interrupt source, located at port D. 19 different interrupt vectors supporting 19 events generated by internal peripherals. Timer/Counter: Three Internal Timers are available, two 8 bit, one 16 bit, offering various operating modes and supporting internal or external clocking. SPI (Serial Peripheral interface): ATmega8 holds three communication devices
integrated. One of them is Serial Peripheral Interface. Four pins are assigned to Atmega8 to implement this scheme of communication. USART: One of the most powerful communication solutions is USART and ATmega8 supports both synchronous and asynchronous data transfer schemes. It has three pins assigned for that. In many projects, this module is extensively used for PC-Micro controller communication. TWI (Two Wire Interface): Another communication device that is present in ATmega8 is Two Wire Interface. It allows designers to set up a commutation between two devices using just two wires along with a common ground connection. As the TWI output is provided by means of open collector outputs, external pull up resistors are required to complete the circuit. Analog Comparator: A comparator module is integrated in the IC that provides comparison facility between two voltages connected to the two inputs of the Analog comparator via External pins attached to the micro controller. Analog to Digital Converter: Inbuilt analog to digital converter can convert an analog input signal into digital data of 10bit resolution. For most of the low end applications, this degree of resolution is enough.
Application of CodeVisionAVR C Compiler Microcontrollers are usually programmed using the assembly language. The language consists of various mnemonics which describe the instructions. An assembly language is unique to a microcontroller and the assembly language of a certain microcontroller cannot be used for any other type of microcontroller. Although the assembly language is very fast, it has some major disadvantages. Perhaps the most disadvantage is that the assembly language can become very complex and difficult to maintain. It is usually a very time consuming task to develop large projects using the assembly language. Program debugging and testing is also considerably more complex and it requires more time. Microcontrollers can be programmed using some of the popular high-level languages. For example, it is possible to use BASIC, PASCAL, or C compilers to program ATmgega8 microcontroller. Most of these compilers generate native machine code which can directly be loaded into the memory of the target microcontroller. In this project, we are going to use a typical commercial C compiler for the Atmel AVR microcontrollrs. CodeVisionAVR is the only Integrated Development Environment on the market that features an Automatic Program Generator for the new XMEGA devices. To get more information about CodeVisionAVR compiler, please you may refer to the following link: http://www.hpinfotech.ro/cvavr_download.html Using 3 × 3-digit 7-segment displays One thing all microcontrollers lack is some kind of video display. A video display would make a microcontroller much more user-friendly as it will enable text messages and numeric values to be output in a more versatile manner. A seven-segment display (SSD), or seven-segment indicator, is a form of electronic display device for displaying decimal numerals that is an alternative to the more complex dot matrix displays. Seven-segment displays are widely used in digital clocks, electronic meters, and other electronic devices for displaying numerical information. In this project, I used 3 × 3-digit 7-segment displays to show the amount of SV, PV temperature values in° Celsius and Time (in minutes) respectively.
Chapter 2: Temperature and its Measurement Abstract The control objective is the sample dyeing machine, and the structure of its temperature system is shown in Figure 2.1. The temperature control range of the system is from about 25 to 100° Celsius. When the dyeing machine is working, the temperature of the water in the dyeing trough must be changed according to the technical requirements. If the temperature is lower than the set value, the controller should turn the hot water valve on, and if the temperature of the water is higher, the hot water valve must be turned off (and in our case, the cold water valve will be turned on). See Figure 2.1.
Figure 2.1: The temperature system of a sample dyeing machine Note: 1- Water, 2- Hot water valve, 3- The cold water valve, 4- Dyeing trough, 5- PT100 sensor, 6- A single board microcontroller A common temperature controller can implement temperature keeping control, which is used in some earlier dyeing machines, and if the automatic ° is further enhanced to make the equipment ascend, keep and descend the temperature according to needed speed until the whole process ends, the simple temperature control can not fulfill these requirements, and it is necessary to design a sort of reliable, different fully automated temperature control system with perfect functions.
The design of the controller system with a single board microcontroller In the industry, there are many methods to control the temperature, but here I chose to design and implement a single board microcontroller to implement the controller system. Figure 2.2 is the sketchy structure of the temperature control system.
Figure 2.2: The sketchy structure of PLC control system Note: 1- 220 V AC heater element 2- SSR to control the heater element 3- An electric solenoid the cold water valve 4- An ORDEL made signal transmitter 5- A PT100 sensor 6- A single board microcontroller The set parameters regarding Temperature Time table data is going to be included in the microcontroller's control software program. The microcontroller reads the data many times a minute via the PT100 sensor as an analog voltage. A/D section of the microcontroller transforms the temperature value to some digital number and the microcontroller uses that to compute the process value (PV). Through analysis and
computation, microcontroller can exactly decide when to turn either the heater element or cooling electromagnetic valve on or off to control the temperature.
Microcontroller's controlling method Figure 2.3 illustrates a typical temperature process curve of the dyeing machine which shows both temperature verses time in both table and graph. The temperature verses time graph shows the rate of change of temperature. It will be positive if the temperature is increasing with time and negative if it is decreasing. According to this Figure 2.3, the temperature linearly changes with the subsection. All data related to 8 steps shown in this figure (7 slope and last step is to turn the system off) are included in the software. When operator depresses the START button on the single PCB, the microcontroller automatically starts computing the corresponding time and temperature value of all points on the curve. And it decides either to turn on any output device or turn it off to maintain the liquid's temperature based on the graph shown on figure 2.3.
Figure 2.3: temperature verse time table and its graph Let's assume that 20 minutes have passed ever since the START pushbutton is depressed by the operator. Process value (PV temperature given by the sensor) is equal to 25 .00° Celsius. Microcontroller calculates SV (set value) value in few microseconds to decide what to do. Based on equation shown on figure 2.4, the slope of the line is 0.25 and that y = mx + b is a linear equation, so the graph is a straight line. In order to build the graph, you have to plug in values for x, and find the values for y. with m = 0.25, and x (Time = 20 minutes) = 20, then the amount of y is going to be calculated as following: y = SV (set point value) = 0.25 (20) + 25 = 5 + 25 = 30° Celsius. SV = 30 VS PV = 25 since SV > PV the temperature of water must be increased. Therefore, the controller turns SSR #2 (SSR stands for Solid State Relay) on (which causes heater to be turned on).
Figure 2.4: Temperature control
An On-Off controller A temperature controller is an instrument used to control temperature. It does this by comparing the process temperature (PV or process variable) with the desired value (SV or set value). The difference between these values is known as the error (deviation). Temperature controllers use this error to decide how much heating or cooling is required to bring the process temperature back to the desired value. Once this calculation is complete the controller will produce a signal that effects the change required. This output signal is known as the manipulated value and is normally connected to a heater, control valve, fan or some other “final control element” which actually injects or removes heat from the process. Temperature controllers form one of the four parts of a temperature controlled system. To help visualize this I will consider a water heating system. The four parts would be: 1. The container 2. The water heating pipes 3. Thermometer (PT100 sensor) 4. The controller system The role of the temperature controller is to measure the temperature on thermometer, compare it to the set point and to calculate the amount of time the hot water solenoid valve should remain switched on to maintain a constant temperature. To ensure reliable control, controller needs to know the true temperature. So, the first thing we need to know is what type of temperature probes is being used in the system. This will be the input to the controller. In Figure 2.1, we used a PT100 sensor. 1. We also need to consider what the controller is going to be connected to, so that it can change the temperature. In our case, I will be using a 220 VAC output terminal port to switch a 220 V AC solid state relay (SSR # 2) that can be switched on and off, to cause heater element to be turned on or off to control the temperature of the water. 2. How accurately we need to control the temperature will also determine the type of temperature controller that we tend to use. Three basic types are normally considered: On/OFF control, PID control and Fuzzy Logic control. In control theory, an on–off controller, also known as a hysteresis controller, is a feedback controller that switches abruptly between two states. These controllers may be realized in terms of any element that provides hysteresis. On/ off control is like operating a switch. This type of temperature controller will turn on the heat when the process variable is below the set point and turn it off when the process variable is above the set point. These controllers normally include a delay, to reduce the cycling when the process variable is close to the set point. See Figure 2.5. Notice that in Figure 2.5 the OFF period corresponds to the trailing edges (negative slopes) of the sine wave.
Figure 2.5: The performance of the ON-OFF controller I choose to design and implement a single board computer with ATmega8 microcontroller to perform the function of temperature controller. As you all know, natural environment is all analog. From temperature to seismic waves and from wind to fire every value is continuous in nature. But the problem is that all electronics is turning into digital, a non-continuous domain. So to acquire data from the environment we use an ADC (Analog to Digital Converter). ATmega8 has 6 ADCs have a 10 bit resolution. This means that the highest value in decimal system is 1024. I used an UST200 (model 01 made by ORDEL company) analog signal transmitter to convert analog signal coming from a PT100 sensor to a DC voltage of value between 0 to 10 volt at its output terminal installed on the body of the dyeing machine. Most A/D boards (including ATmega8's input signal level are 0 to 5 V DC) will accept a 0-5Vdc signal, but the output signal of my transmitter is 0 to 10 volt DC. So I designed a voltage shifter circuit to change the transmitter's voltage which is 0 to 10 volt DC to 0 to 5 volts DC to make it compatible for the ATmega8's A/D input pins. In Figure 2.2 you can view the level shift CKT which consists of two 4.9 K Ohm resistors.
The microcontroller's system specifications Here, a complete temperature measurement system will be described in this section using an RTD as the sensor. In this project, the temperature is calculated using an ATmega8 microcontroller and then displayed every 20 milliseconds on a 3-digit 7segment display. The complete circuit diagram, the program code, simulation software developed for Proteus, and program source code (in binary format) to be written inside of the microcontroller by any type of programmer. The system is required to have the following specifications: Temperature range: 0 to 100 degree Celsius, accurate to a few ° Sensor type:
PT100
Display type:
3 × 3-digits 7-segment displays
Display format:
9 characters, displayed as xxx
Display update:
xxx milliseconds
System:
ATmega8 microcontroller
The circuit diagram The complete circuit diagram is shown in Figure 2.6. A standard PT100 is connected to a +24 volt transmitter voltage source. The output of the transmitter is connected to input pin of the microcontroller.
Figure 2.6: Circuit diagram of the temperature measurement system The output of transmitter is sent to one of the A/D converter channels of the ATmega8's microcontroller which is operated from an internal crystal clock source. 3 × 3-digts 7-segments are tied to output ports of ATmaga8, as shown in Figure 2.7.
Figure 2.7: Enlarged circuit diagram with regard to 7-segment displays.
Operation of the Circuit The voltage across the PT100 is converted into a analogue voltage between 0 to 10 V DC which is then changed to voltage of 0 to 5 V DC by the level shift circuit and is sent to the microcontroller. The PV, SV temperature values then are calculated, and microcontroller determines which of the output terminal port has to be activated.
Structure of the microcontroller program The structure of a C program developed for a microcontroller is basically the same as the structure of a standard C program, with a few minor changes. The structure of a typical microcontroller based C program is always advisable to describe the project at the beginning of a program using comment lines. Any microcontroller specific header files should then be included for the type of target processor used. The lines of the main program and any functions used should also contain comments to clarify the operation of the program.
Program Description Language Flowcharts have been used extensively in the past in many computer programming tasks. In this section we shall be looking at a flowchart describing the operation of the controller software. See Figure 2.8.
Figure 2.8: A flowchart of the microcontroller program. The following code is the complete program. ///Beginning of main program/// #include
#include #define heater PORTD.0 #define cool_water PORTD.1 unsigned char k=0,j=1,s,min_time,count=0,i=0,seg[9],dsp[10]= {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xd8,0x80,0x90}; unsigned char key1,key2,key3,key4,key5,key6,key7; unsigned long sec=0,m1,m2,m3,m4,m5,m6,m7; int show_temp=0,time=0,stemp=0,temp=0,ave_temp[10],final_temp;
unsigned int t0=25,t1=35,t2=50,t3=65,t4=80,t5=80,t6=90,t7=45; unsigned long c1=40,c2=48,c3=60,c4=80,c5=100,c6=120,c7=140; // Part 5: void show() { seg[0]=temp%10; seg[1]=(temp/10)%10; seg[2]=(temp/100)%10; seg[3]=stemp%10; seg[4]=(stemp/10)%10; seg[5]=(stemp/100)%10; seg[6]=min_time%10; seg[7]=(min_time/10)%10; seg[8]=(min_time/100)%10; } void finish() { TCCR2=0x00; time=0; s=0; sec=0; min_time=0; heater=0; cool_water=0; } // External Interrupt 0 service routine interrupt [EXT_INT0] void ext_int0_isr(void) { // Place your code here TCCR2=0x04; time=0; s=0; sec=0; min_time=0; heater=0; cool_water=0; stemp=t0; } // External Interrupt 1 service routine
interrupt [EXT_INT1] void ext_int1_isr(void) { // Place your code here finish(); } //Part 5: // Timer 0 overflow interrupt service routine interrupt [TIM0_OVF] void timer0_ovf_isr(void) { // Place your code here count++; if(count>0) { count=0; switch(i) { case 0: PORTD.4=0; PORTB=~dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=~dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=~dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=~dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=~dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=~dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=~dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=~dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=~dsp[seg[i]]; PORTD.4=1; break; /*case 0: PORTD.4=0; PORTB=dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=dsp[seg[i]]; PORTD.4=1; break;*/ } i++; if(i>8) i=0; }
show_temp++; } // Timer2 overflow interrupt service routine interrupt [TIM2_OVF] void timer2_ovf_isr(void) { // Place your code here time++; if(time>500) { time=0; sec++; s++; if(s>59) { s=0; min_time++; } //Part 2: ///////// Step 1 /////////////////// if((sec>0)&&(secc1)&&(sec
if(sec%m2==0) stemp++; } if(key2==1) { if(sec%m2==0) stemp—; } } if(sec==c2) stemp=t2; ///////// Step 3 /////////////////// if((sec>c2)&&(secc3)&&(sec
} } if(sec==c4) stemp=t4; ///////// Step 5 /////////////////// if((sec>c4)&&(secc5)&&(secc6)&&(sec
if(key7==0) { if(sec%m7==0) stemp++; } if(key7==1) { if(sec%m7==0) stemp—; } } if(sec==c7) stemp=t7; //Part 4: if(temp<(stemp-2)) { heater=1; cool_water=0; } if(temp>(stemp+2)) { heater=0; cool_water=1; } if((temp>=(stemp-2))&&(temp<=(stemp+2))) { heater=0; cool_water=0; } if(sec>c7) { finish(); } } TCNT2=0x05; } unsigned int adc_data; #define ADC_VREF_TYPE 0x40 // ADC interrupt service routine
interrupt [ADC_INT] void adc_isr(void) { // Read the AD conversion result adc_data=ADCW; } // Read the AD conversion result // with noise canceling unsigned int read_adc(unsigned char adc_input) { ADMUX=adc_input | (ADC_VREF_TYPE & 0xff); // Delay needed for the stabilization of the ADC input voltage delay_us(10); #asm in r30,mcucr cbr r30,__sm_mask sbr r30,__se_bit | __sm_adc_noise_red out mcucr,r30 sleep cbr r30,__se_bit out mcucr,r30 #endasm ADCSRA|=0x40; return adc_data; } // Declare your global variables here void main(void) { // Declare your local variables here // Input/Output Ports initialization // Port B initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T PORTB=0x00; DDRB=0xff; // Port C initialization // Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In // State6=T State5=T State4=T State3=T State2=T State1=T State0=T PORTC=0x00;
DDRC=0x3e; // Port D initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T PORTD=0x00; DDRD=0xf3; // Timer/Counter 0 initialization // Clock source: System Clock // Clock value: 125.000 kHz TCCR0=0x03; TCNT0=0x00; // Timer/Counter 1 initialization // Clock source: System Clock // Clock value: Timer1 Stopped // Mode: Normal top=0xFFFF // OC1A output: Discon. // OC1B output: Discon. // Noise Canceler: Off // Input Capture on Falling Edge // Timer1 Overflow Interrupt: Off // Input Capture Interrupt: Off // Compare A Match Interrupt: Off // Compare B Match Interrupt: Off TCCR1A=0x00; TCCR1B=0x00; TCNT1H=0x00; TCNT1L=0x00; ICR1H=0x00; ICR1L=0x00; OCR1AH=0x00; OCR1AL=0x00; OCR1BH=0x00; OCR1BL=0x00; // Timer/Counter 2 initialization // Clock source: System Clock // Clock value: 125.000 kHz // Mode: Normal top=0xFF // OC2 output: Disconnected
ASSR=0x00; //TCCR2=0x04; TCCR2=0x00; TCNT2=0x05; OCR2=0x00; // External Interrupt(s) initialization // INT0: On // INT0 Mode: Falling Edge // INT1: On // INT1 Mode: Falling Edge GICR|=0xC0; MCUCR=0x0A; GIFR=0xC0; // Timer(s)/Counter(s) Interrupt(s) initialization TIMSK=0x41; // USART initialization // USART disabled UCSRB=0x00; // Analog Comparator initialization // Analog Comparator: Off // Analog Comparator Input Capture by Timer/Counter 1: Off ACSR=0x80; SFIOR=0x00; // ADC initialization // ADC Clock frequency: 62.500 kHz // ADC Voltage Reference: AVCC pin ADMUX=ADC_VREF_TYPE & 0xff; ADCSRA=0x8F; // SPI initialization // SPI disabled SPCR=0x00; // TWI initialization // TWI disabled TWCR=0x00; // Global enable interrupts #asm(“sei”) c1=c1*60; c2=c2*60; c3=c3*60;
c4=c4*60; c5=c5*60; c6=c6*60; c7=c7*60; //Part 1: ////// key 1 /////// if(t1>t0) { m1=(c1-0)/(t1-t0); key1=0; } if(t1==t0) { key1=2; } if(t1t1) { m2=(c2-c1)/(t2-t1); key2=0; } if(t2==t1) { key2=2; } if(t2t2) { m3=(c3-c2)/(t3-t2);
key3=0; } if(t3==t2) { key3=2; } if(t3t3) { m4=(c4-c3)/(t4-t3); key4=0; } if(t4==t3) { key4=2; } if(t4t4) { m5=(c5-c4)/(t5-t4); key5=0; } if(t5==t4) { key5=2; } if(t5
key5=1; } ////// key 6 /////// if(t6>t5) { m6=(c6-c5)/(t6-t5); key6=0; } if(t6==t5) { key6=2; } if(t6t6) { m7=(c7-c6)/(t7-t6); key7=0; } if(t7==t6) { key7=2; } if(t750) { show_temp=0;
ave_temp[j]=read_adc(0)/10; j++; if(j>10) { j=1; for(k=0;k<10;k++) { final_temp+=ave_temp[k]; } temp=final_temp/10; } } } } ///End of main control program///
Integrated Circuit Temperature Sensors Integrated circuit temperature sensors are semiconductor devices fabricated in a way similar to other semiconductor devices such as microcontrollers. There are no generic types like thermocouples or RTDs but some popular devices are manufactured by more than one manufacturers. Integrated circuit temperature sensors differ from other sensors in some fundamental ways: 1. These sensors have relatively small physical sizes. 2. Their outputs are liner (e.g. 10mV/°C). 3. The temperature range is limited (e.g. -40 C to + 150 C). 4. The cost is relatively low. 5. The sensors can include advanced features such as thermostat functions, builtin A/D converters and so on. 6. Often these sensors do not have good thermal contacts with the outside world and as a result it is usually more difficult to use them other than in measuring the air temperature. 7. A power supply is required to operate these sensors. Integrated circuit semiconductor temperature sensors can be divided into the following categories: Analog temperature sensors Digital temperature sensors Analog sensors are further divided into: Voltage output temperature sensors Current output temperature sensors Analog sensors can either by directly connected to measuring devices or A/D converters can be used to digitize the outputs so that they can be used in computer based applications. Digital temperature sensors usually provide I2C bus, SPI bus, or some other 3-wire interface to the outside world.
Replacing PT100 sensor with LM35 temperature sensor Why is LM35s (Figure 2.9) used to Measure Temperature? Because 1. You can measure temperature more accurately than using a thermistor. 2. The sensor circuitry is sealed and hence is not subject to oxidation, etc. 3. The LM35 generates a higher output voltage than thermocouples and may not require that the output voltage be amplified.
Figure 2.9: LM35 LM35 sensor provides a voltage output signal which is proportional to the temperature measured. It is a 3-pin device and it has two versions and they both provide a linear voltage of 10 mV/°C. The temperature range of the CZ version is -20 C to +120 C while the DZ version only covers the range 0 C to +100 C. The accuracy of LM35 is around ± 1.5 C. Figure 2.10 shows how LM35DZ can be used to measure the temperature. The device is simply connected to a 4 to 20 V power supply and the output voltage is a direct measure of the temperature in 10 mV/°C. A simple voltmeter can be connected and calibrated to measure the temperature directly. Alternatively, an A/D converter can be used to digitize the output voltage so that the sensor can be used in computer based applications.
Figure 2.10: Use LM35DZ to measure the temperature In this project we can use either LM35 or a typical PT100 sensor. Since their output voltages are not the same, when any of them is being used, some alteration both in hardware and software must be considered. Figure 2.11 shows how LM35 must be connected to input terminals of the controller.
Figure 2.11: the circuit with LM35DZ
Chapter 3: Explanation on how to design hardware and software Abstract In this Chapter 3, I would like to give you a brief explanation on how to design hardware and software of a microcontroller (ATmega8) based temperature controller. I usually take a few steps to design and implement a piece of hardware that I think would do the job. So the first step is to think about the hardware that we assume will be good enough to do what we want it to do. Thinking phase
Design and simulation of hardware using Proteus 7.8 software. Figure 3.1 displays the complete hardware schematic diagram of the temperature controller that I think of. If I assemble all those components shown on a bread board, and write a related bug free suitable software, download it into the microcontrollers user memory and execute it, controller will execute and perform the task (I have planed it in my mind) very well. So in step 1, I crank my Proteus 7.8 software up, draw the schematic of the hardware and in next step, I start developing the control software in CodeVisionAVR V 2.05 to simulate the hardware I designed in the first step.
Figure 3.1 display schematic diagram of the controller. As you see from Figure 3.1, the hardware consists of 3 ×3 digit seven segment displays to indicate PV, SV (temperature parameters) and process time in minutes. Table1.1 illustrates the bill of material related to controller hardware in Figure 3.1. Table1.1: bill of material Element name U1
Description ATmega8 microcontroller
U2
ULN2803 Seven segment buffer driver
U3, U4,U5
3 × 3 digit seven segment displays
Q1 – Q9
9 × BC107 NPN transistors
Sensor 1
LM35 temperature sensor
L1
10 micro Henry inductor coil
C1, C2
2 × 100 NF ceramic capacitors
R1, R2
2 × 10 K OHM resistors
R3, R4
2 × 1 K OHM resistors
D1, D2
Red LED, Green LED Hot & the cold water valve on/off
P1, P2
Power supply input terminals, output terminals
S1, S2
START and STOP pushbuttons
D3
Green LED 5 V DC input supply indicator
D6
1N4007 diode
Using CodeVisionAVR V 2.05 software to generate the control program. Assuming that hardware in Figure 3.1 will be good enough to do the job, I go ahead and use CodeVision AVR V 2.05 software to write the final temperature controller's coding to simulate the hardware. Figure 3.2 displays the time-temperature graph for the controller. The microcontroller must turn on/off the hot and the cold water valves to control the water temperature. Hence, I need to develop a control software program, which when loaded into the microcontroller's user memory, can use the hardware to control the temperature based on Figure 3.2.
Figure 3.2: time temperature graph for the controller.
Brief explanation of the solution software Software consists of different sections.
1. Writing equations Writing 7 equations of straight line related to the time temperature graph shown in Figure 3.3.
Figure 3.3: 7 equations of straight line related to the time temperature graph The line graph's each line segment is defined by using the following general straight line equation. m = (Y2-Y1) ÷ (X2-X1).
So, we can write 7 equations based on the Figure 3.3. m1=(c1-0)/(t0-t1); m2=(c2-c1)/(t2-t1); m3=(c3-c2)/(t 3-t2);
We must consider that in occasions where m (of each line) is either zero or a negative number, our equation will not work right. For this reason, for each line, we assume 3 conditions that must be included in the coding. According to the said conditions, we either increase the temperature, decrease it or turn off both heater and cooler control valves and do nothing. See sample coding developed in C language. if(t2>t1) {
m2=(c2-c1)/(t2-t1); key2=0; } if(t2==t1) { key2=2; } if(t2
The first condition of the above code is if slope of the line is a positive number, we use the related equation of the line the way it is. Segments numbers 1, 2, 3, 4 and 6, all have positive slops in Figure 3.3. The second condition is if slope of the line is number 0 (slope of a straight line is = 0), we do not calculate the slope. Segment 5 in Figure 3.3 has slope of 0. The third condition is if slope of the line is a negative number (when t2>t1), in the equation, I assume m2= (c2-c1)/ (t1-t2) to calculate a positive number for the slope of the line (but in this case notice that Key2=1). For example, the slope equation for segment number 7 will be: m2=(c2-c1)/(t1-t2)m = (45-90/(120-140)= 45/20= 9/4
For each of these conditions, variable key2 is set to a value that I will explain later. The conditions must be considered for each segment in the coding of the control program. Also, for more accuracy, we multiply time in minutes by 60 to convert into seconds.
2. START process In the software, two external interrupts related to mega8 are used. Two START and STOP pushbuttons are tied to those inputs. When START pushbutton is pressed, the process starts and when STOP pushbutton is depressed, the process stops. When START button is depressed, it also resets variables and turns on Timer0. This timer is set such that it generates one interrupt every 2 milliseconds. And the content of variable is increased by one unit every time the interrupt occurs. When the content of variable is equal to 500, it means 1 second is passed and the content of SEC and S variables would be increased by one unit. 2 milliseconds × 500 = 1 second.
To calculate the time in minutes, we can simply divide the content of S variable by 60. Every second, we must check the elapse of time and then based on the time, determine the step number and the related slope. After the determination of slope number, step number, we must consider three conditions before to decide either turn any output signal on or off.
If computed slope of the line is equal to a positive number, then key = 0 and the content of stemp variable is increased. If the computed slope is a negative number, key = 1 and stemp variable will be decreased. On the other hand, if m = 0, software would do nothing meaning it would not send out any 'on' or 'off' signal. if((sec>c1)&&(sec
3. Measuring temperature using LM35 sensor PV LM35 is a linear temperature sensor with the output voltage calibrated in Celsius. 1 ° Celsius makes an output voltage of 10mV. So when you are dealing with a room temperature at 25°C, the LM35 generates a DC voltage of 250mV = 0.25V. The sensor has only 3 pins: VCC which can be between + 4V and + 30V, GND and VOUT. So you connect VCC to +5V, GND to GND and you have the sensor powered up. Then connect VOUT to one of the analog inputs of the mega8 and you are done. No additional hardware is needed!. In the control program, VOUT of LM35 is saved in read_adc variable and it is divided by 2 because resolution of our analog signal is 5 MV. And for extra stability of our calculation, temperature is read every second from LM35 sensor.
4. Controlling operation of Hot and the cold water valves. In the control program, when temp (sensor temperature variable) > stemp (time / temperature graph variable), Cold water value, otherwise Hot water valve would be activated (turned on). In practice, when Red LED is on, Hot water valve is activated and when Green LED is turned on, the cold water valve is activated. if(temp<=(stemp-2)) { heater=1;
cool_water=0; } if(temp>=(stemp+2)) { heater=0; cool_water=1; }
5. Displaying PV, SV and process time values on 3 × 3-digit 7-segment displays. Figure 3.4 illustrates simplified schematic related to connection of seven segment displays to controller's microcontroller.
Figure 3.4 show the schematic diagram of how micro controller is connected to seven segment displays.
As you see from Figure 3.4, multiplexing technique is used to display decimal numbers such as process time, PV and SV on the displays. In the technique of multiplexing the entire display is not driven at one time. Instead, each individual display element is multiplexed, that is, driven one at a time, but the electronics and the persistence of vision combine to make the viewer believe that the entire display elements are continuously active. According to Figure 3.4, various segments of each character are connected to port B and com1, 2, and 3 of each 3-digit seven segment display are tied to different microcontroller's output ports. The following code is used to display numbers on 7segments. void show() { seg[0]=temp%10; seg[1]=(temp/10)%10; seg[2]=(temp/100)%10; seg[3]=stemp%10; seg[4]=(stemp/10)%10; seg[5]=(stemp/100)%10; seg[6]=min_time%10; seg[7]=(min_time/10)%10; seg[8]=(min_time/100)%10; } interrupt [TIM0_OVF] void timer0_ovf_isr(void) { // Place your code here count++; if(count>0) { count=0; switch(i) { case 0: PORTD.4=0; PORTB=~dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=~dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=~dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=~dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=~dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=~dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=~dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=~dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=~dsp[seg[i]]; PORTD.4=1; break; }
i++; if(i>8) i=0; } }
Using Proteus 7.8 software to simulate the control program. In this step, I used Proteus software to simulate the controller software developed in STEP2 (Figure 2.6). As mentioned already, I used 3× 7-segment indicators for the display of PV, SV and Time (in minutes). For the sake of simplicity, in Figure 3.5 some components such as transistors and buffers are not included in the schematic.
Figure 3.5: simulating circuit Since ULN2803 is an 8 channel Darlington Arrays with inverted outputs (see Figure 3.6), to simulate the software, the following coding should be added to the control software related to interrupt function Timer0:
Figure 3.6: ULN2803 Of course, when using the control program in action, all the above code must be crossed out of the main program.
Part of program when simulating it with Proteus software Before downloading the final developed program into the microcontroller's user memory, with the ULN2089 in place, the following code must be replaced with the next one. /*case 0: PORTD.4=0; PORTB=~dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=~dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=~dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=~dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=~dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=~dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=~dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=~dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=~dsp[seg[i]]; PORTD.4=1; break;*/
case 0: PORTD.4=0; PORTB=dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=dsp[seg[i]]; PORTD.4=1; break;
The above cods must be replaced with the following ones. case 0: PORTD.4=0; PORTB=~dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=~dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=~dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=~dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=~dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=~dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=~dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=~dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=~dsp[seg[i]]; PORTD.4=1; break; /*case 0: PORTD.4=0; PORTB=dsp[seg[i]]; PORTC.3=1; break; case 1: PORTC.3=0; PORTB=dsp[seg[i]]; PORTC.4=1; break; case 2: PORTC.4=0; PORTB=dsp[seg[i]]; PORTC.5=1; break; case 3: PORTC.5=0; PORTB=dsp[seg[i]]; PORTD.5=1; break; case 4: PORTD.5=0; PORTB=dsp[seg[i]]; PORTD.6=1; break; case 5: PORTD.6=0; PORTB=dsp[seg[i]]; PORTD.7=1; break; case 6: PORTD.7=0; PORTB=dsp[seg[i]]; PORTC.1=1; break; case 7: PORTC.1=0; PORTB=dsp[seg[i]]; PORTC.2=1; break; case 8: PORTC.2=0; PORTB=dsp[seg[i]]; PORTD.4=1; break;*/
Assuming that the final program is going to perform as we wanted, the next step is to compile and convert it into a HEX file before transferring it to Microcontroller's user memory. So please do the following steps: 1. Click on the microcontroller's symbol in Proteus design, the Edit Component dialog box appears. 2. Click on the program file folder, and you would be directed to the Select File Name dialog box. 3. Click on Exe folder icon, you will see all files developed at different occasions with .EXE suffixes. Select your program 4. Click Open icon. You will come back to the Edit Componenet Dialoge box. On the Edit Component dialog box, select your developed file name.
5. Click OK to Run your program. 6. Click Play icon ( ) to cause the software to simulate your hardware based on the software you already have developed and loaded into Proteus. When the controller program is placed in RUN mode, you can click on START pushbutton to execute the program. You can increase sensor temperature while process Time display is indicating the amount of time passed, to check if your software is developed correctly without any logical bug or such. See Figure 3.7.
Figure 3.7: Simulating circuit Proteus 7.0 is a Virtual System Modeling (VSM) that combines circuit simulation, animated components and microprocessor models to co-simulate the complete microcontroller based designs. This is the perfect tool for engineers to test their microcontroller designs before constructing a physical prototype in real time. This program allows users to interact with the design using on-screen indicators and/or LED and LCD displays and, if attached to the PC, switches and buttons. In Figure 3.7, notice the PV, SV and Process time indicators, display values 034, 035, and 040 respectively. Now take a look at Figure 3.2. Time Temperature table that shows at time = 40 minutes, SV must be equal to 35 ° Celsius. Figure 3.7, which is the simulation output of our program developed, checks out the result. Also notice that since SV > PV or 35 > 34, then hot water valve indicator (red LED) is turned on. This means, the output is tied to a relay, which could turn Hot water valve on to cause temperature to go up by one
° Celsius. At this stage, you can keep the simulator running to check out all the check-points in Figure 3.2. And then, when you come to the conclusion that your software is right, you can compile the control software to get xxx.HEX version programmed into a mega8 microprocessor's memory to prototype the hardware. Proteus VSM comes with extensive debugging features, including breakpoints, single stepping and variable display for a neat design prior to hardware prototyping. In summary, Proteus 7.0 is the program to use when you want to simulate the interaction between the software running on a microcontroller and any analog or digital electronic device connected to it.
Uploading the control program into the ATmega8 microcontroller (hex file). I used my little mega8 programmer (Figure 3.8) to upload the hex file developed in step 2 to ATMega8 microcontroller. At this stage, I have a Mega8 micro controller that has the control software in it and ready to be used. I could test the final project using a breadboard. In this case, I need not solder wires or anything else. You typically create an electronics project on a breadboard to make sure that everything works. If it's a project you wish to save, you can create a more permanent version. Because I wanted to create a permanent version of my circuit, I need to create a soldered or printed circuit board.
Figure 3.8 The programmer is used to program Atmega8 microcontroller
Using Altium Designer software to build the PCB of the controller. Printed circuit boards At this stage, I did some computer-aided simulations and the circuit was working great. Only one thing left! I need to create a printed circuit board for the circuit so I can see it in action! I decided that the controller board was worthy of immortality, I wanted to make it permanent by soldering components in place on a printed circuit board. Whether your circuit is a project for school/college or is a final piece of electronics in a professional product for your company, implementing your circuit on a PCB will give it a much better professional look besides giving you an idea of how the finished product will look like! I created the PCB layout of the controller circuit by converting the circuit's schematic diagram (Figure 3.9) into a PCB layout using my good old Altium Designer software to do PCB layout process. Figure 3.10 shows the PCB layout of the schematic shown in Figure 3.9.Then I asked a friend to build Controller's final PCB. Also See Figure 3.11 and 3.12.
Figure 3.9: The controller circuit
Figure 3.10: PCB layout of the controller circuit
Figure 3.11 final view of the temperature controller
Figure 3.12 illustrates controller's final look with a 8.5 × 7 Cm PLEXIGLASS sheet covered seven segment displays.
Chapter 4: PID Controller with an Arduino board
Project specification of the system Nowadays PID controllers (Proportional Integral Derivative) have an important role in industrial devices to control a wide variety of processes. We implemented the project explained in the previous chapters with PID controller instead of ON-OFF controller. In addition, we use an Arduino board instead of an ATmega8 microcontroller as the brain of system. The control objective here is for a dyeing sample machine too. The structure of its temperature system is shown in Figure4.1. The temperature control range of the system is from approximately 25° to 100° Celsius. When the dyeing machine is working, the temperature of the water in the dyeing trough must be changed according to the technical requirements. If the temperature is lower than the set value, the controller should turn the hot water valve on, and if the temperature of the water is higher, the hot water valve must be turned off (and in our case, the cold water valve must be turned on). See Figure 4.1.
Figure 4.1: The temperature system of a sample dyeing machine The adjustment of the control variable according to data obtained by reading the process variable and analyzing the error between it and the set point is referred to as the control loop. Most control loops are affected by disturbances, which influence the process and alter the process variable (PV).
What’s PID? Anytime you adjust how you do something based on previous results, you are forming your own little control loop. As an example, the PID controller (imbedded in our Heating and cooling system's electronic circuitry) looks at the set point and compares it with the PV of the temperature sensor installed in the room and determines how close it is to 75° F. If the SP and the PV are the same the controller does not have to do anything. It will set its output to zero without a need to turn on anything. However, if there is a disparity between the SP and the PV values (SP-PV > 0), the
system needs to react to this error value and therefore, some type of corrective action is needed (the system i.e. needs to turn on the cooling compressor). From Wikipedia, a proportional-integral-derivative controller is a generic control loop feedback mechanism widely used in industrial control systems. A PID controller calculates an ‘error’ value as the difference between a measured PV and a desired SP. PID loops provide technicians and engineers with a customizable way to control a variety of conditions, from temperature to speed and everything in between. The loop's control is used to modify application behavior to keep the output at stable and improved response rates. What's particularly exciting is that special software and PID modules can perform calculations to make PID design easier.
Figure 4.2: shows the classic block diagram of a process under PID Control. In continuation of this section, I am assuming you already are familiar with the concept of a closed loop systems, the theory of a classical PID, and the effects of tuning a closed loop control system. If you are not, please check appendix B, in which I have covered some basic facts about the theory of classical PID and the effects of tuning a closed loop control system. Now you might be able to come up with a circuit diagram such as Figure 3.1 in previous chapter. There is no problem to test the circuit and code at this stage, Because of using two great software- CodevisionAVR ® and Proteus ® that can help us to generate code and simulate the circuit respectively. Therefore, in the next step, we may go ahead and start generating program code for Arduino board after putting all components on the edit screen of the great Proteus software.
Generating the main Control Code for the Arduino Microcontroller The program is written by Arduino 1.0.5 software that you can find in Attendant files. Figure 4.3 shows a flowchart of the program logic and next you see the written program that we are going to explain each part.
Figure 4.3: A flowchart of written program
///Beginning of main program/// ///Initial definition/// #include /// Define PID library/// #include /// Define LCD library/// #define RelayPin 3 /// Define an output pin/// const int sensor_pin=A0; /// Define parameter and constants/// const int led=13; byte s=0,min_time=0,count=0,i=0,run=0,led_blink=0; byte key1,key2,key3,key4,key5,key6,key7; unsigned long sec=0,m1,m2,m3,m4,m5,m6,m7; unsigned int t0=25,t1=35,t2=50,t3=65,t4=80,t5=80,t6=90,t7=45; unsigned long c1=40,c2=48,c3=60,c4=80,c5=100,c6=120,c7=140; long previousMillis = 0; double kp=8,ki=120,kd=0.1; /// Define PID parameters/// double stemp, temp, Output; int WindowSize = 5000; unsigned long windowStartTime; LiquidCrystal lcd(22, 23, 24, 25, 26, 27); void finish() { lcd.clear(); /// Write a sentence on LCD/// lcd.setCursor(3, 0); lcd.print(“Processing”); lcd.setCursor(4, 1); lcd.print(“Finished”); run=0; ///Reset some parameter/// s=0; sec=0; min_time=0; digitalWrite(RelayPin,LOW); /// Turn off the heater/// digitalWrite(led,LOW); ///Turn off the LED/// } PID myPID(&temp, &Output, &stemp,kp,ki,kd, REVERSE); /// Make a typical PID function/// void setup() { Serial.begin(9600); /// Communication setting/// lcd.begin(16, 2); ///Define LCD size/// pinMode(RelayPin,OUTPUT); /// Define outputs///
pinMode(led,OUTPUT); ///Active two interrupts for start and stop buttons/// attachInterrupt(5,start_key,FALLING); attachInterrupt(4,stop_key,FALLING); c1=c1*60; /// change time from minute to second/// c2=c2*60; c3=c3*60; c4=c4*60; c5=c5*60; c6=c6*60; c7=c7*60; /// Compute the slope of each section on our curve temperature/// ////// key 1 /////// if(t1>t0) { m1=(c1-0)/(t1-t0); key1=0; } if(t1==t0) { key1=2; } if(t1t6) ↓ stemp=t0; /// write a sentence on LCD to display system is already to work/// lcd.setCursor(1,0); lcd.print(“PID Controller”); lcd.setCursor(3,1); lcd.print(“Press START”);
//windowStartTime = millis(); //myPID.SetOutputLimits(0, WindowSize); //myPID.SetMode(AUTOMATIC); } void loop() { unsigned long currentMillis = millis(); /// get elapsed time/// if((currentMillis - previousMillis > 1000)&&(run==1)) /// in each second/// { previousMillis = currentMillis; if (led_blink == LOW) /// Blinker LED with 1Hz frequency/// led_blink = HIGH; else led_blink = LOW; digitalWrite(led,led_blink); sec++; s++; if(s>59) { s=0; min_time++; } temp=analogRead(sensor_pin); /// read temperature/// //temp=temp/2; temp=temp/10; /// compute set point every second/// ///////// Step 1 /////////////////// if((sec>0)&&(sec
} if(sec==c1) stemp=t1; ///////// Step 2 /////////////////// ↓ ↓ ///////// Step 7 /////////////////// if((sec>c6)&&(secc7) { finish(); } lcd.clear(); ///display useful information on LCD every second/// lcd.setCursor(0, 0); lcd.print(“S=”); lcd.print(temp); lcd.setCursor(8, 0); lcd.print(“SP=”); lcd.print(stemp); lcd.setCursor(0, 1); lcd.print(“T=”); lcd.print(min_time); lcd.print(“:”); lcd.print(s); lcd.setCursor(8, 1);
lcd.print(“DC=”); lcd.print(100-(Output/50)); } if(run==1) { myPID.Compute(); /// compute PID output every time/// if(millis() - windowStartTime>WindowSize) { windowStartTime += WindowSize; } if(Output < millis() - windowStartTime) /// make a slow PWM signal /// digitalWrite(RelayPin,HIGH); else digitalWrite(RelayPin,LOW); } } void start_key () { lcd.clear(); ///write a sentence on LCD to display system starts the process/// lcd.setCursor(2, 0); lcd.print(“Starting…”); stemp=t0; windowStartTime = millis(); myPID.SetOutputLimits(0, WindowSize); /// Give a limitation on PID output///. myPID.SetMode(AUTOMATIC); /// Start PID controller./// run=1; } void stop_key () { if(run==1) /// If stop button is pressed, then the process will stop/// finish(); } /// End of main control program///
Now we explain each part of the above program.
Initial Definition
At first, we define the PID and LCD library in the program. You can get PID library from Attendant files. In addition, we will consider Arduino pin3 for the PID output and call it with RealyPin symbol in the program. Then we define initial parameters and constants such as PID parameter.
Finish function When the time of process exceeds 140 minutes, this function is recalled. It writes “Processing finished” on LCD and resets some parameters such as time and turns off the heater and LED.
Make PID. We defined PID library before and now we can create a PID controller linked to the specified input, output, and set point with the following instruction PID myPID(&temp, &Output, &stemp,kp,ki,kd, REVERSE);
The above inputs of the instruction are: 1. &temp: The variable we're trying to control (double) 2. &Output: The variable that will be adjusted by the PID (double) 3. &stemp: The value we want to Input to maintain (double) 4. Kp, Ki, Kd: Tuning Parameters. These affect how the PID will change the output. (double>=0) 5. Direction: Either DIRECT or REVERSE. Determines which direction the output will move when faced with a given error.
setup function The setup function is called when a sketch starts. We use it to initialize variables, pin modes, start using libraries, etc. The setup function will run only once, after each power up or reset of the Arduino board. The written program in this function includes several parts At first, it sets the data rate in bits per second for serial transmission. Then the LCD.begain instruction Initializes the interface configuration with the LCD screen, and specifies the dimensions (width and height) of the LCD. Then, the program defines RelayPin and led as Arduino output. Then, it actives two interrupts to stop and start process. We have their functions at the end of program. We change the table time unit from minutes to seconds to have more Accuracy. The important part for us is defining the set point curve. As mentioned in the previous chapter, we should generate set point curve according to our time- temperature table. In this program, our time-temperature table includes 7 sections (Figure 3.3). For each
section, we write the following code to compute the slope and store it on m1… m7 variables. And store the direction of slope (positive, negative or zero slopes) on key1… key7. if(t2>t1) { m2=(c2-c1)/(t2-t1); key2=0; } if(t2==t1) { key2=2; } if(t2
Finally, it displays some information on LCD to show it’s ready to work.
Loop function This function consists of two parts. The first one is run every second and another is run every time. In the first one, millis() is used to get elapsed time in milliseconds form. Then, the program makes a LED blink with 1Hz frequency. Also, we store the elapsed time in minutes in min_time parameter. The LM35 sensor has a 10mv on its output for each centigrade. In the program, we read the sensor's analog output with analogRead function and divide it by two, because each step in Arduino analog input is 5mv. temp=analogRead(sensor_pin); temp=temp/2;
If a thermocouple is used instead of the LM35 we should divide the analog input by 10 in program. temp=analogRead(sensor_pin); temp=temp/10;
In another part of loop function, we determine the set point and in which section on our set point curve. In each section, we use two conditions. If the slop was positive (key=0) or negative (key=1) the stemp parameter is increased or decreased respectively according time and slope (m and sec parameter). Otherwise the slop is zero (key=2) and the program does not do any work. if((sec>c1)&&(sec
if(key2==0) { if(sec%m2==0) stemp++; } if(key2==1) { if(sec%m2==0) stemp—; } }
In the last section when the time reaches C7, its means the process is finished and recall finish function to stop process. We also display the useful data such as PV, ST, etc on LCD simultaneously. In second part, the PID computations are done continually with the following instruction myPID.Compute();
If you need a fast PWM output, you can use analogWrite instruction to send PID output to a Arduino output, but we use a SSR (Solid State Relay) to control the heater. We can’t use a fast PWM. We changed the PID output Analog signal to a slow PWM (Pulse Width Modulation).
start_key and stop_key function These functions are run to handle the external interrupts on pin5, 4 that are defined in setup function. In the last three lines of start_key function, we considered a limitation on PID output and then run it and finally we change run value to 1. Therefore, our program in loop function that was written for PID controller will be run. If stop_key function is run, then the run value changes to 0, and our PID programs that were written in loop function are disabled, because we use run parameter in their starting condition.
Getting to manufacturing the PCBs of the project It was very encouraging to see that simulation was carried out successfully and now we wish to get the PCBs built and test the lift system functionality manually in the first place. This might be also related to a project that we are working on it as a collage final year project and our instructors have advised us the course grade will not be give in full unless we show them the whole hardware of the system working properly! No sweat again. Some other big brothers already have developed great software that their application allows us to design and generate the PCB layout of our circuits. Altium Designer ® which is a registered trademark of Altiume Company is a sample of that software that can be used to create PCBs of any complexity. Since all the components of this project have been designed in the previous chapters, now we just need to design a main controller board with Arduino board (Figure 4.4) instead of AVR microcontroller.
Figure 4.4: The Arduino Mega 2560 board A summary of the main Ardunio Feature are: Microcontroller
ATmega2560
Operating Voltage
5V
Input Voltage (recommended)
7-12V
Input Voltage (limits)
6-20V
Digital I/O Pins
54 (of which 15 provide PWM output)
Analog Input Pins
16
DC Current per I/O Pin
40 mA
DC Current for 3.3V Pin
50 mA
Flash Memory
256 KB of which 8 KB used by bootloader
SRAM
8 KB
EEPROM
4 KB
Clock Speed
16 MHz
In this one project, we use an ArduinoMega2560, but our circuit is simple and you can use other boards such as ArduinoPro or ArduinoNano that are simpler and less expensive. Figure 4.5 displays a schematic of our designed circuit. We do not use any monitoring device such as LCD or 7segment to have a simple schematic. Instead of them, we use a SerialMonitor.
Figure 4.5: Designed Circuit with an ArduinoMega2560 We use pin3 as arduino output through a transistor to control a relay. This relay turns the heater on or off. We use an LED to show that the state of the heater. Also we use a LM35 sensor to mesure the temperature. The middle pin of LM35 is connected to Arduino analog input and the two other ones are connected to the power sensor. Instead of LM35, you can use a PT100 termocouple. To use a PT100 you must decrease the 0-10v generated voltage by PT100 to 0-5v for Arduino input (Figure 4.6).
Figure 4.6: The used circuit to connect PT100 to arduino. To have a better interface between the operator and the Arduino that controls the process, we designed a PCB layout by Altium Designer (Figure 4.7). We put it on the Arduino board as shown in Figure 4.7.
Figure 4.7: The Interface Circuit Between Arduino and Operator
Figure 4.8: The Arduino board and Interface Circuit Maybe you want to build this circuit. In Figure 4.9, we have explained each section of
this circuit. In addition, you can use our Design by Altium designer software in attendant files
Figure 4.9: Figure 4.9 Notes:1-Female pin header (1×16). 2- 10 K ohm pot. 3-Four small push buttons. 4-2×5.6K ohm Resistors. 5-KSP 2222A NPN Transistor. 6-470 ohm Resistor. 7-330 ohm Resistor. 8-3×10K ohm Resistors. 9-Red LED. 10-4.7 K ohm Resistor. 112×3 Input Pins. 12- 470 ohm Resistor. 13- Green LED.
Uploading the control program into the Arduino board One great thing I like about Arduino board is that you do not need to have a programmer to upload your developed code. If this is the first time you are using an Arduino board for building your project, there are tons of information on the internet to teach you how to do it, or you might try the following link for example: http://www.ladyada.net/learn/arduino/lesson1.html
Questions and Answers related to these projects: This section of this manual is reserved for you. I would be very glad if you please write to me any question (hardware or software wise) you have related to this well designed industrial project. I shall answer your questions ASP and also, will include your question in this section of the manual believing that it might be also somebody else's question as well. Thanks a lot for your comments & concerns!
Conclusion Now you have the information you need to become a successful PLC programmer. This is a moment for you to take the information you’ve been given and not be afraid to put it to use. The primary thing that keeps people from becoming successful is fear. If you can overcome this fear then you will succeed and prosper. All you need to do at this point is to stop putting things off and just do it. Start working and you will find it becomes easier as you go along. Once you accomplish any new skill or task, you will realize just how easy it is. That is when you want to kick yourself for not starting sooner. So don’t hesitate. Start right now. Start today. Break that cycle of doubt and enjoy your newfound skills and succeed in exploiting them. To your success and happiness, Seyedreza
Good informative links Data Acquisition System usingATmega8 http://chaokhun.kmitl.ac.th/~kswichit%C2%A0/PLogger/index.html Shows the application and test of LM35 sensor http://www.ladyada.net/learn/sensors/temp36.html Downloadable PDF document about specification of LM35 sensor www.ti.com/lit/ds/symlink/lm35.pdf
Appendix A Slope of a straight line Equation of a straight line is y = mx + b To find the slope (m), you use the following formula:
In Figure 1, pick two x and y on the line and calculate the slope m1 and write the line equation: M1= 0.25 hence the equation of the line related to m1 is y = 0.25 x + 25. After 30 minutes, the temperature is: y (30) = 0.25 (30) + 25 = 7.5 + 25 = 32.5 ° Celsius
Figure 1
Appendix B PID (Proportional Integral Circuit) Figure 1 shows that the PID controller receives a set point request from the programmer and compares it to a measured feedback (E = SP-PV). In Figure 1, SP can be interpreted as where I want to be and feedback (PV) can be thought of as where I really am. The PID controller looks at the current value of an error E, the integral of the error over a time interval ∫ε and the rate of change of the error Δε to determine how much of a correction to apply. The controller continues to apply the correction until change is seen on the feedback. The corrective action can be adjusted at a fast rate (for instance, the analog feedback on some variable frequency drives is updated every 10 milliseconds). A good PID Tuning technique will calculate exactly how the three Tuning Parameters (or ‘Tunings’): Kp, Ki & Kd is going to be applied. Adjusting these values will change the way the output is adjusted. Fast or slow or something in the middle. The job of a PID controller is to eliminate the error (eventually getting to the point where the error = 0 in the whole duration time of the process) – so where I am going be is ideally changed to where I want to be. How does a PID loop work? PID is an acronym for the mathematical terms Proportional, Integral, and Derivative. Proportional means a constant multiple. A number is said to be a proportion to another if there exists a constant n such that y = nx. This n can be positive or negative, greater or less than one. To make the formula more accurate by PID controller standards, proportion is given by KP and the x term is the control loop error ε or y = KP(ε). The term Integral means the summation of a function over a given interval. In the case of controller PID that is the sum of error over time: y = ∫f (ε) dt. Finally, Derivative is the rate of change during a given interval. Interpreted by a PID controller: All three of these PID controller components create output based on measured error of the process being regulated. If a control loop functions properly, any changes in error caused by setpoint changes or process disturbances are quickly eliminated by the combination of the three factors P, I, and D and then imposing it to output port actuator.
Figure 1 shows a simplified block diagram of the PID process control loop The proportional, integral, and derivative terms are summed to calculate the output of the PID controller. Defining CV(t) as the controller output, the final form of the PID algorithm is shown in Figure 2
Figure 2 Tuning Parameters The black magic of PID comes in when the three Tuning Parameters (Kp, Ki & Kd) are adjusted well enough (or right tuning values) to drive the Input towards the Setpoint.
So what are the ‘right’ tuning values to use? There isn't one right answer. The values that work for one application may not work for another, just as the driving style that works for a truck may not work for a race car. With each new application you will need to try Several Tuning values until you find a set that gives you what you want. Proportional Response The proportional gain (Kp) determines the ratio of output response to the error signal. For instance, if the error term has a magnitude of 10, a proportional gain of 5 would produce a proportional response = E × Kp = 10 × 5 = 50. In general, increasing the proportional gain will increase the speed of the control system response. However, if the proportional gain is too large, the PV will begin to oscillate. If Kp is increased further, the oscillations will become larger and the system will become unstable and may even oscillate out of control. It appears that if we use a simple analog multiplier circuit to replace it with its mathematical model shown in Figure 2, it will do the job of multiplying the two error term and the proportional gain signals easily to product the related output signal. An analog multiplier is an important circuit building block in the field of analog signal processing. Its application can be found in communication, measurement and instrumentation systems (our case). Figure 3 shows a very simplified and naive version of an analog signal multiplier could be made with op amps.
Figure 3 Integral Response In the close loop equation shown in Figure 2, the integral component sums the error term over time. The result is that even a small error term will cause the integral component to increase slowly. Actually, this ingredient as matter of fact is the sum of all the instantaneous values that the signal has been, from the time you started counting until you stop counting. The integral response will continually increase over time unless the error is zero, so the effect is to drive the Steady-State error (the final difference between PV and SP) to zero. From our high school math, we might remember that we can use 3 methods of numerical integration – the rectangular rule, trapezoidal rule, and Simpson's rule. These methods are used to approximate a definite integral.
Figure 4 shows a very simplified and naive version of an analog signal integrator circuit which could be made with op amps. The input voltage passes a current Vi/R1 through the resistor and series capacitor, which charges or discharges the capacitor over time. Because the resistor and capacitor are connected to a virtual ground, the input current does not vary with capacitor charge and a linear integration operation is achieved.
Figure 4 Rectangular Rule The rectangular rule for a numerical integration is a relatively crude method for approximating the definite integral. This method approximates f(x) with a piecewise constant function (see Figure 5). The area under the curve y = f(x) is approximated by summing the area of n equally spaced rectangles, called subintervals. The width of each subinterval is abbreviated h, where: h = (xH-xL)/n The height of each rectangle is given by f(xi), where xi = xL + (i + 1/2)h. Given the width and height of each rectangle, the total area under the curve is approximated by summing the area of each rectangle,
This approximation can be significantly improved by approximating f(x) with piecewise linear or quadratic function.
Figure 5 Trapezoidal Rule This method is similar to the rectangular rule mentioned earlier with one important exception that the function f(x) is approximated by a piecewise linear function, instead of a piecewise constant function. Figure 6 shows the geometric interpretation of the trapezoidal rule.
Figure 6 As shown in Figure 6, the area A (see Figure 7), where A is divided into n equally spaced subintervals of width h, where h = (xL-xH)/2 and xi = a + hi. By recognizing that each subinterval consists of a rectangle and a right triangle, Ai=1/2 h [f(xi-1) + f(xi)] where Ai is the area of the ith subinterval. The sum of he area of these n subintervals, A, is
The equation shown in Figure 7 is called the trapezoidal rule.
Figure 7 We next take up the application of integrals to an electrical problem. Later in the continuation of this, we shall see how differentiation would help us to analyze the operation of certain electrical and magnetic systems. Here, we learn similar application of integrals. Example 1: Finding energy from power. We know that the power in a system equals the rate at which energy (work) is expended:
Example 2 The power in a certain electrical system changed according to p = t2 Watts. Calculate the energy in this circuit used from t =0 to t = 5 by applying the energy equation derived in example 1. To illustrate the trapezoidal rule, the area under the curve will be approximated by dividing it into five subintervals. Next table shows the results of these calculations.
The sum of the areas of the subintervals is 42.5. By performing the integration it is found that:
Conclusion: In the close loop equation shown in Figure 2, the integral component sums the error term over time. The result is: even a small error term will cause the integral component to increase slowly. Therefore, this ingredient actually is the sum of all the instantaneous values that the signal has been, from the time you started counting until you stop counting. The integral response will continually increase over time unless the error is zero, so the effect is to drive the Steady-State error (the final difference between PV and SP) to zero. Derivative Response The derivative component causes the output to decrease if the process variable is increasing rapidly. The derivative response is proportional to the rate of change of the process variable. Increasing the derivative time (Td) parameter will cause the control system to react more strongly to changes in the error term and will increase the speed of the overall control system response. Figure 8 below shows an ideal op-amp integrator with input-output relationships that is theoretically correct.
Figure 8 In high school math, we were told: the exact rate of change of a function y with respect to an independent variable x is the limit that the average rate of change approaches, as approaches zero, while always including the single value of x in question. We will call this exact rate the derivative of y with respect to x (symbol, dy/dx).
There are two ways of introducing the derivative concept, the slope of a curve or a rate of change. The slope of a curve translates to the rate of change when looking at real life
applications (take a look at example 3). Either way, both the slope and the instantaneous rate of change are equivalent, and the function to find both of these at any point is called the derivative. The Geometrical concept of the Derivative A way to find the slope is using the rise over run method, or the equation of a straight line is y = mx + b. To find the slope (m), use the following formula:
Figure 9 The way to get a better approximated slope is to make the two x values as possible. This is a tedious process when we want to find the slope for many points on a graph. So how can we find the slope at a point? This is where differentiation comes in. The definition of a derivative comes from taking the limit of the slope formula as the two points on a function get closer and closer together. The physical way or rate of change concept of the Derivative On the other hand, in Figure 10, we would like to calculate the rate of change or slope of at the point shown.
Figure 10
Instantaneous induced voltage We do know that if we insert a winding into a magnetic field (or if we withdraw the winding from the field) we change the number of magnetic lines of force through the winding. The law of Henry and Faraday tells us that the result is an average induced winding voltage Vav. In the formula shown in Figure 11, N is the number of turns and is the flux (in webers) that actually passes through the winding. The induced voltage V (ind) appears in the winding.
Figure 11 The induced voltage at any instant equals the product of the number of turns N times the rate of charge d /dt of the flux that links the winding.
Figure 12 We can express this result in an equation:
Figure 13 The negative sign in equation in Figure 13 accords with Lenz's law, indicating that if a current results from the induced voltage, such a current opposes the flux change. Example 3 During certain time interval, the magnetic flux through a 100-turn winding varied according to the formula = 10t3 + 5 webers. We need to find the induced voltage in the winding when t= 0.1 second. By differentiating = 10t3 + 5, we get d /dt = 30 t2 webers/seconds and by substituting it in the formula shown in Figure 11, we will have:
V (ind) = -N (d /dt) = (-100) [(30) (0.1)2] = -30 volts (at t=0.1)
My e-book product list www.plc-doc.com Hardware, software and more We would like to introduce our Teach Yourself Consumer PLC books as an excellent resource for readers who want to learn more about PLCs. So far, we have launched this groundbreaking new series with five exciting titles: 1. Programming with SIMATIC S7 300/400 Programming Controllers 2. Programming with SIMATIC S7-200 PLCs using STEP 7-Micro/win software 3. Introduction to programming a SIEMENS LOGO! PLC 4. Basics of Programmable Logic Controllers (PLC) 5. Programming Allen Bradley series of PLCs using RSLogix 500 software compiler 6. Introduction to programming Allen-Bradley series of PLCs (Second Edition) Design and Implementation of typical end year college projects using a PLC with youtube.com site links to watch the projects in action: 1. Programming a 4 floor elevator with SIMATIC STEP 7 and LOGO! SoftComfort http://youtu.be/dqkeHD5WNcc 2. Programming SIEMENS LOGO! PLC as a dyeing machine temperature controller http://youtu.be/mJfT4z1oCeo 3. Programming a Traffic Light Controller system using SIMATIC S7-300 & HMI display http://youtu.be/0ADfFPOzIUE 4. Programming a PLC based car Parking System with SIMATIC S7-300 PLC http://youtu.be/51oqLRxXcHk 5. Implementing a PLC-based temperature controller with PID algorithm http://youtu.be/yhSyKObMlgA 6. Design and implementation of an 8 Floor Elevator Control System with a PLC http://youtu.be/M3qgxkEIDw8 Design and Implementation of typical end year college projects using AVR Microcontroller\the Arduino board based controllers with youtube.com site links to watch the projects in action: 1. Simple Arduino based 4 Floor Elevator Project http://youtu.be/WU2arv-yghw 1(A) - Microcontroller based 4 Floor Elevator System http://youtu.be/UQbGcntcVP4 2. Implementing a Traffic Light Controller System using Arduino http://youtu.be/f-ZbP8juB20 2(A). Programming a TRAFFIC LIGHT CONTROL system using an AVR
microcontroller http://youtu.be/q0eWsX2kMeU 3. Simple Arduino based Automated Parking lot System http://youtu.be/CNt2DIlwrso 3(A). Design and implementation of a Microcontroller-Based Car Parking System http://youtu.be/7aIp2iCC_mU 4. Implementing an Arduino based temperature controller with PID algorithm http://youtu.be/i2nxqLs9wBg 4(A). Temperature controller and monitoring with a microcontroller http://youtu.be/mIyixludYaE 5. Analog LED clock with chime, alarm, calendar and temperature display (not published yet) http://youtu.be/Mi5zAdctp4g Free microcontroller \Arduino based project Downloads from our www.plc-doc.com or www.plcgoods.net websites: 1. How to control a Stepper motor with an ATmega8 microcontroller http://youtu.be/XBWCsl512Lc 2. MATLAB/PC and Microcontroller based advanced Line following Robot http://youtu.be/2Y_qSzKL_2Y 3. 2 Zones microcontroller based weekly digital timer http://youtu.be/xbIEKI3qqNM