You are on page 1of 55

LAB 3:

SPEED CONTROL OF A DC MOTOR


Mechatronics 576
Spring 2010
April 13th, 2010

“Group D”

Priyanshu Agarwal
Dipen Harishbhai Dave
Ravikiran Chollangi
Jason Lieu

Department of Mechanical and Aerospace Engineering


State University of New York at Buffalo
Buffalo, New York 14260
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.
Contents
Abstract 
 
Contents 
1. Introduction 
1.1 Design Objective 
1.2 Features of DC Motor Control System 
1.3 System Architecture 
1.4 User Operation Instructions 

2. Hardware 
2.1 List of Components 
2.2a Microcontroller (Master BASIC Stamp 2) Pin Assignment 
2.2b Microcontroller (Slave BASIC Stamp 2) Pin Assignment 
2.3 Hardware Description 
2.4 Circuit Diagrams 
2.5 Mechanical Setup 
 

3. Software 
3.1 PBASIC Commands 
3.2 Programming Challenges 

4. Mathematical Methods 
4.1 On‐Off Control 
4.2 Differential Gap Control 
4.3 Proportional Control 
4.4 PD Control 
4.5 PID Control 
4.6 PWM control 

5. Implementation 
5.1 Software Algorithms 
5.1.1 Controls Flowchart 
5.1.2 Auto Calibration Flowchart 
5.1.3 Master BS‐2 Flowchart 
5.1.4 Slave BS‐2 Flowchart 
 
5.1.5 Open‐Loop Control Flowchart 
5.1.6 On‐Off Control Flowchart 
5.1.7 Differential Gap Control Flowchart 
5.1.8 PID Control Flowchart  
5.2 Subroutines 
 

6. Calibration & Testing 
6.1 Digital Sensor Calibration 
6.2 Duty Cycle Vs Optical Encoder Count Calibration 
6.3 Testing 
6.3.1 Diagnostics 
6.3.2 Open‐Loop Control 
6.3.3 On‐Off Control  
6.3.4 Differential Gap Control  
6.3.5 Proportional Control 
6.3.6 PD Control 
6.3.7 PID Control  
 

7. Discussion 
8. Conclusion 

Bibliography 
 
Appendix 
 
A. PBASIC Code for Speed Control System 

A.1 Slave Micro‐controller Code 

A.2 Master Micro‐controller Code 

B. MATLAB GUI Code for Speed Control System 

 
 
1. Introduction
A DC motor is used in a variety of applications, and precise control of speed is important. Here we use
an opto-reflective sensor to measure the speed and give feedback for closed loop control. Multiple
control methods, viz. on-off, Differential, Proportional, PD and PID are implemented in the form of a
MATLAB GUI. MATLAB is used for back end calculations, which communicates with the NX-1000
board acting as the master and another Board of Education acting as a slave. The master slave
configuration 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 slave
micro-controller.
 
1.1 Design Objective
The 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 System


This 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 encoder
count against the applied duty cycle. This feature is provided as it was observed that motor show
varying 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 automatic
calibration, 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 MATLAB
GUI. When accuracy is set to High the system performs the best possible calibration but
takes slightly more time. As the accuracy is compromised the time required to perform the
calibration is improved.

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

(iii) Fit Statistics – The system also provides the statistics related to the quality of fit achieved. It
displays 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 an
obtained calibration equation based on the fit statistics.

(v) Calibration Data Logging – The system also provides the feature of logging the obtained
calibration data and stores it automatically in an excel file with its name having the current
date 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 feature
of using the default calibration.
MATLAB GUI of the system depicting the calibration plot and the fit statistics along with its
recommendation in the top left message window.

MATLAB GUI of the system depicting the calibration plot and the fit statistics along with its
recommendation of using default calibration in the top left message window.
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 controls
in 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 on
whether 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.
(iii) Differential Gap Control – The differential gap control switches the system on and off but
when it is beyond a certain range. The system provides the feature of changing the
differential 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 to
change 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 the
value of the gain related to the error derivative.
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 in


order 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 the
results. 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 of
webcam that is interfaced using MATLAB to the developed GUI. However, this feature currently
cannot be run simultaneously with the control operation as this requires higher computational
capabilities.
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 of
the system i.e. Healthy or Unhealthy, maximum RPM registered and the maximum optical encoder
counter observed.

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

2.4 System Architecture


