MAE576 GroupD LAB3 Report

download MAE576 GroupD LAB3 Report

of 55

Transcript of MAE576 GroupD LAB3 Report

  • 8/9/2019 MAE576 GroupD LAB3 Report

    1/55

    LAB 3:

    SPEED CONTROL OF A DC MOTORMechatronics 576

    Spring 2010April 13th, 2010

    Group D

    Priyanshu AgarwalDipen Harishbhai Dave

    Ravikiran ChollangiJason Lieu

    Department of Mechanical and Aerospace Engineering

    State University of New York at Buffalo

    Buffalo, New York 14260

  • 8/9/2019 MAE576 GroupD LAB3 Report

    2/55

    Abstract

    The goal of this assignment was to develop a Speed control system for a DC motor. Various control

    methods were to be employed, both open loop and closed loop. All control methodologies are

    implemented using MATLAB GUI. The important feature of the system is the auto-calibrate function

    which provides the capability to calibrate the system at three different levels depending on the desired

    level of accuracy and recommend whether to use the calibration or not based on the statistics of fit. In

    closed loop control, on-off, differential, proportional, proportional-plus-differential and proportional-

    plus-integral-plus-differential are implemented. The system also has a feature to run a diagnostics in

    order to assess its state of health. A monitoring feature which employs a webcam to monitor the fan by

    the user is also present. This can be of importance in remote operation of the motor. In addition, the

    system also provides the feature of data logging both for calibration and for controls.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    3/55

    Contents

    Abstract

    Contents

    1.Introduction1.1 Design Objective1.2 Features of DC Motor Control System1.3 System Architecture1.4 User Operation Instructions

    2. Hardware

    2.1 List of Components2.2a Microcontroller (Master BASIC Stamp 2) Pin Assignment

    2.2b Microcontroller (Slave BASIC Stamp 2) Pin Assignment2.3 Hardware Description2.4 Circuit Diagrams2.5 Mechanical Setup

    3. Software

    3.1 PBASIC Commands3.2 Programming Challenges

    4. Mathematical Methods

    4.1 OnOff Control4.2 Differential Gap Control4.3 Proportional Control4.4 PD Control4.5 PID Control4.6 PWM control

    5. Implementation

    5.1 Software Algorithms5.1.1 Controls Flowchart5.1.2 Auto Calibration Flowchart5.1.3 Master BS2 Flowchart5.1.4 Slave BS2 Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    4/55

    5.1.5 OpenLoop Control Flowchart5.1.6 OnOff Control Flowchart5.1.7 Differential Gap Control Flowchart5.1.8 PID Control Flowchart

    5.2 Subroutines

    6. Calibration & Testing

    6.1 Digital Sensor Calibration6.2 Duty Cycle Vs Optical Encoder Count Calibration6.3 Testing6.3.1 Diagnostics6.3.2 OpenLoop Control6.3.3 OnOff Control6.3.4 Differential Gap Control6.3.5 Proportional Control6.3.6 PD Control6.3.7 PID Control

    7. Discussion

    8. Conclusion

    Bibliography

    Appendix

    A. PBASIC Code for Speed Control SystemA.1 Slave Microcontroller Code

    A.2 Master Microcontroller Code

    B. MATLAB GUI Code for Speed Control System

  • 8/9/2019 MAE576 GroupD LAB3 Report

    5/55

    1. IntroductionA DC motor is used in a variety of applications, and precise control of speed is important. Here we usean opto-reflective sensor to measure the speed and give feedback for closed loop control. Multiplecontrol methods, viz. on-off, Differential, Proportional, PD and PID are implemented in the form of aMATLAB GUI. MATLAB is used for back end calculations, which communicates with the NX-1000board acting as the master and another Board of Education acting as a slave. The master slaveconfiguration is used to give a continuous PWM of accurate waveform to the motor, where the slave

    micro-controller generates PWM and master coordinates between MATLAB, sensor and the slavemicro-controller.

    1.1 Design ObjectiveThe following are the design objectives for the developed Speed Control System:(i) It should be based on an indigenously developed self-calibrated digital sensor.(ii)It should be capable of handling higher currents due to actuators like DC fan motor.(iii)It should explore the different control schemes like on-off, differential gap, P, PD and PID to judge

    the effectiveness of one over the other.(iv)It should also provide a feature of data logging in real-time.(v)It should be user friendly.1.2 Features of DC Motor Control SystemThis section describes the various features of the developed Speed Control System.

    1. Auto Calibration The system provides a feature of automatic calibration of the optical encodercount against the applied duty cycle. This feature is provided as it was observed that motor showvarying calibration plots under different conditions. The various features in this module are:

    (i) Different Levels of Accuracy The system not only offers the feature of automaticcalibration, it also offers the flexibility to choose the accuracy of calibration. There are three

    levels of accuracy i.e. High, Medium and Low which can be selected from the MATLABGUI. When accuracy is set to High the system performs the best possible calibration buttakes slightly more time. As the accuracy is compromised the time required to perform thecalibration is improved.

    (ii) Curve Fitting The system also fit a second order polynomial to the obtained calibrationplot, plots the fitted curve on the actual curve for visualization and also shows the equation ofthe fitted curve.

    (iii) Fit Statistics The system also provides the statistics related to the quality of fit achieved. Itdisplays the coefficient of determination and the root mean square error of the fit.

    (iv) Recommendation The system also make recommendations on using or not to use anobtained calibration equation based on the fit statistics.

    (v) Calibration Data Logging The system also provides the feature of logging the obtainedcalibration data and stores it automatically in an excel file with its name having the currentdate and the logging time to avoid any overwriting of data in subsequent runs.

    (vi) Default Calibration In case poor calibration is obtained the system also provides the featureof using the default calibration.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    6/55

    MATLAB GUI of the system depicting the calibration plot and the fit statistics along with itsrecommendation in the top left message window.

    MATLAB GUI of the system depicting the calibration plot and the fit statistics along with itsrecommendation of using default calibration in the top left message window.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    7/55

    2. Controls In order to achieve a desired speed of the motor the desired RPM of the motor can be

    entered in the Required RPM text box in the GUI. The system offers the following types of controlsin order to achieve the desired speed of the dc motor:(i) Open-loop Control The open-loop control is based on the calibration equation and so is not

    very accurate in terms of achieving a desired RPM of the motor.

    MATLAB GUI of the system displaying the response of the system with Open-loop control.

    (ii) On-Off Control The On-Off control simply switches the system on and off based onwhether the current speed of the motor is less or more than the required RPM.

    MATLAB GUI of the system displaying the response of the system with On-Off control.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    8/55

    (iii) Differential Gap Control The differential gap control switches the system on and off butwhen it is beyond a certain range. The system provides the feature of changing thedifferential gap.

    MATLAB GUI of the system displaying the response of the system with Differential gap control.

    (iv) Proportional Control The system provides proportional control with the flexibility tochange the value of the Proportional gain.

    MATLAB GUI of the system displaying the response of the system with Proportional control.

    (v) Proportional-plus-Derivative Control The system also provides the feature to change thevalue of the gain related to the error derivative.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    9/55

    MATLAB GUI of the system displaying the response of the system with PD control.

    (vi) Proportional-plus-Derivative-plus-Integral Control All the three gains can be adjusted inorder to achieved the desired performance in this PID control.

    MATLAB GUI of the system displaying the response of the system with PID control.

    Here also the feature of data logging can be used to log any data required for further analysis of theresults. The different types of controls can be switched from within the GUI.

    3. Monitoring The system also provides the feature of monitoring the actual system with the help ofwebcam that is interfaced using MATLAB to the developed GUI. However, this feature currentlycannot be run simultaneously with the control operation as this requires higher computationalcapabilities.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    10/55

    4. Diagnostics This feature of the control system helps in identifying the current state of the system.

    A test is carried out by the system and based on the performance of the system it states the state ofthe system i.e. Healthy or Unhealthy, maximum RPM registered and the maximum optical encodercounter observed.

    5. Message Window The GUI also provides a small message window to let the end-user knowwhether the system is performing an operation or has completed the assigned operation.

    2.4 System ArchitectureThe system consists of a master micro-controller (NX-1000 board), a slave micro-controller(Board of Education), an optical encoder (digital RPM sensor), motor and a MATLAB port forcalculation and processing of results. The master micro-controller is interfaced with theMATLAB and slave micro-controller through serial port and acquires data from the digitalsensor. The purpose of slave micro-controller is to generate an accurate waveform PWM andcontrol the motor. The rationale behind using a dedicated micro-controller for generating PWMis to preserve the waveform of the PWM which might be changed if the micro-controller

    performs other tasks as well. All communications are asynchronous. The communicationbetween MATLAB and master micro-controller is bi-directional where as that between slave andmaster micro-controller is uni-directional. The PWM duty cycle and the number of cycles arefirst sent to the master micro-controller by MATLAB. This data is then transferred by the masterto the slave. The slave then becomes busy in applying the pulse to the motor based on the datareceived. The master in the mean time acquires data from the digital sensor and sends it to theMATLAB via serial port.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    11/55

    1

    P

    D

    C

    .3 Userhe followi

    . The GUI

    Boar

    Educa

    Mot

    WM

    ty for

    ycles

    Operatig are the in

    starts with

    Oftion

    or

    n Instrutructions fo

    a welcome s

    Asynchro

    Serial

    Communic

    D

    Opti

    PWM

    Duty & Cy

    ctionsr the user to

    creen and a

    Welcome S

    (Se

    ous

    tion

    PWM

    ty & Cycle

    cal Encoder

    Count

    les

    operate the

    picture of t

    reen of M

    NX000

    ATLAB

    rialPor

    developed

    e motor-se

    TLAB GUI

    )

    Bi-dir

    Asynchro

    Commu

    Optical E

    Cou

    igital Mult

    sor setup.

    ctional

    ous Serial

    nication

    ncoder

    nt

    i-meter:

    igitalSens

    PMr

  • 8/9/2019 MAE576 GroupD LAB3 Report

    12/55

    2. The user can then first run the diagnostics in order to verify that the system is healthy. Once thediagnostics is run the system will display the current state of the sensor-actuator system along withthe maximum rpm attainted by the motor and the maximum optical encoder count registered.

    3. Once the system is in healthy state the user can continue with other operations. In case the system isunhealthy the user must rerun the diagnostics. In case of recurrent failure of the system the user mustcheck the manual connections.

    4. Once diagnostics is completed successfully, the user should move on to the automatic calibration.This feature will recalibrate the system for any changes in the environmental conditions. Based onthe requirement the user can choose the level of desired accuracy. Also the user can check the datalogging option in case logging of the calibration data is required.

    5. Based on the calibration obtained and the system recommendation the user may continue using theobtained calibration by un-checking the Use Default Calibration option. In case of poor calibrationthe user should continue with the default calibration.

    6. Once the calibration is complete, the user can move on to explore the various control methodsoffered by the system. The user can start with the open-loop control. The user can enter the desiredvalue of rpm in the text box and switch the radio to run option. By running the system in open-loopthe user can understand how good the calibration of the system is. Here also the data logging optioncan be used to record the data in an excel file for further processing.

    7. The user can then move on to On-Off control to evaluate its performance. The system will displayboth the current rpm and the error in rpm for this type of control. The user can stop the system byclicking the stop radio button.

    8. The Differential gap control can then be explored. The gap value can be specified in the text box.The switching will take place as per this gap value now.

    9. For P, PD and PID control the user can specify the value of Kp, Kd and Ki in the respective text boxes. The system will display the current rpm, the proportional, the derivative and the integralcontrol applied on the motor.

    10.The user can also have look on the actual setup by clicking the video button which will display areal-time video of the system.

    11.It is recommended that the user refer the message window at the top left corner in order to assess thecurrent state of the system.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    13/55

    2. HardwareThe following sections deals with the details of the hardware used to implement the developed controlsystem.

    2.1 List of Components

    S. No. Component Quantity1. BASIC Stamp Kit NX-1000 1

    2. BASIC Stamp Module II 1

    3. 10K Resistor 1

    4. 1K Resistor 3

    5. 220 Resistor 2

    6. 0.68 F Capacitor 1

    7. 10K Variable Resistor 2

    8. IN4003 Diode 2

    9. ADC0831 2

    10. 12 VDC Brushless Fan 1

    11. IRF540N MOSFET 112. 100 Resistor 2

    The total estimated cost of the system is around 400$ including both the kits.

    2.2a Microcontroller (Master BASIC Stamp 2) Pin Assignment

    Pin No. I/O Description0 Output LCD Enable Pin

    4 Input ADC0831 Chip Select Pin

    5 Input ADC0831 Clock Pin6 Output ADC0831 Data Pin

    8 Output Transmitter Pin to Slave

    10 Input Receiver Pin from Slave

    11 Input ADC0831 Chip Select Pin

    12 Input ADC0831 Clock Pin

    13 Output ADC0831 Data Pin

    2.2b Microcontroller (Slave BASIC Stamp 2) Pin Assignment

    Pin No. I/O Description0 Output PWM Pin

    7 Input Receiver Pin from Master

    9 Output Transmitter Pin to Master

    2.3 Hardware Description

    Basic Stamp Kit INEX-1000

  • 8/9/2019 MAE576 GroupD LAB3 Report

    14/55

    http://www.mouser.com/catalog/supplier/library/ParallaxMiniCatalog.pdf

    1. INEX-1000 is a high-quality prototype and experiment area for all 24-pin BASIC Stamp modules2. Audio amplifiers with screw terminals for 8 ohm speakers. an audio amplifier for external speakers

    and current limit resistors sized for driving more LEDs. 510 ohm resistors allow more LED driving.3. Board provides socket ports for each BASIC Stamp I/O pin.4. A parallel LCD with cable.5. 16 LEDs to monitor I/O pin status.6. DB-9 connector for program download and debugging.7. 4-digit LED 7-segment display with common cathode.8. 8 pushbutton switches (active low without pull-up resistors) 8 DIP switches (with built-in pull-up

    resistors)9. ULN2003 high-current driver for relay and stepper motors10.Pulse generator for 1Hz, 10 Hz, 100 Hz, and 1 kHz11.RS-232 interface port for communication with COM program12.Socket for 24-pin BASIC Stamp modules13.Parallel LCD module with connector and brightness control14.Piezospeaker15.10K potentiometer16.2.5" x 7" breadboard with 800 contact points17.7.5V DC 1 amp power supply with polarity protectionSource: http://www.apexvalue.com/basic_stamp/product_id_28135.htm

    Basic Stamp II Module

    Microcontroller PIC 16C57 C signifies EPROM program memory

    Processor Speed Max Operation Frequency 20 MHz

    Program Execution Speed ~4,000 PBASIC instructions/sec

    Current Draw @ 5 VDC 3mA Run, 50 A Sleep

  • 8/9/2019 MAE576 GroupD LAB3 Report

    15/55

    Package 28-pin DIP

    Max Source / Sink Current by any I/O pin 20mA/25mA

    EEPROM (Program) Size: 2 Kbytes ~500 PBASIC instructions

    RAM Size: 32 Bytes (6 for I/0, 26 for Variable)

    ADC0831

    ADC0831 is a 8-bit successive approximation A/D converter with a serial I/O. The serial I/O isconfigured to comply with the NSC MICROWIRE serial data exchange standard for easy interface tothe COPS family of processors, and can interface with standard shift registers or Ps. The differentialanalog voltage input allows increasing the common-mode rejection and offsetting the analog zero inputvoltage value. In addition, the voltage reference input can be adjusted to allow encoding any smalleranalog voltage span to the full 8 bits of resolution.

    Key Specifications:

    Paramaters / Values ADC0831

    Resolution 8 bits

    Input Channels 1Max KSample Rate 31 ksps

    Max Sample Rate 0.031 MSPS

    LM358

    http://www.sparkfun.com/

    The LM358 is a dual-channel operational amplifier (opamp). LM358 applications includetransducer amplifiers, DC gain blocks and all the conventional opamp circuits.

    Features:

    Two internally compensated op-amps Internally frequency compensated for unity gain Large DC voltage gain: 100 dB Wide bandwidth (unity gain): 1 MHz (temperature compensated) Wide power supply range:oSingle supply: 3V to 32Voor dual supplies: 1.5V to 16V

  • 8/9/2019 MAE576 GroupD LAB3 Report

    16/55

    Optical Sensor:

    The QRB1113/1114 consists of an infrared emitting diode and an NPN silicon phototransistormounted side by side on a converging optical axis in a black plastic housing. The phototransistorresponds to radiation from the emitting diode only when a reflective object passes within its fieldof view. The area of the optimum response approximates a circle .200" in diameter.

    Features:

    No contact surface sensing Phototransistor output Focused for sensing specular reflection Daylight filter on photosensor Dust cover

  • 8/9/2019 MAE576 GroupD LAB3 Report

    17/55

    IRF540N

    Pin 1 Gate (G)Pin 2 Drain (D)

    Pin 3 Source (S)Features:Ultra Low-On Resistance2. Simulation Models- Temperature Compensated PSPICE and SABER Electrical Models- Spice and SABER Thermal Impedance Models

    Brushless DC motor (12 VDC):

    A brushless DC (BLDC) motor is a synchronous electric motor powered by direct-current(DC) electricity and having an electronic commutation system, rather than a mechanicalcommutator and brushes.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    18/55

    2.4 Circuit DiagramsMotor Interface Circuit

    +

    Ri

    12k

    Rf

    10k

    R1

    10k

    C1

    0.6

    8MF

    Rd2

    1k

    Rd1

    1k

    Vss

    Vss

    Vss

    Vss

    Vss

    Vin

    Vdd

    FAN

    U1

    LM358(a)

    Q1

    2N3904

    Master

    P0

    MasterP

    11

    MasterP

    12

    MasterP

    13

    4

    56

    7

    8

    1 2 3 4

    8 7 6 5

    /CS

    Vdd

    Vin(+)

    Vin()

    GND

    Vre

    f

    CLK

    DO

    ADC0831

  • 8/9/2019 MAE576 GroupD LAB3 Report

    19/55

    The above circuit was first implemented with the aim of providing 10V of supply to the motor.However, it was observed that the output to the motor is significantly reduced as soon as the operationalamplifier is introduced in the circuit. To avoid any such reduction in voltage to the motor the followingcircuit was finally implemented.

    Motor Interface Circuit

    The motor is controlled by the slave micro-controller with a PWM. A separate micro-controller is usedin order to preserve the waveform of the applied PWM.

    Digital Sensor CircuitThe digital sensor was not used with transistor as it was observed that the system doesnt giveappreciable output once the transistor is used in the circuit.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    20/55

    Master-Slave-Laptop Communication Circuit

    Since, separate micro-controller is used to control the motor communication need to be establishedbetween the master and the slave micro-controller. The master and the slave communicates in anasynchronous mode. Furthermore, the master and the laptop also communicates in an asynchronousmode using serial port.

    Complete Circuit Diagram for Developed Speed Control System

  • 8/9/2019 MAE576 GroupD LAB3 Report

    21/55

    2.5 Mechanical Setup

    Top View

    1. The fan is mounted on the flexi-glass surface using screws present on the four corners of the fan.2. Encoder pattern is attached on one of the faces of fan using glue.3. Also, the Opto-Reflective Switch is mounted, using the Screw and Nut arrangement which is

    adjustable. This helps in adjusting the distance of the encoder from the sensor.4. Moreover the fan attachment is easily removable and can be replaced by another motor if need be.

    EncoderWheel

    BrushlessFan

    Flexi-GlassMaterial

    Adjustable Slotarrangement using

    bolt and nut

  • 8/9/2019 MAE576 GroupD LAB3 Report

    22/55

    3. Software

    The following section presents a basic overview of the important commands used and majorprogramming challenges faced while implementing the system.

    3.1PBASIC Commands

    The PBASIC version 2.5 is used to program the BASIC Stamp II module [2]. The following specialcommands are used to program the module:

    1. SERIN - Receive asynchronous serial data (e.g., RS-232 data).Syntax: SERINRpin {\Fpin}, Baudmode, {Plabel,} {Timeout, Tlabel,} [InputData]

    2. SEROUT - Transmit asynchronous serial data (e.g., RS-232 data).Syntax: SEROUTTpin {\Fpin}, Baudmode, {Pace,} {Timeout, Tlabel,} [OutputData]

    3.2 Programming Challenges

    The following are the challenges faced while implementing the system:

    (i) Master-Slave Micro-controller Synchronization: Since, the asynchronous mode of communication isused to transfer data between the two micro-controllers it was important that no data is lost. This isensured by employing the timeout option of the SERIN and SEROUT commands. In case the programs running in the master and slave are not synchronized the timeout sends the programcontrol back to its original place so that no data is lost.

    (ii)Master-MATLAB Synchronization: This is ensured by providing sufficient time out delay of around10 seconds in MATLAB.

    (iii)Data Package Format: The format for the data package is defined such that as soon as the data isreceived the termination character will let the processor know that the data has been transferred. Thedata package is defined with a common termination character of ASCII equivalent of 10 to ensurethat the data transfer is smooth.

    (iv)Multiple Runs without Hardware Reset: The system has the capability to run continuously withoutthe need of hardware reset. This has been achieved by looping the system using time out feature suchthat only when the data transfer takes place that the programs in the stamps will actually moveforward.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    23/55

    . Mat

    .1 On-For

    setpo

    facto

    .2 DiffIt isthe v

    .3 ProIn prinsta

    .4 PDDeri

    acco

    .5 PID

    hema

    Off Contn-Off cont

    int. If the v

    r is increase

    rential Gtype of on-

    ariable reac

    ortionalportional ctaneous va

    ontrolative contr

    dingly. A p

    Control

    Set-

    ical

    olol, instanta

    lue is more

    d if the valu

    ap Controff control,es at the to

    Controlontrol, the due of variab

    l measure t

    oportional

    Point

    ethod

    eous value

    than the set

    e is below t

    lwhere the d

    or bottom

    riving factole and the d

    e rate of ch

    nd derivati

    s

    of the varia

    oint, drivin

    e setpoint.

    iving factoof the range

    is proportiesired value

    .

    ange of err

    e control u

    . .

    OFF

    ON

    le is measu

    g factor is d

    is turned ospecified a

    nal to the d.

    r and chang

    ed together

    ed and com

    ecreased an

    or off if thout the set-

    ifference be

    es the contr

    can be repr

    pared to the

    d driving

    e value ofoint.

    tween the

    l signal

    sented as:

  • 8/9/2019 MAE576 GroupD LAB3 Report

    24/55

    I

    For acontr

    Thus

    n terms of tifference.

    PID controoller calcul

    , PID contr

    e numerica

    l, integral ctes the accu

    l can be sho

    l calculatio

    ntrol is usemulation of

    wn as:

    .

    the integra

    in combinerror and c

    .

    and deriva

    tion with Plculates the

    ..

    ive can be r

    control.area below

    eplaced by

    n integralthe curve.

    ummation nd finite

  • 8/9/2019 MAE576 GroupD LAB3 Report

    25/55

    4.6 PWM controlPulse-width modulation (PWM) is a very efficient way of providing intermediate amounts ofelectrical power between fully on and fully off. A simple power switch with a typical power sourceprovides full power only, when switched on. The term duty cycle describes the proportion of on timeto the regular interval or period of time; a low duty cycle corresponds to low power, because thepower is off for most of the time. Duty cycle is expressed in percent, 100% being fully on.

    The waveform shown above represents the voltage signal amplitude against time. As the duty cycleof the pulse is changed the average voltage obtained as output varies based on the pulse on time andpulse off time.

    In our system the control of the motor is achieved by varying the duty cycle of the pulse and thenumber of cycles for which the pulse is repeated.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    26/55

    5. Implementation

    The following section details the algorithms used along with the various MATLAB and Basic Stampsubroutines used to implement them.

    The following figure shows the final setup of the system implemented using NX-1000 Experiment

    Board and Board of Education.

    5.1 Algorithms

    The following section presents the various algorithms used to implement different features of thesystem. The different algorithms used are as follows:

    1. Controls Flowchart2. Auto Calibration Flowchart3. Master BS-2 Flowchart4. Slave BS-2 Flowchart5. Open-Loop Control Flowchart6. On-Off Control Flowchart7. Differential Gap Control Flowchart8. PID Control Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    27/55

    5.1.1 Controls Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    28/55

    5.1.2AutoCalibration Flowchart

    5.1.3Master BS-2 Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    29/55

    5.1.4Slave BS-2 Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    30/55

    5.1.5Open-Loop Control Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    31/55

    5.1.6On-Off Control Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    32/55

    5.1.7Differential Gap Control Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    33/55

    5.1.8PID Control Flowchart

  • 8/9/2019 MAE576 GroupD LAB3 Report

    34/55

    5.2 Subroutines

    The main functions used are in MATLAB as the micro-controllers are only being used to transfer datafrom sensor and to actuator. The following functions are used in MATLAB GUI for implementingvarious features:

    (i) Calibration Function This function provides the various inputs to the master BS-2 forperforming the calibration based on the accuracy selected.

    (ii) Controls Function This function controls the dc motor by providing the duty cycle and numberof cycles required to control the system.

    (iii) Video Function This function search for a connected video device and display the video streamcaptured by the device.

    (iv) Clear Plot Function This function clears the plot.(v) Diagnostics Function This function runs the diagnostics on the system and evaluate the state ofthe system.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    35/55

    6. Calibration & Testing

    The digital sensor was first calibrated in order to determine the optimum distance for best performanceof the system and then the system calibration was carried out. The designed system was then tested forperformance for different controls.

    6.1 Digital Sensor CalibrationThe digital sensor calibration was carried out in order to determine the best distance of placing thedigital sensor from the encoder wheel. Black surface and white surface the gradually moved in front ofthe sensor and the various voltages are recorded. The sensor was finally mounted at the position atwhich the maximum difference in voltage is observed for the white and black surface.

    0

    1

    2

    3

    4

    5

    6

    0 0.5 1 1.5 2 2.5

    Voltage(V)

    Distance(cm)

    DigitalSensorVoltageOuputWhiteSurface BlackSurface

    0

    0.5

    1

    1.52

    2.5

    3

    3.5

    4

    0 0.5 1 1.5 2 2.5

    Volta

    ge(V)

    Distance(cm)

    VoltageDifference

  • 8/9/2019 MAE576 GroupD LAB3 Report

    36/55

    6.2 Duty Cycle Vs Optical Encoder Count CalibrationThe auto calibration feature helped in calibrating the system with almost no effort. Also the calibrationwith low and high accuracy was performed in order to check the quality of fit. Both the calibrationshowed good results.

    6.3 TestingThe following presents the results for different kinds of controls implemented:

  • 8/9/2019 MAE576 GroupD LAB3 Report

    37/55

    6.3.1 DiagnosticsThe following diagnostics show that the system is in healthy state with maximum rpm of 5325and maximum optical encoder count of 71.

    6.3.2 Open-Loop ControlThe response shows that there is a significant error in the required rpm and the actual rpm inopen-loop control.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    38/55

    6.3.3 On-Off ControlThe response shows that though the system is oscillating around the required rpm but theoscillations are appreciable.

    6.3.4 Differential Gap ControlThe system response depicts that the switching takes place only when the system moves out ofthe specified zone due to which even higher deviations in the output are observed.

    6.3.5 Proportional ControlThe system shows that though the output becomes very steady but there is significant steady-state error.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    39/55

    6.3.6 PD ControlThe response shows that both the proportional and the derivative control action in acting tocontrol the system.

    6.3.7 PID ControlThe response was first evaluated with a 4 cycle/revolution optical encoder. The response showedsignificant oscillations. Also the plots are for optical encoder count.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    40/55

    The system was finally modified for 8 cycle/revolution optical encoder. The response shows thatthe system is oscillating about the required output.

    0 200 400 6000

    10

    20

    30Opto Count

    0 200 400 600-20

    -10

    0

    10

    20Error Opto Count

    0 200 400 600-10

    0

    10

    20de Opto Count

    0 200 400 600-200

    -100

    0

    100ie Opto Count

  • 8/9/2019 MAE576 GroupD LAB3 Report

    41/55

    7. Discussion

    The system still has a scope for improvement. The following is a list of the features that can eitherimprove the control performance or can be an added feature:

    The system control doesnt optimize the gains for achieving good performance. The gains still need tobe tweaked by the user in order to obtain desired performance. The feature which can automatically

    change the gain values and can select the gain values based on the obtained response can be veryuseful.

    The developed monitoring system cannot be currently used in real-time to monitor the system. Thiscan be improved by writing more efficient algorithms or more practically by increasing thecomputational capability of the system.

    The performance of the system is limited by the accuracy of the rpm measurement by the opticalencoder. The optical encoder used is very basic. An optical encoder with multiple sensors can be used

    in order to improve the accuracy of optical encoder count.

    The PWM offers around 100 levels at present. More precise control can be obtained if more levels areused to actuate the motor.

    The system does not provide statistics regarding the performance of a control. Further analysis of theresponse can be carried out in order to obtain settling time, maximum overshoot, steady state error etc

    which can quantify the control performance.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    42/55

    8. Conclusion

    The following design objectives are met:(i) The rpm sensor was indigenously developed with its position selected for optimum performance(ii)The system provides a very user friendly way to explore the various control strategies available for

    controlling devices.(iii)The system also provides the feature of data logging in real-time, auto calibration and diagnostics.

    (iv)The system is highly user friendly with a MATLAB GUI interface and message window to guide theuser.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    43/55

    Contribution by each Team Member

    Priyanshu Agarwal: Algorithm Coding, overall system integration, coordination among team membersand lab report.

    Dipen Harishbhai Dave: Developed mechanical set up for the system, calibration and mathematicalmethods section in lab report.

    Ravikiran Chollangi: Developed circuits for the system, asynchronous communication between masterand slave, and hardware section in lab report.

    Jason Lieu:Drawn flow charts of the system and circuit diagrams for lab report.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    44/55

    Bibliography[1] Process Control, Student Guide, PARALLAX INC., Version 1.0

    [2] PBASIC Syntax Guide, PARALLAX INC., BASIC Stamp Editor/Development System, Version2.4.2.

    [3] StampWorks Manual Version 1.1a, Parallax Inc.

  • 8/9/2019 MAE576 GroupD LAB3 Report

    45/55

    Appendix

    A. PBASIC Code for Speed Control SystemA.1 Slave Microcontroller Code

    ' {$STAMP BS2}

    ' {$PBASIC 2.5}' =========================================================================' LAB3: SPEED CONTROL OF A DC MOTOR PBASIC CODE (SLAVE)'' GROUP D'' Priyanshu Agarwal' Dipen Harishbhai Dave

    ' Ravikiran Chollangi' Jason Lieu'' =========================================================================' ' CONSTANTS & VARIABLES DEFINITION' RXS PIN 7 ' RX of SlaveTXS PIN 9 ' TX of SlaveFan PIN 0 ' Pin no of Fan

    Duty VAR Byte ' Duty cycle of the PWMx VAR Byte ' Counter in the loopCycles VAR Byte ' No of PWM cycles

    Baud CON 84 ' Baud Rate is 9600

    ' [ Main Program in Slave ]

    Program_Start:No_Data:DEBUG CR,"Waiting for Master Synchronization"

    SERIN RXS, Baud, 200, No_Data, [WAIT(10)] ' Waits for a 10 which is the termination character. This ensures Master Slave Synchronization.

    Duty = 0 ' initializing duty with zero.DO

    GOSUB Apply_DriveNo_Data2:SERIN RXS, Baud, 2000, No_Data2, [DEC Duty, WAIT(10)] ' Wait for a BYTE and put it in Duty.

    ' In case nothing is received send back to No_Data_2SERIN RXS, Baud, 2000, No_Data2, [DEC Cycles, WAIT(10)] ' Wait for a BYTE and put it in Cycles

    LOOP

  • 8/9/2019 MAE576 GroupD LAB3 Report

    46/55

    Apply_Drive: ' Apply drive with a 100msc period

    FOR x = 1 TO Cycles ' Apply for repetitions equal to number of CyclesIF duty > 0 THEN HIGH Fan ' Check if any HIGH timePAUSE Duty ' Apply for amount of high timeIF duty < 100 THEN LOW Fan ' Check if any LOW timePAUSE 100Duty ' Apply for rest of 100mSec

    NEXTRETURN

    A.2 Master Microcontroller Code

    ' {$STAMP BS2}' {$PBASIC 2.5}' =========================================================================' LAB3: SPEED CONTROL OF A DC MOTOR PBASIC CODE (MASTER)'' GROUP D

    '' Priyanshu Agarwal' Dipen Harishbhai Dave' Ravikiran Chollangi' Jason Lieu'' =========================================================================

    ' ' CONSTANTS & VARIABLES DEFINITION'

    Opto_SW PIN 1 ' OptoReflectorOpto_Count VAR Word ' Count from optoreflective switchDuty VAR Byte ' Duty cycle value 0255Cycles VAR Byte ' No of cycles of a duty cycle

    RX PIN 14 ' Serial port RX PinTX PIN 15 ' Serial port TX PinTXM PIN 8 'TX pin of MasterRXM PIN 10 'RX pin of Master

    Baud CON 84 ' Baud Rate is 9600

    Program_Start:SEROUT TX, Baud, [10] ' write the termination character 10 to slaveDO

    No_Data1:SERIN RX, Baud, 2000, No_Data1,[DEC Duty, WAIT(10)] ' Wait for a BYTE and put it in DutySERIN RX, Baud, 2000, No_Data1,[DEC Cycles, WAIT(10)] ' Wait for a BYTE and put it in CyclesSEROUT TXM, Baud, [DEC Duty , 10] ' Transmit Duty to Slave uControllerSEROUT TXM, Baud, [DEC Cycles , 10] ' Transmit Duty To Slave uController

  • 8/9/2019 MAE576 GroupD LAB3 Report

    47/55

    COUNT Opto_SW,100,opto_count ' Count number of pulses from sensorSEROUT TX, Baud, [DEC opto_count, 10] ' Transmit count to MATLAB via serial port

    LOOP

    B. MATLAB GUI Code for Speed Control Systemfunction varargout = Motor_Control(varargin)

    % MOTOR_CONTROL M-file for Motor_Control.figgui_Singleton = 1;

    gui_State = struct('gui_Name', mfilename, ...

    'gui_Singleton', gui_Singleton, ...

    'gui_OpeningFcn', @Motor_Control_OpeningFcn, ...

    'gui_OutputFcn', @Motor_Control_OutputFcn, ...

    'gui_LayoutFcn', [] , ...

    'gui_Callback', []);

    if nargin && ischar(varargin{1})

    gui_State.gui_Callback = str2func(varargin{1});

    end

    if nargout

    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});

    else

    gui_mainfcn(gui_State, varargin{:});

    end

    % End initialization code - DO NOT EDIT

    % --- Executes just before Motor_Control is made visible.

    function Motor_Control_OpeningFcn(hObject, eventdata, handles,

    varargin)

    handles.output = hObject;

    % Update handles structureguidata(hObject, handles);

    clc;

    global sPort CyclesPerRev Cycles Scale P1 P2 P3; % Define global

    variables

    Cycles = 15; % No of PWM cycles applied in one go.

    CyclesPerRev = 8; % No of encoder pulses per revolution

    Scale = 600/CyclesPerRev; % Scale to convert pulse count to RPM

    P1 = 0.015525; % Calibration constant 1

    P2 = 0.11082; % Calibration constant 2

    P3 = 2.2737; % Calibration constant 3

    devices = instrfind; % Find all open devicesif(~isempty(devices)) % If devices are open

    fclose(devices); % Close the devices

    end

    subplot(1,1,1,'Position',[0.2 0.05 0.75 0.8],'FontSize',1);

    I = imread('System.jpg'); %Read the image of the system

    imshow(I); %Show the image

    box on;

    sPort =

    serial('COM4','BaudRate',9600,'Tag','BTDevice','Timeout',10,'Terminat

    or',10,'OutputBufferSize',8)

  • 8/9/2019 MAE576 GroupD LAB3 Report

    48/55

    fopen(sPort) %Open serial port

    % --- Outputs from this function are returned to the command line.

    function varargout = Motor_Control_OutputFcn(hObject, eventdata,

    handles)

    varargout{1} = handles.output;

    % --- Executes on button press in button_video.

    function button_video_Callback(hObject, eventdata, handles)vid = videoinput('winvideo', 1, 'RGB24_720x480'); %Define video input

    object

    preview(vid); % Preview the video object

    % % --- Executes on button press in button_run.

    function button_run_Callback(hObject, eventdata, handles)

    global sPort CyclesPerRev Cycles P1 P2 P3 Scale; % Define global

    variables

    Opto_Count_Max = 80 %Maximum optical encoder count

    Kp = 2Kd = 0.01

    Ki = 1

    i = 1; % Loop counter

    PWM_Levels = 100; % No of PWM levels

    Req_RPM = str2num(get(handles.edit_reqdrpm,'String')) % Read required

    RPM

    E_Opto_Count = [0];

    e_Time = 1;

    DE_Opto_Count = [0];

    IE_Opto_Count = [0];Opto_Counter = [0];

    I = [1];

    Cycles = 10

    set(handles.text_message,'String','Running!')

    if(get(handles.checkbox_def_calibration,'Value')==1) % If default

    calibration is checked

    P1 = 0.015525;

    P2 = 0.11082;

    P3 = 2.2737;

    end

    if(get(handles.radio_openloop,'Value') == 1) % Classifying Control

    control_type = 0; % Open Loop

    elseif(get(handles.radio_onoff,'Value') == 1) % Classifying Control

    opto_gap = 0;

    control_type = 1; % On Off

    elseif(get(handles.radio_differential,'Value') == 1) % Classifying

    Control

    rpm_gap = str2num(get(handles.edit_rpm,'String'));

    opto_gap = rpm_gap/Scale;

    control_type = 1; %Differential Gap

    elseif(get(handles.radio_p,'Value') == 1) % Classifying Control

  • 8/9/2019 MAE576 GroupD LAB3 Report

    49/55

    control_type = 2;

    Kp = str2num(get(handles.edit_kp,'String')); %Proportional

    Kd = 0;

    Ki = 0;

    elseif(get(handles.radio_pd,'Value') == 1) % Classifying Control

    control_type = 2; % PD

    Kp = str2num(get(handles.edit_kp,'String'));

    Kd = str2num(get(handles.edit_kd,'String'));

    Ki = 0;elseif(get(handles.radio_pid,'Value') == 1) % Classifying Control

    control_type = 2; %PID

    Kp = str2num(get(handles.edit_kp,'String'));

    Kd = str2num(get(handles.edit_kd,'String'));

    Ki = str2num(get(handles.edit_ki,'String'));

    end

    Req_Opto_Count =Req_RPM*CyclesPerRev/(600); % Calculating Required

    Optical Encoder Count from Required RPM

    % DutyCycle = 0.088*Req_Opto_Count^2 + 0.171*Req_Opto_Count +

    20.03+40 % Default Calibration EquationDutyCycle = P1*Req_Opto_Count^2 + P2*Req_Opto_Count + P3 +40

    % Calibration Equation

    status = 1 % While the Run radio button is selected

    while(status == 1)

    i= i+1; % increment loop counter

    I = [I i];

    if(DutyCycle>PWM_Levels) % If Calculated Duty

    Cycle>Max Value

    DutyCycle = PWM_Levels; % reduce to Max Value

    elseif(DutyCycle

  • 8/9/2019 MAE576 GroupD LAB3 Report

    50/55

    subplot(1,2,2,'Position',[0.60 0.05 0.35 0.8],'FontSize',10);

    box on

    plot(I,E_Opto_Count*Scale,'-r','Linewi',1);

    title('RPM Error Plot');

    grid on

    hold on

    pause(0.001)

    elseif(control_type == 1) %On-Off & Differential Gap

    Controlif(Req_Opto_Count-Opto_Count>opto_gap) % Decide duty cycle

    based on error and gap

    DutyCycle = PWM_Levels;

    elseif(Opto_Count-Req_Opto_Count>opto_gap)

    DutyCycle = 0;

    end

    if(abs(Opto_Count-Req_Opto_Count)0)% && Ki~=0) % Adjust no of

    cycles based on current error

    Cycles = 1;

    else

    Cycles = 15;

    end

    subplot(2,2,1,'Position',[0.2 0.50 0.35 0.35],'FontSize',10);

    % Plot all quantities

    box on

    plot(I,Opto_Counter*Scale,'-b','Linewi',1)

  • 8/9/2019 MAE576 GroupD LAB3 Report

    51/55

    hold on

    plot(I,Req_Opto_Count*Scale*ones(size(I)),'-r','Linewi',1);

    title('RPM Plot','Fontsize',12)

    grid on

    subplot(2,2,2,'Position',[0.6 0.50 0.35 0.35],'FontSize',10);

    plot(I,Kp*E_Opto_Count*Scale,'-r')

    title('Kp*RPM Error Plot','Fontsize',12)

    grid on

    hold onsubplot(2,2,3,'Position',[0.2 0.06 0.35 0.35],'FontSize',10);

    box on

    plot(I,Kd*DE_Opto_Count*Scale,'-g')

    title('Kd*Error Derivative Plot','Fontsize',12)

    grid on

    hold on

    subplot(2,2,4,'Position',[0.6 0.06 0.35 0.35],'FontSize',10);

    box on

    plot(I,Ki*IE_Opto_Count*Scale,'-k')

    title('Ki*Error Integral Plot','Fontsize',12)

    grid onhold on

    pause(0.001) %Pause to Plot the data

    if(New_Opto_Count>Opto_Count_Max) % Check new optical

    encoder count

    New_Opto_Count = Opto_Count_Max;

    elseif(New_Opto_Count

  • 8/9/2019 MAE576 GroupD LAB3 Report

    52/55

    set(handles.text_message,'String','Calibrating! Please Wait...')

    calibration_type = get(handles.dropdown_calibration,'Value') %Get

    level of accuracy

    if(calibration_type ==1) % High Accuracy

    delta_Duty=1;

    elseif(calibration_type ==2) % Medium Accuracy

    delta_Duty=2;

    elseif(calibration_type ==3) %Low Accuracy

    delta_Duty=3;end

    disp('Synchronized');

    cla;

    axis([0 80 0 120]);

    xlabel('Optical Encoder Count \rightarrow','FontSize',12);

    ylabel('Duty Cycle \rightarrow','FontSize',12);

    title('Calibration Plot','FontSize',14);

    grid on

    hold on

    for Duty=140:-delta_Duty:0 % Vary duty cycle to obtain thecalibration plot

    if(Duty>100)

    Duty = 100;

    end

    fprintf(sPort,'%d\n',Duty); % Send duty to Master BS2

    fprintf(sPort,'%d\n',Cycles); % Send cycles to Master BS2

    Opto_Count = fscanf(sPort,'%d\n') %Scan optical encoder count

    Duty_Cycle = [Duty_Cycle Duty];

    Opto_Counter = [Opto_Counter Opto_Count];

    plot(Opto_Counter,Duty_Cycle,'-r','Linewi',1);

    pause(0.001);end

    Opto_Counter = Opto_Counter(40/delta_Duty:140/delta_Duty);

    Duty_Cycle = Duty_Cycle(40/delta_Duty:140/delta_Duty);

    [fit1,gof1,out1] = fit(Opto_Counter',Duty_Cycle','poly2'); %Fit 2

    degree polynomial

    P1 = fit1.p1 % Coefficient 1

    P2 = fit1.p2 % Coefficient 2

    P3 = fit1.p3 % Coefficient 3

    text(1,65,['Coefficient of determination = '

    num2str(gof1.rsquare)],'FontSize',12);

    text(1,55,['Root mean squared error = '

    num2str(gof1.rmse)],'FontSize',12);

    text(1,45,['DC = ' num2str(P1) 'x^2+' num2str(P2) 'x+'

    num2str(P3)],'FontSize',12);

    f = P1*z^2+P2*z+P3; %Obtain calibration equation

    ezplot(f,[0 80]); % Plot calibration equation

    axis([0 80 0 120]);

    xlabel('Optical Encoder Count \rightarrow','FontSize',12);

    title('Calibration Plot','FontSize',14);

    if(gof1.rmse>5) % If rms value is more than 5 => Poor Calibration

  • 8/9/2019 MAE576 GroupD LAB3 Report

    53/55

    set(handles.text_message,'String','Poor Calibration!, Use Default

    Calibration')

    else

    set(handles.text_message,'String','Good Calibration!')

    end

    if(get(handles.checkbox_log,'Value')==1)

    c = clock;

    xlswrite(['Calibration' date num2str(c(4))

    num2str(c(5))],[Opto_Counter' Duty_Cycle']);set(handles.text_message,'String','Data Logged!') %Log data in

    xls file

    end

    % --- Executes on selection change in dropdown_calibration.

    function dropdown_calibration_Callback(hObject, eventdata, handles)

    % --- Executes during object creation, after setting all properties.

    function dropdown_calibration_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');

    end

    function edit_kp_Callback(hObject, eventdata, handles)

    % --- Executes during object creation, after setting all properties.

    function edit_kp_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))

    set(hObject,'BackgroundColor','white');

    end

    function edit_kd_Callback(hObject, eventdata, handles)

    % --- Executes during object creation, after setting all properties.

    function edit_kd_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))

    set(hObject,'BackgroundColor','white');

    end

    function edit_ki_Callback(hObject, eventdata, handles)

    % --- Executes during object creation, after setting all properties.

    function edit_ki_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))

    set(hObject,'BackgroundColor','white');

    end

    function edit_rpm_Callback(hObject, eventdata, handles)

  • 8/9/2019 MAE576 GroupD LAB3 Report

    54/55

    % --- Executes during object creation, after setting all properties.

    function edit_rpm_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))

    set(hObject,'BackgroundColor','white');

    end

    function edit_reqdrpm_Callback(hObject, eventdata, handles)

    % --- Executes during object creation, after setting all properties.

    function edit_reqdrpm_CreateFcn(hObject, eventdata, handles)

    if ispc && isequal(get(hObject,'BackgroundColor'),

    get(0,'defaultUicontrolBackgroundColor'))

    set(hObject,'BackgroundColor','white');

    end

    % --- Executes on button press in button_exit.

    function button_exit_Callback(hObject, eventdata, handles)

    status = 0;

    devices = instrfind;fclose(devices);

    close all;

    % --- Executes on button press in button_clear.

    function button_clear_Callback(hObject, eventdata, handles)

    subplot(1,1,1,'Position',[0.2 0.05 0.75 0.8],'FontSize',1); % Clear

    the plot

    box on

    cla

    % --- Executes on button press in checkbox_log.function checkbox_log_Callback(hObject, eventdata, handles)

    % --- Executes on button press in checkbox_def_calibration.

    function checkbox_def_calibration_Callback(hObject, eventdata,

    handles)

    % --- Executes on button press in button_diagnostics.

    function button_diagnostics_Callback(hObject, eventdata, handles)

    global sPort Cycles Scale P1 P2 P3;

    Duty_Cycle = [];

    Opto_Counter = [];

    Cycles = 15;

    subplot(1,1,1,'Position',[0.2 0.06 0.75 0.8],'FontSize',1);

    axis([0 80 0 120]);

    box on;

    set(handles.text_message,'String','Running Diagnostics! Please

    Wait...')

    drawnow;

    calibration_type = get(handles.dropdown_calibration,'Value')

    disp('Synchronized');

  • 8/9/2019 MAE576 GroupD LAB3 Report

    55/55

    cla;

    for Duty=100:10:200 % Run motor at full duty to achieve highest rpm

    if(Duty>100)

    Duty = 100;

    end

    fprintf(sPort,'%d\n',Duty);

    fprintf(sPort,'%d\n',Cycles);

    Opto_Count = fscanf(sPort,'%d\n')

    Opto_Counter = [Opto_Counter Opto_Count];end

    pause(5)

    set(handles.text_message,'String','Diagnostics Completed!')

    drawnow;

    if(max(Opto_Counter)>60) % If full rpm is not achieved

    text(20,70,['System State: HEALTHY'],'FontSize',14);

    else

    text(20,70,['System State: UNHEALTHY'],'FontSize',14);

    end

    text(20,80,['Diagnostics Results'],'FontSize',14);

    text(20,60,['Max RPM Registered = 'num2str(max(Opto_Counter)*Scale)],...

    'FontSize',14); % Display maximum rpm

    text(20,50,['Max Optical Encoder Count Registered = '

    num2str(max(Opto_Counter))],...

    'FontSize',14); % Display maximum encoder count

    fprintf(sPort,'%d\n',0);

    fprintf(sPort,'%d\n',0);