23
Indian Institute of Technology Bombay I Semester control lab project Report on Inverted Pendulum Controller Design Authors: Adeesh Kale (133079008) Barath Sastha (133070022) Krishnamohan M (133070020) Sandeep Kumar (133074016) Vaibhav Somani (133074001) Advisor: Prof. Debraj Chakraborty

Report on Inverted Pendulum

Embed Size (px)

DESCRIPTION

Sem 1

Citation preview

  • Indian Institute of Technology Bombay

    I Semester control lab project

    Report on InvertedPendulum Controller

    Design

    Authors:Adeesh Kale (133079008)Barath Sastha (133070022)Krishnamohan M (133070020)Sandeep Kumar (133074016)Vaibhav Somani (133074001)

    Advisor:Prof. Debraj Chakraborty

  • Abstract

    Inverted Pendulum is a device with an arm fixed at a fulcrumpoint that has a single axis of freedom. The objective is to applyforce or torque to this pivot point so that the arm balances on itsjoint. The controlled point may be actuated in either linear or rotaryorientation. This experiment considers the rotary inverted pendulumproblem where a DC motor with rotation axis perpendicular to theaxis of the fulcrum is connected to the base.

    The inverted state of the pendulum is an unstable equilibrium.Small errors or noise can destabilize it. Feedback control is requiredto continuously compensate for the noise. This experiment uses an op-tical encoder to provide the feedback. We use Simulink and MATLABenvironment to model the control system, which uses this feedback andmodels a PID controller that outputs to the DAQ card. The motorat base is thus controlled bidirectionally using PWM signals outputby the DAQ card. A separate motor driver circuit is used to generateboth power and electrical isolation to protect the DAQ card.

    1

  • Contents

    1 Introduction 4

    2 Angle and angular speed measurement 72.1 Obtaining and interpreting data from relative encoder . . . . . 72.2 Using DAQ card to calculate angle . . . . . . . . . . . . . . . 82.3 Using Arduino to calculate angle . . . . . . . . . . . . . . . . 102.4 Calculating angular speed from angle . . . . . . . . . . . . . . 13

    3 Executing with simple PD controller 14

    4 Motor driver circuits 144.1 L293D IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2 L298N IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    5 Results, complications and future endeavors 195.1 Limitations of MATLAB as realtime operating system . . . . . 195.2 ARDUINO Serial port output . . . . . . . . . . . . . . . . . . 215.3 Motor driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    6 Suggestions 22

    2

  • List of Figures

    1 Basic overview of the system . . . . . . . . . . . . . . . . . . . 52 Pendulum physical dimensions . . . . . . . . . . . . . . . . . . 63 Motor details . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Relative encoder diagram . . . . . . . . . . . . . . . . . . . . . 75 Encoder track pattern and corresponding signal . . . . . . . . 86 Basic logic for detecting angular change at 4x in Simulink . . . 97 Main Angle counter and Angular Speed decoder blocks in

    Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Angle and Angular Velocity using Arduino and serial commu-

    nication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 PID controller Simulink diagram . . . . . . . . . . . . . . . . . 1410 L293D Pin layout . . . . . . . . . . . . . . . . . . . . . . . . . 1511 L293D maximum ratings . . . . . . . . . . . . . . . . . . . . . 1512 L293D application diagram for bi-directional motor control . . 1613 Circuit diagram to illustrate using channel 1 to drive motor . . 1714 L298N DC motor driver layout . . . . . . . . . . . . . . . . . 1715 L298N DC motor driver maximum ratings . . . . . . . . . . . 1816 L298N DC motor driver application diagram . . . . . . . . . . 1817 L298N DC motor driver application note . . . . . . . . . . . . 1818 Encoder Angle conversion process by DAQ card . . . . . . . . 2019 PD controller output . . . . . . . . . . . . . . . . . . . . . . . 2020 PWM output . . . . . . . . . . . . . . . . . . . . . . . . . . . 2121 Missed ticks behavior in MATLAB . . . . . . . . . . . . . . . 21

    List of Tables

    1 Logic for reading change in angle at various speeds . . . . . . 92 L293D application note . . . . . . . . . . . . . . . . . . . . . . 153 Absolute maximum ratings for L298N . . . . . . . . . . . . . . 16

    3

  • 1 Introduction

    An inverted pendulum is a classic example of a nonlinear mechanical systemcontaining a pendulum with its center of mass above its pivot point.

    The objective of the experiment is to balance a pendulum vertically upwith motor driven arm using PID control.

    Setup Description:

    PC running MATLAB

    Plant: The system consists of a 24-Volt DC motor that is coupledwith an encoder and is mounted vertically in the metal chamber. Itconsists of two links: arm and pendulum link. The pendulum link isallowed to freely rotate in vertical configuration. The arm link rotatesin horizontal configuration and is connected to the pendulum link atone end and to the motor shaft at the other.

    Optical encoder: There are two optical encoders, one to measure theangular position of the pendulum link and another for the arm link.These encoders converts angular displacement into digital pulses whichare fed into MATLAB blocks, where it is converted as degrees. Theangular position and its corresponding derivatives are used as feedbacksfor PID control.

    The system is later enhanced by using arduino (ATmega2560) to measure an-gles from encoder for high sampling rate to avoid missed ticks. The measuredangles are then fed into MATLAB from Arduino connected to PC throughan USB port.

    Motor driver circuit: The motor driver used is L293D of Texas Instru-ments through which controlled (PWM) voltage is given to motor input ter-minals. The same driver is used to give direction control to the motor.

    DAQ: The DAQ card used is PCI-MIO-16E-1 model of National Instru-ments which is used to connect optical encoders and motor drivers to thePC.

    4

  • Figure 1: Basic overview of the system

    More details on every component will be given in respective topics of thisreport.

    The work has been carried out in following steps:

    1. Study and analyze the physical inverted pendulum model, DAC cards,optical encoders and motor driver circuits used

    2. Setup connections between optical encoders, motor driver (L293D),DAC card to the computer running MATLAB

    3. Design the PID controller for balance up controller

    4. Code in Arduino (ATmega2560) to measure the pendulum angle athigh sampling rate

    How is inverted pendulum balanced?The inverted pendulum (IP) is balanced by implementing a feedback from

    pendulum angle and its derivative (the other states being arm angle and itsderivative). Please note that the experiment has been setup only for balanceup position and not for swing up control.

    The pendulum has two stationary points, one at 0 degree (stable) andanother at 180 degree (unstable). The inverted pendulum can be kept atvertical position by applying oscillating force as motor torque. 24V DCmotor has been used. Physical dimensions of the inverted pendulum are asfollows:

    5

  • Figure 2: Pendulum physical dimensions

    Figure 3: Motor details

    6

  • 2 Angle and angular speed measurement

    Optical encoder is an electro-mechanical device, primarily a sensor that en-codes angle into an analog or digital electrical signal. There are generallytwo classes of optical encoders: Relative encoders, that only give the changein angle, and absolute encoders which give the absolute value of the anglewith reference to a designated zero. This experiment uses two relative opticalencoders, one to give positional change of the motor axis and the other forthe arm axis, perpendicular to that of the motor axis.

    2.1 Obtaining and interpreting data from relative en-coder

    The relative encoder consists of two perforated disks set in quadrature withrespect to each other. This is illustrated in figure 4.

    Figure 4: Relative encoder diagram

    Each disk has 1024 perforations in the cycle. The data is mapped ontotwo channels: A and B, with track patterns as shown in figure 5, which leadto two square pulses that are a quadrature apart.

    7

  • Figure 5: Encoder track pattern and corresponding signal

    From this information, position value of angle may be inferred by arbi-trarily defining:

    The initial state as reference value 0 degrees

    Clockwise rotation as negative count

    2.2 Using DAQ card to calculate angle

    The first option is to use the DAQ card to input the data from channels Aand B as discussed in previous section, at the digital I/O port. Since thechannels are sending a square pulse, digital port is sufficient to read them.The simulink setup to read angle for logic given above, at each rate are shownin figures 6 and 7.

    8

  • Speed Clockwise Anticlockwise1x B A = 1 A B = 12x B A = 1; B A = 0 A B = 1; A B = 04x A B = 0; A B = 1;

    B A = 1; B A = 0A B = 1; A B = 0;B A = 0; B A = 1

    Table 1: Logic for reading change in angle at various speeds

    Figure 6: Basic logic for detecting angular change at 4x in Simulink

    9

  • Figure 7: Main Angle counter and Angular Speed decoder blocks in Simulink

    The sampling rate guarantee of real time windows target in normal modeis claimed by Mathworks to be nearly 500. In practice, it is found that thecurrent setup gives generally a much worse performance. This is elaboratedupon in the last section. Due to the inaccuracy resulting from missed ticks,we move to the second option, using arduino to decode and count angle.

    Application Note

    1. Mathworks claims that executing the real time simulink design in ex-ternal mode guarantees a much better (20khz) rate, the next logicalstep is to use it and verify the existence and frequency of missed ticks,or lack thereof.

    2.3 Using Arduino to calculate angle

    As noted before, a real time system is essential to provide a feedback tomake this system solvable. This drawback of the previous setup may becircumvented by having a man-in-the-middle as it were that provides a nearlyreal-time performance for the same.

    10

  • For this function, dedicated ICs like HCTL-2021 quadrature decoder/-counter IC are available in market. Due to constraints, the arduino de-velopment board is used here without noticeable loss of performance. Thechannels A and B are supplied to interrupt enabled pins of the arduino board,because we need edge detection for the signals as is explained in the logicabove. However, to avoid any issues with conflict of interrupt service routine(ISR), the arduino board is used to handle only one optical encoder.

    Transmitting data from arduino board to MATLAB For this purpose,multiple options are available:

    Serial port that is already interfaced to the onboard serial to USBconverter

    Analog output through PWM pin, using analogWrite() command

    Breaking down the data as individual bits and transmitting via digitalpins using digitalWrite() command

    Clearly, considering clocking considerations and overhead, the digitalport write appears to be the best option. However, the DAQ card availablehas 8 digital I/O pins, 3 of which are interfaced to control the motor drivercircuit (this can however be circumvented by using the analog channel in-stead, which can be used as a quasi digital input port). In addition, it takessome clever register manipulation and multiplexing to:

    1. Distribute each 10 bit resolution signed count over two cycles of 8 bitdigital writes

    2. add signatures to each frame to denote start frame, stop frame andsigned/unsigned state

    Although the overhead for this is not comparable to that for serial com-munication and it still takes place at a quicker pace than PWM output, thearduino platform is unsuitable for such programming tactics. It will requireinstead to build a basic application board with a raw microcontroller, pro-grammed using either ASM or C for best effect considering the complexityin our code is not high.

    On the other hand, PWM is impractical for this purpose because thismode requires the Timer0 to be enabled, which relies on its own interruptcalling where it halts other ISRs to service its own. This is clearly unaccept-able for our situation where we require real time handling of optical encoderinterrupts. A framework that is capable of handling parallel interrupt calls isrequired. In addition, PWM resolution is 8bits, whereas our tick resolution

    11

  • at 4x is 16 bits deep being a signed integer data type. This can be circum-vented by using PWM to denote only a small variation from the mean. Thissolution is good enough for this application because the controller designis just for balancing the pendulum, which becomes irreversibly unstable forlarger deviations of angles anyways.

    Serial port transmit has two major issues:

    1. The output data is always as strings of characters where each blockvaries in length according to data to be transmitted. This requiressome clock formatting on both ends to transmit and receive properly.

    2. There is an inherent latency in serial data transmit due to the factthat the serial communication header file for arduino contains a delaycommand for 25ms. If this is tampered with, it may lead to somewhatunpredictable serial communication behavior.

    This builds a stronger case to move away from arduino and onto a raw mi-crocontroller platform or dedicated quadrature decoder counter IC. However,a working version of serial transmit, with very low error but high latency ispresented in its Simulink model form.

    Figure 8: Angle and Angular Velocity using Arduino and serial communica-tion

    12

  • Application Notes

    1. We can observe that error in angle computation still creeps in even witharduino. With a little engineering, we see that changing the overflowconditions to optimize and then adding a delay in the range of 25microseconds reduces the error to least possible value. Our hypothesisis that this is the point where there is the least probability of falsepositives while the sampling being fast enough to avoid false negatives.

    2.4 Calculating angular speed from angle

    Once we have the angle input into the system, the angular speed needs to becalculated according to the following algorithm for maximum accuracy andperformance

    input : Angle output: Angular speed

    beginTimer t : {t = 1ms

    endwhile 1 do

    if > 0 then = /t

    endif t = 1s AND = 0 then

    = 0;endReset t;

    end

    Algorithm 1: Discrete domain angular speed calculator

    In practice, due to the various limitations cited earlier, the simple algo-rithm shown below also works within tractable error bound.

    Application Notes

    1. To compensate for performance loss due to missed ticks, we can assumethat the simple algorithm for angular velocity can also be implementedexternally on the arduino board. However, this is impossible becauseof the same reason as PWM is not practical, in that due to the Timerclass being initiated, ISR for optical encoders are interrupted.

    13

  • input : Angle output: Angular speed

    beginTimer t : {t = 1ms

    endwhile 1 do

    if t = 1ms then = /t

    end

    end

    Algorithm 2: Simple angular velocity algorithm

    3 Executing with simple PD controller

    The PID controller used is illustrated in figure 9. We havent included Inte-grator because it is not applicable for experiment.

    Figure 9: PID controller Simulink diagram

    4 Motor driver circuits

    4.1 L293D IC

    The L293D is a quadruple high current half-H driver IC .It is designed toprovide bidirectional drive currents up to 600 mA at voltages from 4.5 voltsto 36 volts. It is a 16 Pin IC consisting of 2 driver channels on either sideof the chip.channel 1 has inputs at Pin 2 and Pin 7 respectively and outputsat Pin 3 and Pin 6 respectively.Channel 2 has inputs at Pin 10 and Pin 15respectively and outputs at Pin 11 and Pin 14 respectively.

    14

  • Figure 10: L293D Pin layout

    The absolute maximum ratings of various parameters are given in figure11

    Figure 11: L293D maximum ratings

    The following table presents the motor driving function of channel 1 de-pending on inputs given at 1A and 2A(Pins 2 and 7) .The outputs of thedrivers 1A and 2A (Pin 3 and 6 respectively) are to be connected to theinput channels of the motor(motor channel A and B).EN denotes the enablepin(Pin 1 for drivers with inputs 1A and 2A) .The drivers remain disabledas long as this pin is grounded.

    EN 1A 2A Functionhigh low high Turn righthigh high low Turn lefthigh low low Fast Motor Stophigh high high Fast Motor StopLow high/low high/low Fast Motor Stop

    Table 2: L293D application note

    15

  • Thus the motor can be made to rotate in either direction by applyingappropriate inputs 1A and 1B .In order to vary the output torque and thusthe speed of rotation a Pulse width modulated(PWM) wave can be appliedat the enable pin ,EN. Now the output torque depends on the duty cycle ofthe PWM wave.

    Figure 12: L293D application diagram for bi-directional motor control

    Parameter ValueSupply voltage,VS 36VLogic supply voltage,VSS 36VInput voltage,V1 7VOutput voltage range V0 -3V to VCC2 + 3VPeak output current,I0 1.2AContinuous output current,Ic 600mA

    Table 3: Absolute maximum ratings for L298N

    16

  • Figure 13: Circuit diagram to illustrate using channel 1 to drive motor

    4.2 L298N IC

    The L298N is a high voltage,high current dual full bridge driver.Like in theL293D,it has 2 channels and 2 enable inputs are provided to enable or disablethe device independently of the input signals.Channel 1 input is between pins5 and 7 and output is to be taken across Pins 2 and 3.Channel 2 inputs areto be given between Pins 10 and 12 and outputs are obtained across Pins 13and 14.Pin 6 serves as the enable Pin for channel 1 and Pin 11 is the enablePin for channel 2. The IC can output a maximum of 2A per channel.As inthe case of L293D the outputs of both channels can be Paralleled for highercurrent.

    Figure 14: L298N DC motor driver layout

    17

  • Figure 15: L298N DC motor driver maximum ratings

    The followings diagram shows half part of the IC being used to drive astepper motor and the table for rotation of the motor.

    Figure 16: L298N DC motor driver application diagram

    Figure 17: L298N DC motor driver application note

    18

  • 5 Results, complications and future endeav-

    ors

    5.1 Limitations of MATLAB as realtime operating sys-tem

    We used MATLAB-Simulink model to decode the encoder output to get theangle of the pendulum and the motor arm. We noted that the angle recordedwas quite accurate during initial program runs but errors crept into it asthe time progressed. We also noted that the error was very high when thependulum was moved at high angular speeds. After few runs we understoodthat the mean value (or reference value) of the angle was shifting.

    Then to analyse the problem we conducted lot of experiments by givingsquarewave from a function generator and reading it in MATLAB. Afteranalysis we found that the MATLAB was not recording the input signalcorrectly. It was missing many of the samples of the input signal. We foundout that there was a relation between the Missticksreported by DigitalInput block. Whenever there was a misstick the program missed to recorda sample. The number of samples missed are proportional to the number ofmissticks.

    It was obsevered that the number of missticks reduced as we reduced thesampling frequency but they were always present. At sampling frequency aslow as 500 Hz also there were missticks.

    We therefore concluded that MATLAB as an realtime operating systemdoes not give a guarantee of even 500 Hz. As the encoder input signalfrequency is upward of 1 Khz, a minimum sampling rate of 10Khz is requiredgetting recording signal in high fidelity, hence MATLAB is unsuitable for thepuporse of decoding the encoders.

    19

  • Figure 18: Encoder Angle conversion process by DAQ card

    Figure 19: PD controller output

    20

  • Figure 20: PWM output

    Figure 21: Missed ticks behavior in MATLAB

    5.2 ARDUINO Serial port output

    To solve the problem of decoding angle, we wrote a code in Arduino usingMega 2560 kit. The angle now measured was quite accurate and very lowerror was there even when pendulam was moved at high angular velocity. Wetransmitted the data to MATLAB through serial port, but we found thatthere was some lag in the data. On analysing we was found that the serialport eventhough when used at high baud rates of 38400 was not sufficientto work on the problem. Another option was to send analog data through

    21

  • analog card, but the bit resolution of Mega 2560 is 8 bits (256 counts) is toolow for angle as we wont be able to get even one degree resolution.

    Also one Arduino can be used for only one encoder as the program isbased on interrupt.

    5.3 Motor driver

    We analysed that the power supply required for the motor is more than 2 A.We designed motor driver with two numbers of IC L293D in parallel. Thisgave a total of 1.2A output current but this was not sufficient. To go forhigher current rating we tried to make a motor driver with IC L298N whichis capable of giving 2A current. But, we somehow couldnt make it work.

    6 Suggestions

    Hardware based decoder for optical incremental encoders As decod-ing the encoder output is the most important par of the experiment,no error can be tolerated in it. We analysed that the best way is togo for hardware based decoders such as HCTL-2032 or LFLS7082-S.These IC based decoders can give output for two numbers of incremen-tal encoders as required in our case. We tried to procure them but thedelivery time in India was 21 days.

    Better Motor driver As the error increases the motor driver is not able togive sufficient current to the motor and hence torque developed is notsuffiecient to reduce the error. Suitable motor driver may be fabricatedwith current capacity of 3 A.

    Incremental Encoder with reference signal Most of the incremental en-coders have a reference signal for correction of the errors in anglecalculation. We suggest that if a new experiment setup is being de-signed/procured then if they should have incremental encoders withreference signal. This will enable the experiment to be completed byMATLAB alone.

    22