The 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 for
calculation and processing of results. The master micro-controller is interfaced with the
MATLAB and slave micro-controller through serial port and acquires data from the digital
sensor. The purpose of slave micro-controller is to generate an accurate waveform PWM and
control the motor. The rationale behind using a dedicated micro-controller for generating PWM
is 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 communication
between MATLAB and master micro-controller is bi-directional where as that between slave and
master micro-controller is uni-directional. The PWM duty cycle and the number of cycles are
first sent to the master micro-controller by MATLAB. This data is then transferred by the master
to the slave. The slave then becomes busy in applying the pulse to the motor based on the data
received. The master in the mean time acquires data from the digital sensor and sends it to the
MATLAB via serial port.
M
MATLAB
(Serial Portt)
Motor
Optiical Encoderr
Count Bi-direectional
Asynchronnous Serial
PWM
P PWM Commuunication
Duuty for Duuty & Cycless
Cycles
Asynchronnous
Serial

Board
d Of 
Communicaation NX  Digital R
D RPM 
Educattion PWM
1
1000 Optical Encoder
E
Senso or
Duty & Cyccles Counnt

1 User Operatio
1.3 on Instru
uctions
T followinng are the insstructions foor the user too operate the developed Digital
The D Multti-meter:

1 The GUII starts with a welcome screen


1. s and a picture of thhe motor-sennsor setup.

Welcome Sccreen of MA
ATLAB GUII
2. The user can then first run the diagnostics in order to verify that the system is healthy. Once the
diagnostics is run the system will display the current state of the sensor-actuator system along with
the 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 is
unhealthy the user must rerun the diagnostics. In case of recurrent failure of the system the user must
check 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 on
the requirement the user can choose the level of desired accuracy. Also the user can check the data
logging 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 the
obtained calibration by un-checking the ‘Use Default Calibration’ option. In case of poor calibration
the user should continue with the default calibration.

6. Once the calibration is complete, the user can move on to explore the various control methods
offered by the system. The user can start with the open-loop control. The user can enter the desired
value of rpm in the text box and switch the radio to run option. By running the system in open-loop
the user can understand how good the calibration of the system is. Here also the data logging option
can 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 display
both the current rpm and the error in rpm for this type of control. The user can stop the system by
clicking 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 integral
control applied on the motor.

10. The user can also have look on the actual setup by clicking the video button which will display a
real-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 the
current state of the system.
2. Hardware
The following sections deals with the details of the hardware used to implement the developed control
system.

2.1 List of Components


S. No. Component Quantity
1. 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 1
12. 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 Description


0 Output LCD Enable Pin
4 Input ADC0831 Chip Select Pin
5 Input ADC0831 Clock Pin
6 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 Description


0 Output PWM Pin
7 Input Receiver Pin from Master
9 Output Transmitter Pin to Master

2.3 Hardware Description


Basic Stamp Kit INEX-1000
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 modules
2. 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 motors
10. Pulse generator for 1Hz, 10 Hz, 100 Hz, and 1 kHz
11. RS-232 interface port for communication with COM program
12. Socket for 24-pin BASIC Stamp modules
13. Parallel LCD module with connector and brightness control
14. Piezospeaker
15. 10K potentiometer
16. 2.5" x 7" breadboard with 800 contact points
17. 7.5V DC 1 amp power supply with polarity protection
Source: 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
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 is
configured to comply with the NSC MICROWIRE™ serial data exchange standard for easy interface to
the COPS™ family of processors, and can interface with standard shift registers or µPs. The differential
analog voltage input allows increasing the common-mode rejection and offsetting the analog zero input
voltage value. In addition, the voltage reference input can be adjusted to allow encoding any smaller
analog voltage span to the full 8 bits of resolution.

Key Specifications:

Paramaters / Values ADC0831


Resolution 8 bits
Input Channels 1
Max 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 include


transducer 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:
o Single supply: 3V to 32V
o or dual supplies: ±1.5V to ±16V
Optical Sensor:

The QRB1113/1114 consists of an infrared emitting diode and an NPN silicon phototransistor
mounted side by side on a converging optical axis in a black plastic housing. The phototransistor
responds to radiation from the emitting diode only when a reflective object passes within its field
of 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
IRF540N

Pin 1 – Gate (G)


Pin 2 – Drain (D)
Pin 3 – Source (S)
Features:
Ultra Low-On Resistance
2. 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 mechanical
commutator and brushes.
Ri Rf
12 kΩ 10 kΩ
Motor Interface Circuit
2.4 Circuit Diagrams

Vin

Vss
Vdd

R1 6 8
‐ 7
Master P0 10 kΩ MasterP11
1 8
Q1
+ 4 U1 /CS Vdd
5 2N3904 Rd2
LM358 (a)
1 kΩ
2 7
Vin (+) CLK MasterP12
C1
ADC0831
0.68 MF 3 6
Vin (‐) DO MasterP13
Rd1
FAN
1 kΩ
4 5
GND Vref

Vss Vss

Vss

Vss
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 operational
amplifier is introduced in the circuit. To avoid any such reduction in voltage to the motor the following
circuit was finally implemented.

Motor Interface Circuit

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

Digital Sensor Circuit


The digital sensor was not used with transistor as it was observed that the system doesn’t give
appreciable output once the transistor is used in the circuit.
Master-Slave-Laptop Communication Circuit

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

Complete Circuit Diagram for Developed Speed Control System


2.5 Mechanical Setup

Brushless
Fan

Top View
Encoder Flexi-Glass Adjustable Slot
Wheel Material arrangement using
bolt and nut

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.
3. Software
The following section presents a basic overview of the important commands used and major
programming challenges faced while implementing the system.

3.1 PBASIC Commands


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

1. SERIN - Receive asynchronous serial data (e.g., RS-232 data).


Syntax: SERIN Rpin {\Fpin}, Baudmode, {Plabel,} {Timeout, Tlabel,} [InputData]

2. SEROUT - Transmit asynchronous serial data (e.g., RS-232 data).


Syntax: SEROUT Tpin {\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 is


used to transfer data between the two micro-controllers it was important that no data is lost. This is
ensured 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 program
control 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 around
10 seconds in MATLAB.

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

(iv) Multiple Runs without Hardware Reset: The system has the capability to run continuously without
the need of hardware reset. This has been achieved by looping the system using time out feature such
that only when the data transfer takes place that the programs in the stamps will actually move
forward.
4 Matthemattical Method
4. M s
4
4.1 On-O
Off Contrrol
For On-Off
O contrrol, instantanneous value of
o the variabble is measurred and com mpared to thee
setpooint. If the vaalue is more than the setppoint, drivinng factor is decreased
d andd driving
factorr is increased if the valuue is below thhe setpoint.

OFF
Set--Point
ON

4
4.2 Diffe
ferential Gap
G Controol
It is a type of on--off control, where the drriving factorr is turned onn or off if the value of
the vaariable reachhes at the topp or bottom of the range specified abbout the set-ppoint.

4
4.3 Prop
portional Control
C
In prooportional co
ontrol, the driving
d factorr is proportioonal to the difference
d beetween the
instanntaneous vallue of variabble and the desired
d valuee.
  .

4
4.4 PD Control
C
Derivvative contro
ol measure thhe rate of chhange of erroor and changges the controol signal
accorrdingly. A prroportional and
a derivativve control ussed together can be repreesented as:
  .    .

4
4.5 PID Control
For a PID controll, integral coontrol is usedd in combinaation with PD D control. An
A integral
contrroller calculaates the accuumulation off error and caalculates the area below the curve.

Thus, PID contro


ol can be shoown as:
 
  .  .   . .  

IIn terms of thhe numericaal calculationn the integrall and derivattive can be replaced
r by summation
s aand finite
d
difference.
4.6 PWM control
Pulse-width modulation (PWM) is a very efficient way of providing intermediate amounts of
electrical power between fully on and fully off. A simple power switch with a typical power source
provides full power only, when switched on. The term duty cycle describes the proportion of on time
to the regular interval or period of time; a low duty cycle corresponds to low power, because the
power 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 cycle
of the pulse is changed the average voltage obtained as output varies based on the pulse on time and
pulse off time.

In our system the control of the motor is achieved by varying the duty cycle of the pulse and the
number of cycles for which the pulse is repeated.
5. Implementation
The following section details the algorithms used along with the various MATLAB and Basic Stamp
subroutines 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 the
system. The different algorithms used are as follows:

1. Controls Flowchart
2. Auto Calibration Flowchart
3. Master BS-2 Flowchart
4. Slave BS-2 Flowchart
5. Open-Loop Control Flowchart
6. On-Off Control Flowchart
7. Differential Gap Control Flowchart
8. PID Control Flowchart
5.1.1 Controls Flowchart
5.1.2 Auto Calibration Flowchart

5.1.3 Master BS-2 Flowchart


5.1.4 Slave BS-2 Flowchart
5.1.5 Open-Loop Control Flowchart
5.1.6 On-Off Control Flowchart
5.1.7 Differential Gap Control Flowchart
5.1.8 PID Control Flowchart
5.2 Subroutines

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

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

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

(iii) Video Function – This function search for a connected video device and display the video stream
captured 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 of
the system.
6. Calibration & Testing
The digital sensor was first calibrated in order to determine the optimum distance for best performance
of the system and then the system calibration was carried out. The designed system was then tested for
performance for different controls.

6.1 Digital Sensor Calibration


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

Digital Sensor Voltage Ouput
6
White Surface Black Surface
5

4
Voltage (V)

0
0 0.5 1 1.5 2 2.5

Distance (cm)

Voltage Difference
4
3.5
3
Voltage (V)

2.5
2
1.5
1
0.5
0
0 0.5 1 1.5 2 2.5

Distance (cm)
6.2 Duty Cycle Vs Optical Encoder Count Calibration
The auto calibration feature helped in calibrating the system with almost no effort. Also the calibration
with low and high accuracy was performed in order to check the quality of fit. Both the calibration
showed good results.

6.3 Testing
The following presents the results for different kinds of controls implemented:
6.3.1 Diagnostics
The following diagnostics show that the system is in healthy state with maximum rpm of 5325
and maximum optical encoder count of 71.

6.3.2 Open-Loop Control


The response shows that there is a significant error in the required rpm and the actual rpm in
open-loop control.
6.3.3 On-Off Control
The response shows that though the system is oscillating around the required rpm but the
oscillations are appreciable.

6.3.4 Differential Gap Control


The system response depicts that the switching takes place only when the system moves out of
the specified zone due to which even higher deviations in the output are observed.

6.3.5 Proportional Control


The system shows that though the output becomes very steady but there is significant steady-
state error.
6.3.6 PD Control
The response shows that both the proportional and the derivative control action in acting to
control the system.

6.3.7 PID Control


The response was first evaluated with a 4 cycle/revolution optical encoder. The response showed
significant oscillations. Also the plots are for optical encoder count.
Opto Count Error Opto Count
30 20

10
20
0
10
-10

0 -20
0 200 400 600 0 200 400 600

de Opto Count ie Opto Count


20 100

10 0

0 -100

-10 -200
0 200 400 600 0 200 400 600

The system was finally modified for 8 cycle/revolution optical encoder. The response shows that
the system is oscillating about the required output.
7. Discussion
The system still has a scope for improvement. The following is a list of the features that can either
improve the control performance or can be an added feature:

ƒ The system control doesn’t optimize the gains for achieving good performance. The gains still need to
be 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 very
useful.

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

ƒ The performance of the system is limited by the accuracy of the rpm measurement by the optical
encoder. 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 are
used to actuate the motor.

ƒ The system does not provide statistics regarding the performance of a control. Further analysis of the
response can be carried out in order to obtain settling time, maximum overshoot, steady state error etc
which can quantify the control performance.
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 the
user.
Contribution by each Team Member
Priyanshu Agarwal: Algorithm Coding, overall system integration, coordination among team members
and lab report.

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

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

Jason Lieu: Drawn flow charts of the system and circuit diagrams for lab report.
Bibliography
[1] Process Control, Student Guide, PARALLAX INC., Version 1.0

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

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


Appendix
A. PBASIC Code for Speed Control System 

A.1 Slave Micro‐controller 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 Slave 
TXS        PIN 9             ' TX of Slave 
Fan       PIN 0              ' Pin no of Fan 
 
Duty       VAR   Byte        ' Duty cycle of the PWM 
x         VAR    Byte        ' Counter in the loop 
Cycles    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_Drive 
    No_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_2 
    SERIN RXS, Baud, 2000, No_Data2, [DEC Cycles, WAIT(10)] ' Wait for a BYTE and put it  in Cycles 
  LOOP 
 
Apply_Drive:                             ' Apply drive with a 100msc period 
    FOR x = 1 TO Cycles                      ' Apply for repetitions equal to number of Cycles 
      IF duty > 0 THEN HIGH Fan          ' Check if any HIGH time 
      PAUSE Duty                         ' Apply for amount of high time 
      IF duty < 100 THEN LOW Fan         ' Check if any LOW time 
      PAUSE 100‐Duty                     ' Apply for rest of 100mSec 
    NEXT 
RETURN 
 
A.2 Master Micro‐controller 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         ' Opto‐Reflector 
Opto_Count      VAR     Word      ' Count from opto‐reflective switch 
Duty            VAR     Byte      ' Duty cycle value 0‐255 
Cycles          VAR     Byte      ' No of cycles of a duty cycle 
 
RX        PIN 14                  ' Serial port RX Pin 
TX        PIN 15                  ' Serial port TX Pin 
TXM     PIN      8                'TX pin of Master 
RXM     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 slave 
DO 
    No_Data1: 
    SERIN RX, Baud, 2000, No_Data1,[DEC Duty, WAIT(10)] ' Wait for a BYTE and put it in Duty 
    SERIN RX, Baud, 2000, No_Data1,[DEC Cycles, WAIT(10)] ' Wait for a BYTE and put it in Cycles 
    SEROUT TXM, Baud, [DEC Duty , 10]     ' Transmit Duty to Slave uController 
    SEROUT TXM, Baud, [DEC Cycles , 10]   ' Transmit Duty To Slave uController 
    COUNT Opto_SW,100,opto_count          ' Count number of pulses from sensor 
    SEROUT TX, Baud, [DEC opto_count, 10]  ' Transmit count to MATLAB via serial port 
LOOP 
 
B. MATLAB GUI Code for Speed Control System 
function varargout = Motor_Control(varargin)
% MOTOR_CONTROL M-file for Motor_Control.fig
gui_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 structure
guidata(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 devices
if(~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)
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 = 2
Kd = 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
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 Equation
DutyCycle = 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<0) % If Duty Cycle comes out to
be negative
DutyCycle = 0; % reduce to zero
end

fprintf(sPort,'%d\n',round(DutyCycle)); % Send Duty Cycle to


Master BS2
fprintf(sPort,'%d\n',Cycles); % Send No of PWM Cycles
to Master BS2
Opto_Count = fscanf(sPort,'%d\n'); % Receive Optical Encoder
Count from Master BS2
Opto_Counter = [Opto_Counter Opto_Count];
e_Opto_Count = Req_Opto_Count-Opto_Count; % Calculate error in
actual and required count
E_Opto_Count = [E_Opto_Count e_Opto_Count];
if(control_type == 0) %Open Loop Control
subplot(1,2,1,'Position',[0.2 0.05 0.35 0.8],'FontSize',10);
box on;
plot(I,Opto_Counter*Scale,'-b','Linewi',1)
hold on;
plot(I,Req_Opto_Count*Scale*ones(size(I)),'-r','Linewi',1);
title('RPM Plot');
grid on
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
Control
if(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)<20)
Cycles = 2;
else
Cycles = 10;
end
subplot(1,2,1,'Position',[0.2 0.05 0.35 0.8],'FontSize',10);
plot(I,Opto_Counter*Scale,'-b','Linewi',1)
hold on
plot(I,Req_Opto_Count*Scale*ones(size(I)),'-r','Linewi',1);
title('RPM Plot');
grid on
subplot(1,2,2,'Position',[0.60 0.05 0.35 0.8],'FontSize',10);
plot(I,E_Opto_Count*Scale,'-r','Linewi',1);
title('RPM Error Plot');
grid on
hold on
pause(0.001)
elseif(control_type == 2) %P, PD & PID Control
de_Opto_Count = (e_Opto_Count-E_Opto_Count(i-1))/e_Time;
%Caculating derivative control action
DE_Opto_Count = [DE_Opto_Count de_Opto_Count];
ie_Opto_Count = trapz(E_Opto_Count)*e_Time;
%Calculating integral control action
IE_Opto_Count = [IE_Opto_Count ie_Opto_Count];
New_Opto_Count =
Kp*e_Opto_Count+Kd*de_Opto_Count+Ki*ie_Opto_Count; % Calculate new
optical encoder count
if((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)
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 on
subplot(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 on
hold 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<0)
New_Opto_Count = 0;
end
DutyCycle = P1*New_Opto_Count^2 + P2*New_Opto_Count + P3;
% Actual Calibration Equation
end
if (get(handles.radio_stop,'Value')==1)
set(handles.text_message,'String','Stopping!');
drawnow;
status = 0;
fprintf(sPort,'%d\n',0); % Send 0 Duty Cycle to Master BS2
to stop motor
fprintf(sPort,'%d\n',0); % Send 0 No of PWM Cycles to Master
BS2 to stop motor
end
end
set(handles.text_message,'String','Stopped!');

% --- Executes on button press in button_calibrate.


function button_calibrate_Callback(hObject, eventdata, handles)
global sPort Cycles Scale P1 P2 P3;
syms z;
Duty_Cycle = [];
Opto_Counter = [];
Cycles = 10;
subplot(1,1,1,'Position',[0.2 0.06 0.75 0.8],'FontSize',10);
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 the
calibration 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
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)


% --- 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');
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);

You might also like