You are on page 1of 321

Instrumentation and

Microcontrollers Using
Automatic Code
Generation
Using and Applying
Microcontrollers for
the Rest of Us!

Marc E Herniter

2013 Marc E. Herniter, Rose-Hulman Institute of Technology, and The MathWorks. This document may not
be reproduced without the express written consent of Marc E. Herniter.

i
Table of Contents
I.

Opening the World of Microcontrollers ........................................................................................................ 1


A.

Introduction ............................................................................................................................................. 1

B.

Setup ...................................................................................................................................................... 1
1.

MATLAB/Simulink Setup ..................................................................................................................... 1

2.

MATLAB Complier Setup .................................................................................................................... 8

3.

Installing the RHIT KL25Z Library ........................................................................................................ 8

4.

Installing Freescale FreeMASTER..................................................................................................... 11

5.

Installing Windows Device Drivers ..................................................................................................... 11

6.

Updating the FRDM-KL25Z Firmware ............................................................................................... 16

7.

FRDM-KL25Z Electrical Setup ........................................................................................................... 19

C.

II.

Lab Procedure ................................................................................................................................... 22

1.

Flip-Flop LEDs................................................................................................................................... 22

2.

Manually Setting up a KL25Z Simulink Model .................................................................................... 30

3.

Using the MathWorks KL25Z Library ................................................................................................. 41

4.

Driving a Single Off-Board LED ......................................................................................................... 43

Counters, Digital Input, Stateflow, Truth Tables ........................................................................................ 50


A.

Digital Input Block ................................................................................................................................. 50

B.

Counters with Basic Logic Blocks ......................................................................................................... 54


1.

Ring Counter ..................................................................................................................................... 54

2.

The Digital Memory Block .................................................................................................................. 57

C.

Using a Stateflow Chart to Implement State Diagrams ...................................................................... 59

D.

Debugging Tools ............................................................................................................................... 68

1.

Overrun Detection ............................................................................................................................. 68

2.

Using Freescale FreeMASTER ......................................................................................................... 69

3.

External Mode ................................................................................................................................... 77

E.

Using Truth Tables to Implement Logic ................................................................................................. 84

III.

Analog Input, Sensors, Subsystems, and Lookup Tables...................................................................... 92

A.

Analog Input Block ................................................................................................................................ 92


1.

Data Types ........................................................................................................................................ 95

2.

Analog Voltmeter ............................................................................................................................. 104

3.

Sampling Time and Triggered Subsystems ..................................................................................... 106

B.

Temperature Sensor ........................................................................................................................... 109


1.

Triggered Subsystems..................................................................................................................... 113


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

ii
2.
C.

Temperature Meter .......................................................................................................................... 119


Lookup Tables ................................................................................................................................. 121

1.

Stateflow Charts with Events ........................................................................................................... 121

2.

Integrators, Timing, and Signal Generators ..................................................................................... 123

3.

Tuning Variables with FreeMASTER ............................................................................................... 127

4.

Tuning Variables in External Mode .................................................................................................. 134

5.

Lookup Tables ................................................................................................................................. 144

6.

Variable Speed Ring Counter .......................................................................................................... 146

IV.

Analog Output (PWM and DAC).......................................................................................................... 148

A.

KL25Z DAC Output ............................................................................................................................. 148

B.

Pulse-Width Modulation (PWM) .......................................................................................................... 153


1.

FRDM-KL25Z PWM Output Block ................................................................................................... 155

2.

Low-Pass Filter................................................................................................................................ 157

3.

DC Output ....................................................................................................................................... 158

4.

Sine Wave Output ........................................................................................................................... 159

C.

Variable Brightness Light Bulb ......................................................................................................... 161

D.

Variable Speed Motor ...................................................................................................................... 165

V.

Serial Communication ............................................................................................................................ 166


A.

Introduction ......................................................................................................................................... 166

B.

Useful MATLAB Commands ............................................................................................................... 169

C.

Displaying Text on and LCD Display ............................................................................................... 172

1.

Displaying a Single Line of Text ...................................................................................................... 172

2.

Displaying Text Based on User Selection ........................................................................................ 181

3.

Formatted Text Output .................................................................................................................... 192

VI.

Intelligent Sensors .............................................................................................................................. 199

A.

What is I2C? ........................................................................................................................................ 199

B.

TC74, TMP101, and TMP102 Temperature Sensors .......................................................................... 200


1.

SparkFun BMP085/BMP180 Pressure and Temperature Sensors................................................... 204

2.

Real-Time Clock .............................................................................................................................. 209

3.

KL25Z On-Board Sensors ............................................................................................................... 210

VII.

Memory ............................................................................................................................................... 211

A.

Array Memory ..................................................................................................................................... 211

B.

Min Max Memory ................................................................................................................................ 219

C.

Stateflow Memory and the Switch Case MATLAB Command .......................................................... 223

D.

Multiple Sensor Projects .................................................................................................................. 229


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

iii
VIII.

Collecting Data 1................................................................................................................................. 230

A.

Serial Communication with Simulink ................................................................................................... 230

B.

Serial Communication with MATLAB................................................................................................... 237

C.

Data Collection Simulink Model ....................................................................................................... 239

D.

Data Collection MATLAB Script ....................................................................................................... 246

IX.

Collecting Data 2................................................................................................................................. 250

A.

The SPI BUS ...................................................................................................................................... 250

B.

Data Collection Model ......................................................................................................................... 252

X.

Motors .................................................................................................................................................... 264


A.

DC Motor ............................................................................................................................................ 264


1.

Fan Duty Cycle Response ............................................................................................................... 268

B.

Stepper Motor ..................................................................................................................................... 269

C.

Servo Motor ..................................................................................................................................... 283

XI.

Appendices ......................................................................................................................................... 287

A.

SparkFun Serial LCD Module Datasheet ............................................................................................ 287

B.

SUNON DC Cooling Fan..................................................................................................................... 291

C.

PN2222A datasheet ........................................................................................................................ 292

D.

Datasheet 3 ..................................................................................................................................... 296

E.

Texas Instruments L293 H-Bridge ....................................................................................................... 300

XII.

Bibliography ........................................................................................................................................ 303

XIII.

Index ................................................................................................................................................... 304

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

iv
List of Demonstrations
Demo I.1: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate. .............................................. 29
Demo I.2: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate. .............................................. 40
Demo I.3: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate using the MathWorks Digital
Output block. ................................................................................................................................................... 43
Demo I.4: Show the off-board LED flashing at a 1 Hz rate. .............................................................................. 49
Demo II.1: Show the operation of this circuit to your instructor. When the switch is closed the LED should be
off. When the switch is open, the LED should be on. ....................................................................................... 53
Demo II.2: Show the operation of switch/digital input/digital output model with a 0.1 second fixed-time step.
When the switch is closed, the LED should be off. When the switch is open, the LED should be on................ 54
Demo II.3: Wire up the eight LEDs to your chosen pins and demo the ring counter. ........................................ 57
Demo II.4: Demo the ring counter using a counter implemented with the Memory block. ................................ 58
Demo II.5: Demo the ring counter using a counter implemented with the Stateflow chart. ............................... 67
Demo II.6: Demo the up-down ring counter using a counter implemented with the Stateflow chart. ................. 67
Demo II.7: Demonstrate that your overrun detection works by reducing the fixed-time step until the step is too
small for the model to run in real-time and the overrun detection light comes on. What is the value of your fixed
time step? After the demo, make sure that you set the fixed-step size back to 0.5 seconds. ........................... 69
Demo II.8: Demonstrate the FreeMASTER tool displaying the value of the Pulse_Gen and Counter_Value
signals. ............................................................................................................................................................ 77
Demo II.9: Demo your model using External Mode. Show the operation of the Display block, the Scope Block,
and the Stateflow chart animation. ................................................................................................................... 84
Demo II.10: Demo the up-down ring counter using a counter implemented with the Stateflow chart and a truth
table as a decoder. .......................................................................................................................................... 90
Demo III.1: Show the operation of both types of analog input blocks with FreeMASTER. ................................ 95
Demo III.2: Demonstrate the working linear analog voltmeter. ....................................................................... 105
Demo III.3: Demonstrate the working linear analog voltmeter with different sampling rates. .......................... 109
Demo III.4: Demonstrate the FreeMASTER tool displaying the three signals from the thermistor sensor circuit.
...................................................................................................................................................................... 118
Demo III.5: Demonstrate the working linear temperature meter. .................................................................... 120

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

v
Demo III.6: Demonstrate that the up-down counter can vary between a counting frequency of 1 and 10 Hz by
changing the value of the constant. ............................................................................................................... 126
Demo III.7: Demonstrate the operation of the variable speed counter using FreeMASTER to change the speed
of the counter and magnitude of the ramp in real-time. .................................................................................. 134
Demo III.8: Demonstrate the operation of the variable speed counter using External Mode to change the speed
of the counter and magnitude of the ramp in real-time. Show plots on the scope and show the animation of the
Stateflow charts. ............................................................................................................................................ 143
Demo III.9: Demonstrate the operation of the variable-speed up-down counter. ............................................ 147
Demo IV.1: Demo the DAC output for a 10 Hz sine wave. ............................................................................. 153
Demo IV.2: Demonstrate the PWM output of the FRDM-KL25Z on the oscilloscope using the Repeating
Sequence Stair input. .................................................................................................................................... 157
Demo IV.3: Demonstrate the PWM and DC outputs of the FRDM-KL25Z on the oscilloscope. ...................... 159
Demo IV.4: Demonstrate the PWM and sine wave output of the FRDM-KL25Z on the oscilloscope. ............. 160
Demo IV.5: Demonstrate that your PWM output can directly control the brightness of the light bulb by having
the brightness follow a 1 Hz sine wave. ......................................................................................................... 164
Demo IV.6: Demonstrate that you can control the speed of your motor using the PWM output of the FRDMKL25Z. You may need to change the driver transistor and the base resistor depending on the current
requirements of your motor. Make sure that you use a supply bypass capacitor for the 5 V and 3.3 V supplies.
Applying a switching voltage to a motor can generate a lot of noise. ............................................................. 165
Demo V.1: Display the text, This is a test! on your LCD screen at a fixed step size of 1 second. ................. 174
Demo V.2: Display the text, This is a test! on your LCD screen at a fixed step size of 0.01 second and using a
triggered subsystem to update the text screen once every second. (You should still have an overrun.) ........ 176
Demo V.3: Display the text, This is a test! on your LCD screen at a fixed model step size of 0.01 second using
an atomic subsystem to update the text screen once every second. Show that there is no longer an overrun.
...................................................................................................................................................................... 180
Demo V.4: Demo the working LCD display. The text message should change after the pushbutton is pressed
and cycle through the three text messages.................................................................................................... 192
Demo V.5: Demo the sprint MATLAB Function block displaying the text string, The value of pi is 3.142. .... 198
Demo VI.1: Demo the TC74/TMP101/TMP102 temperature sensor with the temperature being displayed on the
LCD screen. .................................................................................................................................................. 204
Demo VI.2: Demo of the BMP085/BMP180 sensor by displaying the temperature and pressure on the LCD
screen. The values should update once every second................................................................................... 208
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

vi
Demo VII.1: Demonstrate the working memory block with 10 elements. ........................................................ 218
Demo VII.2: Demo the operation of the BMP085/BMP180 with the Min_Max_Memory block and the LCD
displaying the following .................................................................................................................................. 222
Demo VII.3: Demo the BMP085/BMP180 with the Mode Select and Function Select pushbuttons. ............... 229
Demo VIII.1: Now that we have a model that outputs a text string to a UART, we can test that model using a
serial communication program on your computer. Connect the SparkFun FTDI Basic USB port to a USB port
on your computer. Run a communication program (such as SecureCRT) to verify that the model is sending out
text and that your hardware is correct. The LCD display and serial communication program should display a
new line of text every time you press the push button. Note that your communication program will have to
specify the port used by the FTDI (COM18 in my case) and the same BAUD rate (9600).You should see
something similar to that shown below: ......................................................................................................... 236
Demo VIII.2: Demonstrate the operation of sending serial text with the controller and receiving the text with
MATLAB. ....................................................................................................................................................... 239
Demo VIII.3: Demonstrate the operation of your data collection routine. Collect sensor data every 10 seconds,
store a total of 10 rows of data, transfer the data to MATLAB, show the contents of the data array, and then
plot the temperature data versus time............................................................................................................ 249
Demo IX.1: Demonstrate the operation of your Data collection model: .......................................................... 262
Demo X.1: Show that the fan speed can be controlled by changing the duty cycle. Determine: (1) The minimum
duty cycle to start the fan when the fan initially is not rotating. (2) The value of duty cycle where the fan stops
after it was initially rotating. ............................................................................................................................ 268
Demo X.2: Show the working stepper motor. Use external mode so that you can vary the pulse frequency by
changing the pulse generator frequency. Show that you can vary the pulse generator period from 4 ms to 1 s,
and the motor responds appropriately. You will need a fixed time step of 1 ms or smaller. ............................ 280
Demo X.3: Show the working stepper motor with a variable frequency between 0 and 12.5 revolutions per
second. The speed should depend linearly on a potentiometer read with an analog input. ............................ 281
Demo X.4: Demo the stepper motor with variable speed and direction change. A pushbutton should change the
motor direction. The variable speed control should work in any direction. The motor should change direction
when the pushbutton is pressed. The direction should remain unchanged when the pushbutton is released. 283
Demo X.5: Demo the stepper motor with variable speed, direction change, and speed ramping when the
direction pushbutton is pressed. A pushbutton should change the motor direction. When the direction is
changed, the speed should be set to zero and then ramp up linearly to the speed set by the analog input in one
second. The variable speed control should work in any direction. .................................................................. 283
Demo X.6: Show that you can control the motor position using the analog input to position the motor between 0
and 180 degrees. Display the value of the angle on the LCD display............................................................. 285

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

vii
List of Exercises
Exercise I.1: Change the model so that the blue LED flashes at a 2 Hz rate. Demo to your instructor. ............ 29
Exercise I.2: Change the model so that the blue LED flashes at a 10 Hz rate. Demo to your instructor. .......... 29
Exercise I.3: Change the model so that the red LED flashes at a 2 Hz rate. Demo to your instructor............... 29
Exercise I.4: Change the model so that the LED switches back and forth between flashing at a 1 HZ rate and a
2 Hz rate. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library, use
a part called Switch. ....................................................................................................................................... 30
Exercise I.5: Change the model so that the LED switches back and forth between a red LED flashing at a 1 HZ
rate and a Green LED flashing at a 2 Hz rate. When a specific color LED is not flashing, it should be off all of
the time. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library, use
a part called Switch. You may need a Rate Transition block to solve this problem. ........................................ 30
Exercise I.6: Create a model that switches the LED between Green and Red at a 1 Hz rate. When the green
LED is on, the red LED should be off and vice versa. There never should be a time when all of the LEDs are
off. ................................................................................................................................................................... 30
Exercise I.7: Change the model so that the blue LED flashes at a 2 Hz rate. Demo to your instructor. ............ 40
Exercise I.8: Change the model so that the blue LED flashes at a 10 Hz rate. Demo to your instructor. .......... 40
Exercise I.9: Change the model so that the red LED flashes at a 2 Hz rate. Demo to your instructor............... 40
Exercise I.10: Change the model so that the LED switches back and forth between flashing at a 1 HZ rate and
a 2 Hz rate. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library,
use a part called Switch. You may need a Rate Transition block to solve this problem. .................................. 40
Exercise I.11: Change the model so that the LED switches back and forth between the red LED flashing at a 1
HZ rate and the Green LED flashing at a 2 Hz rate. When a specific color LED is not flashing and off, it should
be off all of the time. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks
library, use a part called Switch. Exercise I.12: Create a model that switches the LED between Green and Red
at a 2 Hz rate. When the green LED is on, the red LED should be off and vice versa. There never should be a
time when all of the LEDs are off. You may need a Rate Transition block to solve this problem. ..................... 40
Exercise I.13: Using the RGB LED block, create a model that flashes the LED on and off at a 1 Hz rate. When
on, the LED color should be purple. ................................................................................................................. 43
Exercise I.14: Using three Counter Limited blocks, three Rate Transition blocks, and the RGB LED block,
create a model that steps the red LED from 0 to 255 in 0.01 second steps, the green LED from 0 to 255 in 0.02
second steps, and the blue LED from 0 to 255 in 0.03 second steps. .............................................................. 43
Exercise II.1: Create a model that illuminates the LEDs in the sequence shown below: .................................. 57

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

viii
Exercise II.2: Using a digital input, modify the previous model so that the counter holds its value (stops
counting) when the switch is closed. Note that a switch is required for this exercise. ....................................... 58
Exercise II.3: Using a digital input, modify the ring counter model so that the counter counts up when the switch
is open and counts down when the switch is closed. The counter is not allowed to jump or skip a count when
the switch is pressed. ...................................................................................................................................... 59
Exercise II.4: Using Stateflow and a digital input, create a ring counter that shifts to the right when a switch is
open and shifts to the left when the switch is closed. ....................................................................................... 68
Exercise II.5: Using Stateflow and a second digital input, modify your solution to Exercise II.4 by adding a
switch that will hold the count at its present value. The first switch will still determine the direction. Note that
&& is the logical AND in Stateflow syntax....................................................................................................... 68
Exercise II.6: Modify the Truth Table from Demo II.10 to light up the odd numbered LEDs when the count is
odd and light up the even numbered LEDs when the count is even. ................................................................ 91
Exercise II.7: Modify the Truth Table from Demo II.10 so that two adjacent LEDs travel up and down the LED
display. Two LEDs must be illuminated at all times.......................................................................................... 91
Exercise III.1: Determine the decimal value of the following bit string (it is 32 bits in length.)
10011100111011100110111000000011. Calculate the value of this string assuming the following data types:
(a) Uint32 (magnitude), (b) Int32 (2s complement), (c) sign and magnitude, (d) single precision floating point.
Optional - Create an m-file that displays all four results in a message box..................................................... 102
Exercise III.2: Determine the decimal value of the following bit string (it is 32 bits in length.)
01000000111010000110100000000011. Calculate the value of this string assuming the following data types:
(a) Uint32 (magnitude), (b) Int32 (2s complement), (c) sign and magnitude, (d) single precision floating point.
Optional - Create an m-file that displays all four results in a message box..................................................... 102
Exercise III.3: Modify the linear voltmeter of Demo III.2 to use a base-2 logarithmic scale. That is, the next LED
should only light up when the size of the signal doubles. This makes the bar graph very sensitive for small
signals and less sensitive for larger signals. Hint: Multiply the analog signal by 255 and remember your factors
of two (1, 2, 4, 8 ,16, etc) ........................................................................................................................... 105
Exercise III.4: Modify the temperature meter so that when it zeros out, 4 LEDs are illuminated. Then when the
sensor is warmed up to the maximum temperature, all 8 LEDs are illuminated. If the sensor becomes colder
than the reference, less than 4 LEDs are illuminated. This is essentially a sensor that indicates temperatures
both above and below the reference point. .................................................................................................... 120
Exercise III.5: Modify the temperature meter of Demo III.5 to use a pushbutton to sample the temperature
rather than the step source. This will allow the user to zero the meter at any time, rather than zeroing the meter
automatically at power-up. ............................................................................................................................. 121
Exercise III.6: Modify the temperature meter of Demo III.5 to use a pushbutton and the step source to sample
the temperature. This will automatically zero the meter at power up as well as allow the user to zero the meter
at any time. .................................................................................................................................................... 121

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

ix
Exercise III.7: Create a model that switches between three modes of operation for the up-down counter. When
you push and release a pushbutton, the mode of operation changes. The three modes are: (1) constant 1 Hz
frequency, (2) constant 5 Hz Frequency, and (3) Variable frequency between 1 and 10 Hz based on an analog
input. ............................................................................................................................................................. 147
Exercise IV.1: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 10 Hz, (2) a sine wave at 100 Hz, (3) a 10 Hz saw tooth, and (4) a 10 Hz triangle wave. All waveforms
have 1 V in amplitude. Demo with an oscilloscope monitoring the output. Use the Analog Output block to
generate the waveforms. ............................................................................................................................... 153
Exercise IV.2: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 10 Hz, (2) a sine wave at 100 Hz, (3) a 10 Hz saw tooth, and (4) a 10 Hz triangle wave. All waveforms
have 1 V in amplitude. Demo with an oscilloscope monitoring the output. Use the PWM Output block to
generate the waveforms. ............................................................................................................................... 160
Exercise IV.3: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 1 Hz, (2) a sine wave at 0.5 Hz, (3) a 1 Hz ramp, and (4) a 1 Hz triangle wave. Drive the light bulb with
all of these waveforms. .................................................................................................................................. 164
Exercise V.1: Using a switch, have the LCD automatically switch at a 1 Hz rate between displaying the text My
name is xxxx. and This class is fun! You can use a switch to select between text strings. Note that the text
strings must be the same length, so you may need to pad one of the strings with spaces. ............................ 176
Exercise V.2: Using a switch, have the LCD automatically switch at a 1 Hz rate between displaying the text My
name is xxxx. and This class is fun! Note that the text strings must be the same length, so you may need to
pad one of the strings with spaces. ................................................................................................................ 181
Exercise V.3: For the model of Demo V.4, if you cycle the power, you will notice that the LCD displays a blank
screen until the user presses the pushbutton. This could be confusing to the user. Modify the model so that at
power up, the model will wait 2 seconds and then display the text, 'Press the pushbutton to start. ' When the
user presses the pushbutton, it will display the first text message and then cycle through the three text
messages when the button is pressed. The message 'Press the push button to start.' will never be seen again
unless the power is cycled. ............................................................................................................................ 192
Exercise V.4: Create a model that switches between three functions when a pushbutton is pressed. The
functions are displayed on the LEDs we used in previous labs. The functions are a ring counter, an up/down
counter, and an analog voltmeter. You should have models that solved these problems before. In addition to
this requirement, the LCD should display the text, Ring Counter, Up-Down Counter, or Analog Voltmeter
as appropriate. .............................................................................................................................................. 192
Exercise V.5: Use the LCD display to create a bar-graph display representing an analog input voltage. An input
of 0 should display 0 bars and an input of 3.3 V should display 16 bars. Use a potentiometer to supply a
variable input voltage to one of the FRDM-KL25Z analog input pins. On the top line of the LCD display, show
the text Bar Graph with appropriate spacing. On the second line of the LCD display, show the bar graph. To
display a square, you can send an ASCII code of 6. To display a blank use an ACSII code of 32. As an
example, the array Bar = [6 6 32 32 32 32 32 32 32 32 32 32 32 32 32 32]'; will display 2 bars and 14 blanks.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

x
You may also want to use the Simulink block Vector Concatenate to concatenate strings. Examples are
shown below: ................................................................................................................................................. 192
Exercise V.6: Create a model that increments a counter from 1 to 10. This value is multiplied by the constant
pi. Both numbers are passed to a modified sprintf function. The sprint function generates a text string that
outputs the following, The value of x*pi is y. where x is the counter, and y is the value of the constant times pi.
Example outputs are: ..................................................................................................................................... 198
Exercise V.7: Modify the bar graph of Exercise V.5 so that the first line on the LCD displays the text Bar Graph
xxx.x% where xxx.x is the numerical value of the percent, between 0 and 100. The second line of the LCD
should still display the bar graph as in Exercise V.5. You will need to use the %c format string to display a %
sign on the LCD screen. ................................................................................................................................ 198
Exercise V.8: The LCD splash screen is the text that the LCD displays at power-up. The text is displayed for
half a second and then the LCD goes blank. The datasheet for the LCD gives the procedure for changing the
LCD splash screen. This text string should only be sent once. Create a model that sends one text string to the
LCD screen such that it changes the splash screen. Change the splash screen so that it displays your name. A
data sheet for the LCD screen can be found in the appendix on page 287. ................................................... 198
Exercise VI.1: Demonstrate the difference between when the TMP101 is used with 9-bit resolution and 12-bit
resolution. ...................................................................................................................................................... 204
Exercise VI.2: Create a model that reads the temperature twice with two different temperature sensors. The
model displays both temperatures on the LCD screen for comparison. The display should indicate which
temperature is for which sensor. Note that if you use the TMP101 or TMP102 and you change the address by
rewiring the address pin, you will need to cycle the power on the board before the sensor recognizes the
change. ......................................................................................................................................................... 209
Exercise VI.3: Create a model that programs the RTC with the current date and time. After running this model
once, do not run it again as it will reset the date and time to the values you specified the last time you set the
clock. Note that you need to specify the current time and date in the block parameters. ............................... 209
Exercise VI.4: Create a model that displays the date and time in the format shown below. The display time
should update once a second. You might need to use the %c format string to display a / on the LCD display.
...................................................................................................................................................................... 209
Exercise VI.5: Create a model that reads the three I2C sensors we have studied and flips the display between
the information received from each. The LCD display should change screens once a second. You might need
to use the %c format string to display a / on the LCD display. The alternating screens are shown below: ... 209
Exercise VI.6: Using the on-board accelerometer, display the acceleration of all three axes on the LCD with at
least 2 decimal places of accuracy. An example output could be: .................................................................. 210
Exercise VI.7: Using the on-board Touch Sensor Interface (TSI), display the value returned by the sensor. An
example output could be................................................................................................................................ 210
Exercise VI.8: Create a model that uses a pushbutton to display one of 4 items. The output should change
when the pushbutton is pressed. The output should remain unchanged when the pushbutton is released. The
information displayed should be: ................................................................................................................... 210
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

xi
Exercise VII.1: Determine the maximum size of the ring memory that you can use on the Freescale FRDMKL25Z. When the memory is too large, you will get an error stating that you had a RAM overflow: ............... 218
Exercise VII.2: In Demo VII.1 we are saving data as double-precision floating point data types that use 8 bytes
of data per number stored. Since each number has at most 2 decimal places of accuracy, we could multiply the
numbers by 100 and then save the data as 16-bit unsigned integer data types (assuming that the temperature
is never negative). This would allow us to save 4 times as many data points in the available memory. Rewrite
the model to save the data as 16-bit unsigned integers. The MATLAB command uint16(x) converts x to an
unsigned integer and saves it as an unsigned16-bit value using two bytes of memory. ................................. 219
Exercise VII.3: Modify the Min_Max_Memory block so that it has a reset input. When the reset occurs, the
minimum and maximum values are reset to the current value. For testing, use a pushbutton to reset the values.
...................................................................................................................................................................... 223
Exercise VII.4: Modify the model created in Demo VII.3 to implement the functionality below:....................... 229
Exercise VII.5: Modify the model created in Demo VII.3 to implement the functionality below:....................... 229
Exercise VIII.1: Create a Simulink model and MATLAB script that accomplish the following task. The Simulink
model collects time, temperature and pressure data the same as in Demo VIII.3. When the memory is full with
10 rows of collected data, the data is automatically transmitted on the serial port. After transmitting the data,
the Simulink model collects another 10 rows of data, which is again automatically transmitted when available.
The MATLAB script waits for the data and automatically concatenates the received data to the data array
without user intervention. After receiving the data and appending it to the data array, the script waits for more
data to be sent. This process should continue until the script collects 100 rows of data, all of which are saved in
a single array. The MATLAB script should output a status message each time it receives data so that we can
monitor its progress. When done, the script will plot the temperature and pressure data. An example would be:
...................................................................................................................................................................... 249
Exercise IX.1: Write a MATLAB script that reads your data and generates a figure containing two plots with the
following information: ..................................................................................................................................... 262
Exercise IX.2: Modify your data collection Simulink model to use the Card Detect (CD) pin of the MicroSD
breakout board. Your model must enforce the logic listed below: .................................................................. 263
Exercise IX.3: Create a model that has the same functionality as the model of Exercise IX.2 with the addition
that LCD toggles every two seconds between displaying the time and date or the temperature and pressure.
This is a good opportunity to use the Simulink IF and IF Action Subsystem blocks. These blocks are located
in the Ports & Subsystems library. For both displays, the LCD should still display if data collection is enabled or
not. ................................................................................................................................................................ 263
Exercise X.1: Create a fan controller that turns the fan off for temperatures less than 70 F and full on for
temperatures greater than 80 F. Between temperatures of 70 F and 80 F, the fan speed varies linearly.
Use the LCD to display the duty cycle and temperature and use one of the temperature sensors covered in a
previous lab. .................................................................................................................................................. 268

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

xii
Exercise X.2: Create a two-speed fan controller that implements the following algorithm. When the temperature
is greater than or equal to 75 F, the fan spins at 50% duty cycle. If the fan is on at 50% duty cycle, the fan
cannot turn off until the temperature is less than or equal to 70 F. When the temperature is greater than or
equal to 80 F, the fan spins at 100% duty cycle. If the fan is on at 100% duty cycle, it will not slow down to
50% duty cycle until the temperature is less than or equal to 75 F. .............................................................. 269
Exercise X.3: Add an LCD display to the stepper motor model. The LCD will display the direction (CW or CCW)
and the speed in rpm. Example text would be Direction: CCW
Speed: 193 rpm ........................ 283
Exercise X.4: Create a model that slowly rotates the motor from 0 to 180 degrees (or whatever a safe
maximum is for your hardware), and then slowly rotates it back to zero. The motor will continually rotate back
and forth. The speed of rotation should be constant. ..................................................................................... 285
Exercise X.5: Create a model that rotates the motor from 0 to 180 degrees (or whatever a safe maximum is for
your hardware), and then rotates it back to zero. The motor will continually rotate back and forth. The speed of
rotation should be determined by an analog input. The speed to rotate between 0 and 180 degree should vary
between 1 and 10 seconds as determined by an analog input. The speed to rotate back from 180 to 0 degrees
should be the same as the speed to rotate from 0 to 180 degrees. If the analog input is constant, the speed
should be constant. ....................................................................................................................................... 285
Exercise X.6: Create a model that rotates the motor from 0 to 180 degrees (or whatever a safe maximum is for
your hardware), and then rotates it back to zero. The motor will continually rotate back and forth. The speed of
rotation should be determined by an analog input. The speed to rotate between 0 and 180 degree should vary
between 1 and 10 seconds as determined by an analog input. The speed to rotate back from 180 to 0 degrees
should be the same as the speed to rotate from 0 to 180 degrees. Make the speed follow a sine wave profile
so that the speed increases in the middle of the rotation and slows near the ends of the rotation. (You can use
a look up table for this, a MATLAB embedded function, or a mathematical function block. ............................ 285

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

I.

Opening the World of Microcontrollers

Lab I
Opening the World of Microcontrollers
Hello World!

A.

Introduction

In this lab we will show how to program the Freescale FRDM-KL25Z using automatic code generation facilities
provided by The MathWorks Simulink. Instead of learning how to program in C, how to address hardware I/O
ports of the FRDM-KL25Z target, and how to download and run the program, we will just draw a block diagram
(referred to as a model) in Simulink and tell Simulink to run the model on the hardware target. The translation
of the model to C, compiling the C code, downloading the program, and then running the program are all
transparent to us. In higher level courses, you may explore how the process of automatic code generation
works. We however, will concentrate on creating some rather complex models to accomplish non-trivial tasks
with microcontrollers and leave the under-the-hood workings of automatic code generation to the higher level
courses.
In order to accomplish this task, we must do a few preliminary tasks: (1) Install the FRDM-KL25Z software
package within MATLAB/Simulink, (2) setup the compilers within MATLAB/Simulink, (3) Install the RHIT
FRDM-KL25Z libraries, (4) install the Freescale FreeMASTER software tool, (5) install the Windows device
drivers, (6) update the firmware on our FRDM-KL25Z board, and (7) examine the FRDM-KL25Z datasheet(s)
for pin connections and electrical setup.
Many of these tasks may already have been setup on your computer. These tasks are
documented here for new installations.

B.

Setup

1.
MATLAB/Simulink Setup
For this setup, we will assume that you are using the 64-bit version MATLAB Version 2014b or higher. The first
step is to install the FRDM-KL25Z Target toolbox, but before we do this, we must determine if the FRDMKL25Z target toolbox has already been installed. From the MATLAB command prompt, type 1 targetinstaller:

Note that the targetinstaller command will be removed from future versions, and may generate a warning or error
message.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Instrumentation and Microcontrollers Using Automatic Code Generation

You can also click here and then select


Get Hardware Support Packages.

The Support Package Installer should open:

Click here to see which packages


are installed.

Select the Uninstall option and then select Next to see which hardware packages, if any, are installed on your
computer:

This shows that the FRDM-KL25Z


package is installed.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

If your window shows that the Freescale Kinetis Microcontrollers support package is installed, then you are
done. Click the Cancel button and skip to section I.B.2 on page 8. (Do not uninstall the support package!) If
the Freescale Kinetis Microcontrollers support package is not listed, then you will need to install the support
package. (Important Note - If you receive an error while installing the KL25Z package, you may need to
temporarily turn off your firewall and virus software while you install the package.) Click the Back
button to return to the previous screen and then select the Install from Internet option:

Option selected.

Click the Next


button.

After clicking the Next button, the Support Package Installer will list all of the available support packages:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Instrumentation and Microcontrollers Using Automatic Code Generation

Select the Freescale Kinetis


Microcontrollers package.

Select Freescale Kinetis Microcontrollers package and click the Next button:

This dialog box informs you that you will also need to install the support package for ARM Cortex-M processors
if it is not yet installed. Click the OK button to continue:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

If you do not have a MathWorks account, visit www.MathWorks.com and create an account. Once you have
done this, click the Log In button and log in to your account. After logging in, you should see the screen below:

Accept the agreement and click the Next button. The window should show that you are attempting to install the
Freescale FRDM-KL25Z package:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Instrumentation and Microcontrollers Using Automatic Code Generation

Click the Next button to verify that you want to install the FRDM-KL25Z Support package:

Click the Install button to begin the installation. The first part of the package to be installed is the support
package for Arm Cortex-M Processors:

You may be asked for permission by Windows to install the package. The package will be downloaded and
then the installation will proceed. After a few moments and several different windows, you should see the
window below:

Click the Continue button:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

Select the Freescale Kinetis Microcontrollers support package and click the Next button:

Click here to download and install the


CMSIS Specification.

Most likely, you do not have the CMSIS Specification installed on your computer. Click on the link shown
above to install the specification. The process is not documented here as it is likely to change. Install the latest
version of CMSIS or a version new than or equal to the version specified by the dialog box. When you have
installed the CMSIS Specification, click the Next button:

MATLAB will validate that you have properly installed the specification. Click the Validate button to continue:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Instrumentation and Microcontrollers Using Automatic Code Generation

Click the Confirm button to verify that the CMSIS version MATLAB detected is the same as the version you
just installed:

We will skip the support package examples, so uncheck the box and click the Finish button. The installation
is complete. You may want to repeat the steps shown on pages 1-3 to verify that the Kinetis support package
has been installed properly.
2.
MATLAB Complier Setup
In order to translate our Simulink models into C and then run those models on the FRDM-KL25Z Target, an
appropriate compiler must be installed on your computer. To see if a compiler is installed, type mex setup at
the MATLAB command prompt:

The above screen capture shows that I have Microsoft Windows SDK 7.1 (C) installed and that this is an
acceptable compiler. If MATLAB shows that you do not have a compiler installed, go to
http://www.mathworks.com/support/compilers/R2014b/ to see a list of supported compilers. Note that the
Microsoft Windows SDK 7.1 works for both MATLAB and Simulink and it is free. Install a compiler and then use
the mex setup command to verify that MATLAB recognizes the installation.
3.
Installing the RHIT KL25Z Library
This manual contains several models, functions, and s-functions that can be difficult to
implement for people new to MATLAB, C, or Simulink. To make the more advanced functions easier to use, we
have created a RHIT_KL25Z_Library for Simulink. We will now install this library:

Download the library from MathWorks or my website at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation


_%28Freescale_KL25Z_Version%29#RHIT_FRDM-KL25Z_Block_Library . Locate the section of the page
named RHIT FRDM-KL25Z Block Library and download the latest version.
Unzip the file into a directory where you wish the files to reside.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

Open MATLAB click on the Set Path button

9
:

Click here.

The Set Path window will open:

Click on the Add Folder button and then locate the directory named RHIT_KL25Z_Library_R2014b and then
click on the Select Folder button:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

10

Instrumentation and Microcontrollers Using Automatic Code Generation

Folder added to the path.

Finally, click the Save button and then click the Close button. Restart MATLAB and then run Simulink by
typing simulink in at the MATLAB command prompt. You should see the RHIT KL25Z Library as shown:

ARM Cortex-M and FRDM-KL25Z hardware support


packages we installed earlier.

RHIT KL25Z Library listed


here.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

11

We have not yet covered how to run Simulink yet. If you do not know how to use the Simulink library browser,
we will cover it later. At this point, we are only using the library browser to verify that you have the RHIT
libraries installed correctly.
4.
Installing Freescale FreeMASTER
FreeMASTER is a tool developed by Freescale that allows us to see numerical values inside the FRDM-KL25Z
microcontroller while the controller is running our models. It is an extremely valuable debugging and
visualization tool. This tool can be downloaded from the Freescale website at
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=FREEMASTER. (Or you can search for
freescale freemaster with a search engine.) Download and install the latest version of the software. Note that
version 1.4 will be used for the examples shown in this manual.
5.
Installing Windows Device Drivers
There are two sets of device drivers that you may need to update and/or install on your Windows computer.
One driver is located on your FRDM-KL25Z board, the other must be downloaded from P&E Micro.
a)
Installing the USB COM Device Driver
Plug your FRDM-KL25Z into your Windows computer. Note that you should use the SDA port on the FRDMKL25Z board:

Use the port labelled SDA.

You will always use the SDA port for any exercise contained within this manual. When you plug in your board,
Windows will install device drivers for the FRDM-KL25Z board and it will appear as a drive on your system,
drive F: in my case:

Most likely, Windows will not be able to install the driver and you will receive an error. Open the Windows
Device Manager. (You can run the Device Manager by opening the Windows Control Panel and selecting the
Device Manager, or by right-clicking on Computer, selecting Properties, and then selecting Device Manager.)
When the Device Manager opens, you will notice that two drivers are listed as not being installed properly:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

12

Instrumentation and Microcontrollers Using Automatic Code Generation

These two drivers not


installed properly.

Right-click on this driver and select


Update Driver Software.

Right-click on PEMicro/Freescale CDC Serial Port and select Update Driver Software:

Select this option.

Select Browse my computer for driver software: Note that the driver is located on the FRDM-KL25Z board,
so select the drive for your FRDM-KL25Z board, F: on my system:

Specify the drive that represents


your FRDM-KL25Z board. Make
sure that you specify the root
directory.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

13

Click the Next button to install the driver:

Installation will take a few moments. When complete, you should see the screen below:

When you view the Device Manager window, you should notice that the Open SDA port is now installed
properly and is listed as a COM port:

We will fix this in the next section.

Open SDA port installed properly.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

14

Instrumentation and Microcontrollers Using Automatic Code Generation

We see that we still have one device that did not install properly. We will fix this in the next section.
b)
Installing the PE Micro Device Driver
Next, we need to install drivers for P&E Micro. You will need to download the installation program from PE
Micros website. The link for their website is located on a file on the FRDM-KL25Z drive. Open the drive that
represents the FRDM-KL25Z board on your computer. On my computer, drive F: is the FRDM-KL25Z board:

Double-click on this file.

Double-click on the file named SDA_INFO.HTM. A browser will open and you will go to the PE Micro website:

Scroll down the page to locate the Windows USB Driver section:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

15

Click on this link.

Click on the link PEDrivers_install.exe. You may be required to create an account and login. Download the
file and then run the file:

Agree to the terms and then select all of the default choices. When you are done, open the Device Manager. If
the installation was successful, you should see the PEMicro OpenSDA Debug Driver installed as shown
below:

Driver installed!

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

16

Instrumentation and Microcontrollers Using Automatic Code Generation

6.
Updating the FRDM-KL25Z Firmware
In order to use the Freescale FreeMASTER software without purchasing any additional hardware, you may
need to update the software on your FRDM-KL25Z board. The firmware can be obtained from PE Micros
website. The link for their website is located on a file on the FRDM-KL25Z drive. Open the drive that represents
the FRDM-KL25Z board on your computer. On my computer, drive F: is the FRDM-KL25Z board:

Double-click on this file.

Double-click on the file named SDA_INFO.HTM. A browser will open and you will go to the PE Micro website:

Note this version.

Note the Application Version number. If the Application Version is below 1.14, you will need to update the
firmware. If you have this version or higher, you can skip to the next section. To update the firmware, click on
the link shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

17

Click on this link.

You may be required to create an account and login. Download the file. When done, you should have a file
named something like Pemicro_OpenSDA_Debug_MSD_Update_Apps_2014_09_25.zip. Unzip this file. It
will create a new directory with a number of different files:

This is the file that we want.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

18

Instrumentation and Microcontrollers Using Automatic Code Generation

The file for the KL25Z board is named MSD-DEBUG-FRDM-KL25Z_Pemicro_v114.SDA. The update version
may be higher than version 114 shown above.
Next, we need to open the bootloader drive on your FRDM-KL25Z board. Do the following
steps:
1) Unplug your FRDM-KL25Z board from your computer.
2) Hold down the reset button (RST) on the FRDM-KL25Z board:

Hold down this RST button.

3) While holding down the RST button, plug your FRDM-KL25Z board into your computer.
4) Release the reset button.
The FRDM-KL25Z board will now appear as a drive called BOOTLOADER on your computer:

This shows that you have


opened the FRDM-KL25Z
board in the proper mode
and you can update the
firmware.

Open this drive. Copy the file MSD-DEBUG-FRDM-KL25Z_Pemicro_v114.SDA to your BOOTLOADER drive:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

19

Firmware has
been updated.

Next, unplug your FRDM-KL25Z board and then plug in the board again. Do not hold down the reset button
when you plug it in. (We are done with bootloader mode.) Note that the board will appear as new hardware for
your Windows computer and it will install a driver. When done, open the FRDM-KL25Z drive and double-click
on the file named SDA_INFO.HTM. A browser will open and bring you to the PE Micro website. The statistics
for your board will be displayed. If you successfully updated the firmware, the new Application Version will be
shown:

Verification that the firmware


has been updated.

7.
FRDM-KL25Z Electrical Setup
The Freescale FRDM-KL25Z can be powered from your USB port (as long as the KL25Z and external
hardware do not exceed the power limitations of the USB port) or an external power supply. For the first few
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

20

Instrumentation and Microcontrollers Using Automatic Code Generation

labs, we will use the USB supply and we will not even consider power draw. (Though you might want to
research just how much current a USB port can supply and how much current the KL25Z draws) Plug in the
KL25Z to your computer using the SDA port on the KL25Z:

Use the port labelled SDA.

Next, we have to examine the schematic and board layout of the KL25Z to determine the pin connection of the
on-board LED. First, we will look at the pin connections of Freescale FRDM-KL25Z. This file is saved as KL25Z
Pin Names.jpg:
Arduino UNO compatible pins.

Arduino UNO compatible pins.


Freescale pin names.
Freescale pin names.

Note that several of the pins are Arduino UNO compatible so that the FRDM-KL25Z board will work with many
of the shields 2 available for the Arduino Uno. We will be using the Freescale pin names throughout this
manual. However, you can also use the Arduino pin names in the MathWorks blocks to access the FRDMKL25Z hardware resources. Next, we will look at the KL25Z Schematic:

A shield is a board made by a 3rd party manufacturer that plugs into your controller board. Since the boards are Arduino
compatible, they can plug directly into your KL25Z. This allows you to easily add hardware to your controller without any
wiring on your part.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

21

This is obviously unreadable but the schematic is available in the documents provided for this lab. If we zoom
in on a portion of the schematic, we can see the RGB LED and determine the I/O pins:

Green LED is pin PTB19.

Red LED is pin PTB18.


Blue LED is pin D13.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

22

Instrumentation and Microcontrollers Using Automatic Code Generation

We see that the Red and Green LEDs are connected to pins PTB18 and PTB19, and the Blue LED is
connected to pin D13, which uses the Arduino pin terminology. Looking at the KL25Z pin map we see that pin
D13 is available on the header and has the Freescale pin name PTD1.
Blue LED is pin D13 and pin PTD1.

Pin PTD1 is directly wired to the blue LED on the KL25Z board, so no wiring is required to turn on and off the
blue LED. Since PTD1 is available on the jumper, we can also use it to control things external to the KL25Z
board. The only problem with doing this is that the blue LED might unintendedly flash as we use this output to
control the external device. PTB18 and PTB19 are not available on the header and these outputs only control
the Red and Greed LEDs.

C.

Lab Procedure

1.
Flip-Flop LEDs
We will now create a simple Simulink model to flash the blue on-board LED. Instead of creating a new model
manually and setting it up to run on the KL25Z, we will use a utility provided by MathWorks to create a new
model and set up the options to have it run on the KL25Z. In MATLAB select the Apps tab:

APPS tab selected.


Click on this icon.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

23

(If you do not have the Freescale Cup Companion app, skip to Section I.C.2 on page 30 to setup this model
manually.) Left click on the Freescale Cup Companion icon to run the app:

Click on the Create New Model button. Simulink will run and open an empty model:

We can now place parts in this model. Open the Simulink Library Browser by clicking on the Library Browser
icon

Click here.

The Simulink Library Browser will open:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

24

Instrumentation and Microcontrollers Using Automatic Code Generation

Select the Simulink / Sources library as shown below:

Sources library
selected.

Scroll down the right pane to locate the Pulse Generator:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

25

Pulse
Generator.

Drag the pulse generator into your model:

Double-click on the pulse generator part to edit its attributes. Specify a Period of 1 second and a Pulse Width
of 50%. This will cause our LED to flash on and off at a 1 Hz rate (on and off once per second) with the LED on
50% of the time and off for 50% of the time. Note that the period of a signal is one divided by the frequency,
= 1 , for a frequency of 1 Hz, we will have a period of 1 second:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

26

Instrumentation and Microcontrollers Using Automatic Code Generation

Click the OK button to accept the changes. Next, select the RHIT KL25Z Library / Basic Blocks library:

Digital Output block.

Library selected.

Locate the Digital Output block and drag one into your model:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

27

Digital Output

Connect the input of the Digital Output block to the output of the Pulse Generator:

Next, double-click on the Digital Output block to modify its properties. Change the pin number to PTD1:
Use this menu to change
the pin name to PTD1.

These 5 buttons will display


information about the KL25Z
board such as schematics and
pin names.

Remember that Pin PTD1 will drive the on-board blue LED. Click the OK button to accept the changes. Note in
the model that Pin PTD1 will be displayed on the block:

Before continuing, save your model as Lab1_Project1.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

28

Instrumentation and Microcontrollers Using Automatic Code Generation

We are now ready to run our first model on the FRDM-KL25Z Microcontroller target. To compile
the model, download it to the FRDM-KL25Z Target, and run the model on the target, click on the Build Model
button

Click on this button

A bunch of stuff will happen:

Stuff happening!

Click here to view the


diagnostic window.

When the download is complete, the blue LED light will flash on and off at 1 Hz.
If there was an error and your blue LED is not flashing on and off, you can view the diagnostic
window by clicking on the link as shown above:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

29

These models specify the


size of the model
downloaded to the KL25Z.

This shows that we are


trying to download the
model to the KL25Z.

This shows that the


download was successful.

If the download was not successful, you might not have the drivers installed correctly. However, it is more likely
that you forgot to plug in your KL25Z board into your computer.
The numbers displayed are also important as they specify the size of the model downloaded to
the KL25Z. If the model becomes too large two things may occur. If Simulink detects that the model is too
large, an error message will be generated. If the model is too large and this is not detected by Simulink, the
model will be downloaded to the KL25Z. The results will be a model that does not run properly or not at all.
Since Simulink cannot always detect when a model is too large the general rules for size limits are that the text
size should be less than 130,000, the data size below 7,900, and the BSS size below 17,000. These data sizes
are not mutually exclusive, so a general rule would be to stay 10% below theses limits.
Note that the model is written to the FRDM-KL25Z flash memory so that if you cycle the power,
the model will remain in memory and restart at power up or when you press the reset (RST) button.
Demo I.1: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate.
Exercise I.1: Change the model so that the blue LED flashes at a 2 Hz rate. Demo to your instructor.
Exercise I.2: Change the model so that the blue LED flashes at a 10 Hz rate. Demo to your instructor.
Exercise I.3: Change the model so that the red LED flashes at a 2 Hz rate. Demo to your instructor.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

30

Instrumentation and Microcontrollers Using Automatic Code Generation

Exercise I.4: Change the model so that the LED switches back and forth between flashing at a 1 HZ rate and a
2 Hz rate. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library, use
a part called Switch.
Exercise I.5: Change the model so that the LED switches back and forth between a red LED flashing at a 1 HZ
rate and a Green LED flashing at a 2 Hz rate. When a specific color LED is not flashing, it should be off all of
the time. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library, use
a part called Switch. You may need a Rate Transition block to solve this problem.
Exercise I.6: Create a model that switches the LED between Green and Red at a 1 Hz rate. When the green
LED is on, the red LED should be off and vice versa. There never should be a time when all of the LEDs are
off.
2.
Manually Setting up a KL25Z Simulink Model
In this example we will show how to create a model to run on the KL25Z without using the Freescale Cup
Companion App. We will create the same model as in section I.C.1. Type in Simulink at the MATLAB
command prompt to start Simulink:

The Simulink library browser will open:

Click here to create a


new model.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers


Click on the New Model button

31

to create a new model:

We will now set up the project to run on the FRDM-KL25Z target. The settings that we specify here are the
same as would have been set had we used the Freescale Cup Companion app. Select Simulation and then
Model Configuration Parameters from the Simulink menus:

The Configuration Parameters window will open. Select the Solver pane and then specify a Fixed-step
discrete solver:

Select the discrete solver


second.
Select the Fixed-step type
first.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

32

Instrumentation and Microcontrollers Using Automatic Code Generation

A fixed step solver is necessary for real-time operation. In essence, to operate in real time, the model must
execute once every fixed time step. If we have a short fixed time step and a complex model, the calculations
required by the model may take too long to execute within the specified fixed time step and the model will not
run in real-time. (When the model takes more time to run than the fixed-step size it is called an over-run.) In
this model, the Fixed-step size is set to auto which means that Simulink will choose a value for the fixed time
step. For the model we are creating, this is not a problem. In most of the later models, we will specify a fixedstep size as we want the microcontroller to perform tasks at a specified speed. There are several fixed-step
solvers available. The discrete solver is the fastest in that it requires the least amount of time to perform
calculations. Basically, the next outputs are calculated with the present values only. In the higher order solvers,
the next outputs are calculated with the present values plus values from previous time steps. The higher the
order the larger the number of previous time steps that are used in the calculation. Higher order solvers can be
more accurate but they also require more calculations for each time step, which could cause an overrun. In
general you will not need a higher order solver unless you are using continuous time functions such as Laplace
transforms. To make our models run as fast as possible, we will almost always use the discrete solver.
Next, select the Code Generation pane:

Click on this Browse button.

Code Generation pane


selected.

Click on the Browse button and then select the ert.tlc target file as shown:

ert.tlc selected.

After you click the OK button, the Configuration Parameters dialog box will change slightly. Specify the
Target Hardware as Freescale FRDM-KL25Z:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

33

Select Freescale FRDM-KL25Z.

Next, select the Coder Target pane and specify Build action as Build, load and run:

Build, load and run selected.

Coder Target selected.

The Build, load and run option specifies that Simulink should download the model to the KL25Z and run it
after we choose to build the model. We are now done setting up the model, so click the OK button to save the
changes.
We are now ready to create the model. 3 If the Simulink library browser is not already open then
open the Simulink Library Browser by clicking on the Library Browser icon

The procedure here is a repeat of section I.C.1.3 It is included here for those who did not create the model using the
Freescale Cup Companion app. The exercises and demos in this section are the same as in section I.C.1 as well.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

34

Instrumentation and Microcontrollers Using Automatic Code Generation

Click here.

The Simulink Library Browser will open:

Select the Simulink/Sources library as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

35

Sources library
selected.

Scroll down the right pane to locate the Pulse Generator:

Pulse
Generator.

Drag the pulse generator into your model:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

36

Instrumentation and Microcontrollers Using Automatic Code Generation

Double-click on the pulse generator part to edit its attributes. Specify a Period of 1 second and a Pulse Width
of 50%. This will cause our LED to flash on and off at a 1 Hz rate (on and off once per second) with the LED on
50% of the time and off for 50% of the time. Note that the period of a signal is one divided by the frequency,
= 1 , for a frequency of 1 Hz, we will have a period of 1 second:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

37

Click the OK button to accept the changes. Next, select the RHIT KL25Z Library / Basic Blocks library:

Digital Output block.

Library selected.

Locate the Digital Output block and drag one into your model:

Digital Output

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

38

Instrumentation and Microcontrollers Using Automatic Code Generation

Connect the input of the digital block to the output of the Pulse Generator:

Next, double-click on the Digital Output block to modify its properties. Change the pin number to PTD1:

Use this menu to change


the pin name to PTD1.

These 5 buttons will display


information about the
KL25Z board such as
schematics and pin names.

Remember that Pin PTD1 will drive the on-board blue LED. Click the OK button to accept the changes. Note in
the model that Pin PTD1 will be displayed on the block:

Before continuing, save your model as Lab1_Project1.


We are now ready to run our first model on the FRDM-KL25Z Microcontroller target. To compile
the model, download it to the FRDM-KL25Z Target, and run the model on the target, click on the Build Model
button

:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

39

Click on this button

A bunch of stuff will happen:

Stuff is happening!

Click here to view the


diagnostic window.

When the download is complete, the blue LED light will flash on and off at 1 Hz.
If there was an error and your Blue LED is not flashing on and off, you can view the diagnostic
window by clicking on the link as shown above:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

40

Instrumentation and Microcontrollers Using Automatic Code Generation

This shows that we are


trying to download the
model to the KL25Z.

This shows that the


download was successful.

If the download was not successful, you might not have the drivers installed correctly. However, it is more likely
that you forgot to plug in your KL25Z board into your computer.
Note that the model is written to the FRDM-KL25Z flash memory so that if you cycle the power,
the model will remain in memory and restart at power up or when you press the reset button.
Demo I.2: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate.
Exercise I.7: Change the model so that the blue LED flashes at a 2 Hz rate. Demo to your instructor.
Exercise I.8: Change the model so that the blue LED flashes at a 10 Hz rate. Demo to your instructor.
Exercise I.9: Change the model so that the red LED flashes at a 2 Hz rate. Demo to your instructor.
Exercise I.10: Change the model so that the LED switches back and forth between flashing at a 1 HZ rate and
a 2 Hz rate. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks library,
use a part called Switch. You may need a Rate Transition block to solve this problem.
Exercise I.11: Change the model so that the LED switches back and forth between the red LED flashing at a 1
HZ rate and the Green LED flashing at a 2 Hz rate. When a specific color LED is not flashing and off, it should
be off all of the time. The rate should change every 5 seconds. Hint: In the Simulink Commonly Used Blocks
library, use a part called Switch. Exercise I.12: Create a model that switches the LED between Green and Red
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

41

at a 2 Hz rate. When the green LED is on, the red LED should be off and vice versa. There never should be a
time when all of the LEDs are off. You may need a Rate Transition block to solve this problem.
3.
Using the MathWorks KL25Z Library
The MathWorks library for the FRDM-KL25Z provides many of the same functions as the RHIT library,
plus some blocks not available in the RHIT library. The digital and analog blocks in the MathWorks library are
limited to the Arduino Uno compatible pins of the KL25Z. The digital and analog blocks in the RHIT library are
generalized versions of the MathWorks blocks (and were developed with much assistance from The
MathWorks). In this manual, we will use the RHIT blocks because they use the Freescale pin naming
convention. However, the MathWorks blocks can be used instead of the RHIT blocks if the Arduino Uno
compatible pins are used.
We will start with the model from the previous section. Select File and then Save As from the
Simulink menus, and then save the model as Lab1_Project2. Delete the RHIT Digital Output block. You should
have the model shown below:

In the Simulink Library Browser, expand the Embedded Coder Support Package for Freescale FRDMKL25Z Board menu and select FRDM-KL25Z:

Drag this block into you model.

FRDM-KL25Z library selected.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

42

Instrumentation and Microcontrollers Using Automatic Code Generation

We see that the library has several blocks not available in the RHIT library. Specifically, we will be using the
Analog output and Serial blocks in future labs. Drag the Digital Output block into your model and connect it as
shown below:

Double-click on the Digital Output block and change the Pin to D13, the pin connected to the on-board blue
LED:

Pin D13 selected.

Note that the only pins available are D0 through D13, which are the pins on the KL25Z that are compatible with
the Arduino Uno. Click the OK button to accept the changes.
We are now ready to build and download the model. Type Ctrl-B, click on the Build Button
, or select Code, C/C++ Code, and then Build Model from the Simulink menus to build the model:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

43

Since we chose the Build, Load and Run option, the model will be built, downloaded to the KL25Z, and then
run on the KL25Z.
Demo I.3: Show the FRDM-KL25Z on-board blue LED flashing at a 1 Hz Rate using the MathWorks Digital
Output block.
Exercise I.13: Using the RGB LED block, create a model that flashes the LED on and off at a 1 Hz rate. When
on, the LED color should be purple.
Exercise I.14: Using three Counter Limited blocks, three Rate Transition blocks, and the RGB LED block,
create a model that steps the red LED from 0 to 255 in 0.01 second steps, the green LED from 0 to 255 in 0.02
second steps, and the blue LED from 0 to 255 in 0.03 second steps.
4.
Driving a Single Off-Board LED
Next, we will learn how to drive a load directly from the FRDM-KL25Z digital output ports. Whenever you
connect a load to the output of an electronic device, you must find out how much current that output can
source or sink. When a device sinks current, current flows into the device output pin as shown below. In this
example, if the output voltage of the OP-AMP is less than the supply voltage Vcc, current will flow into the OPAMP output as shown, and the OP-AMP will sink current:

ISink

Typically, a device will sink current if one side of the load is tied to the positive supply (often referred to as the
positive rail or the positive supply rail. In this case, when the output of the device (the OP-AMP shown
above) goes low, current will flow into the device. (Current flows from a high voltage to a low voltage.)
When a device sources current, current flows out of the device output pin as shown below. In this
example, if the output voltage of the OP-AMP is greater than ground (zero volts), current will flow out of the
OP-AMP output as shown, and the OP-AMP will source current:

ISource

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

44

Instrumentation and Microcontrollers Using Automatic Code Generation

Typically, a device will source current if one side of the load is grounded. In this case, when the output of the
device (the OP-AMP shown above) goes high, current will flow out of the device. The ARM mbed webpage 4
for the FRDM-KL25Z states that the digital IO pins are 3.3 V and can supply a maximum current of 4 mA:

The only problem with this information is that we do not know if this is source or sink current. We will assume
that the digital IO lines can source or sink 4 mA of current.
We will now drive an LED from the FRDM-KL25Z digital output. We have two choices, we can
turn on the LED when the digital output is low and have the output sink current, or we can turn on the LED
when the digital output is high and have the output source current. In both cases, we will design the circuit to
have about 3 mA of current flow through the LED. We will also assume that when the LED is on, the voltage
drop across it is about 1.8 V. The circuit below turns on the LED when the digital output goes low:

3.3 V

ISink

LED

1.8 V
-

Vo

When VO goes low (0 V), we would like the current, ISink, to be 3 mA. The equation for the resistor is
4

http://developer.mbed.org/handbook/mbed-FRDM-KL25Z. Note that a number of FRDM-KL25Z datasheets and users


manuals can be obtained from this page.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers


=

45

3.3 1.8 0 1.5


=
=
= 500

The closest standard 5% resistors are 510 and 470 , so we can use either of those two values.
We can also use the circuit below to turn on the LED when the digital output goes high (3.3 V):
Vo

LED

+
1.8 V
-

ISource

When VO goes high (3.3 V), we would like the current, ISource, to be 3 mA. The equation for the resistor is
=

3.3 1.8 1.5


=
=
= 500

Once again, the closest standard 5% resistors are 510 and 470 . Thus, in both cases, we can use the
same resistor value. Note that in many cases, although the logic power supply is 3.3 V, the digital outputs do
not go to the rail, and VO is not 3.3 V, but somewhat less.
We will use the second method show above to drive the LED. This time we will use pin PTC9 of
the FRDM-KL25Z to turn on the LED when the output is high. Modify the Simulink model as shown:

Note that we will still use the ON Board LED block (available in RHIT KL25Z Library / Basic Blocks) to drive
the on-board red LED because we know this works and if our new LED circuit does not work, this on-board
flashing LED will at least tell us that the board is working and running our model.
For this and future labs, we are going to need many connections to ground and the +3.3 V
supply. These pins are available on the FRDM-KL25Z board as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

46

Instrumentation and Microcontrollers Using Automatic Code Generation

+3.3 V pin
Ground pin

+3.3 V pin

Ground pins (2)

We will route these to the supply busses as shown below:

Ground bus.

+3.3 V bus.

Ground pin.

+3.3 V pin.

We will use the blue bus as the ground bus and the red bus as the +3.3 V supply bus. If you have other busses
on your board, you can connect them as shown:

Your entire board should look as shown:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

47

Bus connections.

Bus connections.

Bus connections.

On the board shown, the blue bus is the ground bus and the red bus is the +3.3 V supply bus, and both busses
make a horse shoe pattern around the board.
Power busses, as we use them here, are long wires to which we make several connections. We
will have many connections to ground and many connections to the +3.3V power supply. A power bus is a
good way to make all of these connections. If you peel off the back of your prototyping board (do not do this)
you will notice that the blue and red stripped bus bars run the length of the board. This makes them convenient
to use for many connections. (In this case, power and ground.):
Power Bus

Power Bus

Power Bus

Power Bus

Note, however, that the busses on each side of the board are not connected. Therefore, we connected them as
shown below:

Jumpers
connecting blue
bus to blue bus.

Jumpers
connecting red
bus to red bus.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

48

Instrumentation and Microcontrollers Using Automatic Code Generation

Also note that the shorter connections only connect 5 holes together. This arrangement allows
us to easily connect elements together. Each one of these shorter bars is a connection node in our circuit. We
can have up to five connections for each node. See the picture below for items that are connected on the
prototyping board:

These holes are


connected.

The last thing we need to do is to wire up the LED circuit. Note that the longer lead on the LED
is the positive lead (referred to as the anode):
+

Wire the circuit on your board as shown below (or something close):

When your model is complete and you have wired your circuit, connect your FRDM-KL25Z to your computer
with the USB cable. Click the Build button
to build your model and then download and run it on the FRDMKL25Z target. If all goes well, your wired LED should flash on and off at the same rate as the on-board LED.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab I: Opening the World of Microcontrollers

49

Note that the circuit requires a resistor, the value of which is usually marked with a color code. To learn how to
read a color code, search for information on the internet with the phrase, resistor color code calculator.
Demo I.4: Show the off-board LED flashing at a 1 Hz rate.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

II.

Counters, Digital Input, Stateflow, Truth Tables

Lab II
Counters, Digital Input, Stateflow, Truth Tables

In this lab we will learn how to use the digital input block to read a 1-bit input, and also look at the many
different facilities available in Simulink for implementing both simple and complex logic functions. We will
illustrate the facilities by creating a few simple counters, and then adding functionality to those counters.

A.

Digital Input Block

The Freescale FRDM-KL25Z has 53 pins that can be used as digital inputs. (Keep in mind that these are
multifunction pins that could be used for digital outputs, PWM/analog output, analog inputs, plus several other
functions). Typically, when the input voltage to a digital input is between 0 and 0.8 Volts, the block will output a
logic low or false. (For the Freescale FRDM-KL25Z, it will output a numerical value of zero.) When the input
voltage to a digital input is between ~2 and 3.3 Volts, the block will output a logic high or true. (For the
Freescale FRDM-KL25Z, it will output a numerical value of one.) The voltage ranges are typical and depend
on the logic family. The logic family is the type of electronic circuitry used to realize the function.
We are going to use the digital input to read the input of a switch. To save cost, a single-polesingle-throw (SPST) switch will be used. SPST is a fancy way of saying that the switch is either open or
closed and that it has only two terminals. Open is short for an open circuit where no current flows basically
the switch connects something to something else and the connection is not made. Closed means a
connection is made. We will use the circuit below to allow a single SPST switch to output two voltage levels:
+3.3 V

R
Vo

When the switch is open, we have the circuit below:


+3.3 V

I=0
Vo

The output voltage is 3.3 V IR. Since the current is zero, IR is zero, and VO = 3.3 V. VO is said to be pulledup to 3.3 V, and the resistor in this circuit is called a pull-up resistor. When used in an actual circuit, VO is
connected to the digital input as shown below:
+3.3 V

R
Vo

I0
Digital Input Block

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

51

When the input to a digital block is high a small amount of current usually flows into the input of that block as
shown. The amount of current depends on the implementation of that block, but can be anywhere between
zero and 40 A depending on the type of logic. For the Freescale Kinetis KL25 sub-Family of processors, the
maximum input current is 1 A. This small current will create a voltage drop across the pull-up resistor and
result in VO dropping below 3.3 V. If the resistor is chosen too large, VO may drop so low that it is no longer
considered a logic high input to the digital block. This would obviously be a problem, as the reason for using a
pull-up resistor was to pull VO up to a high voltage when the switch was open.
When the switch is closed, we have the circuit shown below:
+3.3 V

R
Vo

VO is directly tied to ground, so VO is zero volts, a good low logic input. When connected to a digital block, we
have the circuit shown below:
+3.3 V

IR

Vo
Digital Input Block

ILow
When the input to some digital blocks is tied low, as shown in the figure, current will flow out of the input. In our
case, ILow flows directly to ground through the switch and does not affect the voltage VO. For this circuit, neither
the value of the resistor nor the current ILow affect the input voltage to the digital block, VO. The only effect the
choice of the resistor has is the current through the resistor when the switch is closed. (The current would be
3.3
.)

This is a power draw from the +3.3 V supply. The smaller the resistor, the more current it draws from the

supply. Note that power is equal to voltage times current, P=VI. We have a fixed 3.3 V supply, so the more
current we draw, the more power we draw. To reduce power draw, in general we want resistors large.

Thus, we see that the choice of the pull-up resistor is a trade-off. We want the resistor to be
small when the switch is open so that we get a good logic high input to the digital block. When the switch is
closed, we want a large value for the resistor so that it does not draw too much current and power from the
supply. A good compromise for the value of a pull-up resistor is 10 k. For a 10 k resistor used as a pull-up
for a digital input of the KL25Z, when the switch is open the KL25Z will draw 1 A of current. The high input
voltage will be 3.3 V (1 A * 10 k) or 3.29 V, which is a very good high input. When the switch is closed, the
10 k resistor will draw power (3.3 V)2/10 k = 1.089 mW. Thus, a 10 k resistor is a good choice for a pull-up
as it draws little power when the switch is closed and it provides a good high input voltage when the switch is
open.
We will now create the circuit/model below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

52

Instrumentation and Microcontrollers Using Automatic Code Generation


+3.3 V

R1

Digital Input Block

Digital Output Block

LED
Simulink Model

R2

All we are doing is reading a single digital input, and passing that information directly to a digital output block.
When the switch is closed, the LED should turn off. When the switch is open, the LED should turn on. (We
dont need a microcontroller for this, but hey, why not make things as complicated as possible.) We will keep
the flashing on-board LEDs from Lab 1 in all of our models so that we know the controller is working. The
complete model is shown below:

We will use pin PTA1 as the input and pin PTC9 as the output.
Next, wire up the circuit on your breadboard. The picture below shows the layout using a
pushbutton switch:

Pushbutton
switch.

Pull-up resistor.

Wire for a future lab.


Just ignore it...

Note that you can use a piece of wire as a switch if you do not have a real switch:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

10 k pull-up
resistor.

53

Wire used as a
switch.

Connect this side of


the wire to the 10 k
resistor to close the
switch. Leave this
end unconnected as
shown for the
switch to be open.

Demo II.1: Show the operation of this circuit to your instructor. When the switch is closed the LED should be
off. When the switch is open, the LED should be on.
When testing your model, you may have noticed that the LED does not respond quickly to the
switch being closed. This is because the default setting of the time step (referred to as the fixed-step size) was
set to auto by Simulink. To see the setting, select Simulation and then Model Configuration Parameters
from the Simulink menus, type Ctrl-E, or click on the Model Configuration Parameters button

Fixed-step size set to auto.

The auto setting means that Simulink will choose the fixed-time step. The result is that it may choose a step
that is too large for your specific application. The time step determines how fast the controller operates. Even
though a model is very small, the model will only execute once every time step. For example, suppose the time
step is one second. For our model, the input will be checked and the output will be set only once per second. If
the input changes at a faster rate, the controller will not notice a change or may respond late. To avoid this
problem always specify a time for the fixed-step size. For this example, a fixed-step time of 0.1 appears to be
instantaneous to me. (Meaning that when I press the button the light appears to turn on immediately. It could
actually be as long as 0.1 seconds. However, something this fast appears to be instantaneous to humans 5.)
Change the Fixed-step size to 0.1 and test your model.

I just made this up. There is no reference backing up this statement. Research also shows that 63.7% of all statistical
facts are made up on the spot.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

54

Instrumentation and Microcontrollers Using Automatic Code Generation

Demo II.2: Show the operation of switch/digital input/digital output model with a 0.1 second fixed-time step.
When the switch is closed, the LED should be off. When the switch is open, the LED should be on.

B.

Counters with Basic Logic Blocks

1.
Ring Counter
We will now create an 8-bit ring counter that lights up 8 LEDs with the sequence shown below:
Bit
1

Bit
2

Bit
3

Bit
4

Bit
5

Bit
6

Bit
7

Bit
8

Only one LED is illuminated at a time, and the illuminated light shifts from left to right. We would like this ring
counter to change state every half second. This counter has eight different states, thus, we need a Simulink
counter that has eight different values. We will use the Repeating Sequence Stair Simulink block found in the
Commonly Used Blocks / Sources library:

Fill in the properties of the Repeating Sequence Stair block as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

55

We actually could have used any sequence of numbers as long as the numbers in the vector were unique.
(You will see why in the next step.)
Next, we will create a simple decoder using the Compare to Constant block located in the Simulink /
Logic and Bit Operations library:

Double-click on the Compare to Constant block and change its properties to compare to zero and add a
digital output block:

Note that the output data type for the Compare to Constant block was type Boolean. (A Boolean data type
has two values, True and False.) This is an acceptable data type for the Digital Output block, so we can just
connect the two. Complete the model for the 7 other states as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

56

Instrumentation and Microcontrollers Using Automatic Code Generation

We will use this arrangement of LEDs for the remainder of the lab. It will also be used for several of the future
labs, so you should leave the circuit assembled on your proto-board.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

57

Demo II.3: Wire up the eight LEDs to your chosen pins and demo the ring counter.
Exercise II.1: Create a model that illuminates the LEDs in the sequence shown below:
Bit
1

Bit
2

Bit
3

Bit
4

Bit
5

Bit
6

Bit
7

Bit
8

2.
The Digital Memory Block
We will now create our own counter. We will be using this counter instead of the Repeating Sequence Stair
block used in the previous example. Implementing a counter requires a memory block. We will use the
Memory block
located in the Simulink / Discrete library. The output of this block is the input from the
previous time step. We can implement a counter using the Sum, Memory, and Constant blocks as shown:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

58

Instrumentation and Microcontrollers Using Automatic Code Generation

The counter will start at zero and count up forever. The counter starts at zero because the default initial
condition for the Memory block is zero. To reset the counter to zero, we need to use a switch to change the
feedback to a -1 when the counter reaches 7. The Switch block is located in the Simulink / Commonly Used
Blocks library:

This is the
counter output.

This counter will count up every time the model executes, which could be fast depending on the time step. To
control this, we have to specify the time step for the model. Select Simulation and then Model Configuration
Parameters from the Simulink menus (or type CTRL-E or click the Model Configuration Parameters button
), and specify the Fixed-step size as 0.5 seconds:

0.5 second step


size specified.

Solver
selected.

Run the model. You may have to fix a few issues with the Pulse Generator that we created by changing the
fixed time step. The advantage to using a counter of this type is that we can have full control over the operation
of the counter, such as pausing the counter or having it count up or down on command.
Demo II.4: Demo the ring counter using a counter implemented with the Memory block.
Exercise II.2: Using a digital input, modify the previous model so that the counter holds its value (stops
counting) when the switch is closed. Note that a switch is required for this exercise.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

59

Exercise II.3: Using a digital input, modify the ring counter model so that the counter counts up when the switch
is open and counts down when the switch is closed. The counter is not allowed to jump or skip a count when
the switch is pressed.

C.

Using a Stateflow Chart to Implement State Diagrams

A Stateflow chart is a programming facility that allows us to graphically set up a state diagram. A state diagram
has memory (the states) and allows us to use rules of logic to transition between those states. With memory,
we know where we have been. With logic transitions, we can determine where we are going. With Stateflow we
can create logic based on history or a sequence of events, and use the rules of logic to determine the next
state.
We will use Stateflow to create a simple counter. Start with the previous project and delete the counter
we created with the Memory block:

Next, add a Chart from the Stateflow library to your model:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

60

Instrumentation and Microcontrollers Using Automatic Code Generation

Double-click on the chart to open it. You will have an empty Stateflow chart as shown:

Next, drag a state into the chart by clicking and holding the left mouse button on the State button
shown:

as

Drag this into


your chart.

An empty state will be attached to your mouse pointer. Drag it in your chart:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

61

Click on the question mark to highlight it and then type a name for the state. Call the state Zero_Count. Note
that there can be no spaces in the name of a state:

This state will be used to initialize and reset the count to zero. First, we need to create an output for this chart.
This output will keep track of the count and also be fed to the remainder of the Simulink model. To create an
output, select Chart, Add Inputs & Outputs, and then Data Output to Simulink:

Change the name of the output to Count:

Name changed
to Count.

Since we specifically created an output variable, the Scope is set to Output for us. Click the OK button to
create the output. You will not notice any difference in the Stateflow chart. However, if you flip back to the
Simulink diagram, you will notice that the chart now has an output:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

62

Instrumentation and Microcontrollers Using Automatic Code Generation


Chart output.

We will continue with the Stateflow chart. Now that we have defined an output, we can use it. In the
Zero_Count state, add a new line with the text en: Count=0;

The text en: means that when we enter the state, execute the following command. The command is not
executed while we are in the state or when we exit the state. Thus, the line en: Count=0; sets the counter to
zero when we enter the state and only when we enter the state. Other available commands are du: and ex:.
The ex: command executes the statement when we leave a state. The du: command repeatedly executes a
statement while it is in the state (if you want the value to change while in the same state). Note that commands
specified with the du: command will execute each time the chart executes. At this point in this manual, this will
be every fixed-time step.
Next, we need to add a second state that counts up. You can drag in a new empty state or rightclick and copy the Zero_Count state. Fill in the state as shown:

We only need two states for this chart. One state to reset the counter to zero, the other to count up. The next
things we need are transitions to determine how we go between states. To create a transition, place the mouse
pointer over the edge of the top state. The cursor will be replaced with a crosshair:

Crosshair

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

63

When you click and hold the left mouse button, a transition from the first state becomes attached to the pointer:

Transition

Place the mouse pointer over the right edge of the Count_Up state. The Transition will become attached to the
state:

Transition is attached to the


second state. Note
crosshair is still visible.

When you release the mouse button, the transition will become attached to the state. Repeat the process to
add a transition from the Count_Up state back to the Zero_Count state:

These transitions are called unguarded transitions in that the transitions will always be taken unless we add a
guard. The only time we want to move to the Zero_Count state is when the count has reached 7. Thus, we
only want to take the left transition when the count is 7. Click on the left transition. A question mark will appear:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

64

Instrumentation and Microcontrollers Using Automatic Code Generation

Click here to make


the question mark
appear.

Click on the question mark and enter the text [Count==7]. Note the double equals sign (==):

This guard means that the left transition will only be taken when the count reaches 7.
Since the count up state only counts up when the state is entered (because we used the
command en:Count=Count+1;), we need to add a transition from the Count_Up state to itself:

Transition added.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

65

The last thing we need to specify is in which state the chart starts when the controller powers up. This is done
by adding a default transition. Click on the default transition button
transition:

as shown below and drag in a default

Click on this
button.

Connect the default transition as shown:

When the model starts, it will go to the state indicated by the default transition. In this case, it will start in the
Zero_Count state, which has the effect of initializing the counter to zero. 6
The chart is now complete. Switch back to the model and connect the chart to the remainder of
the Simulink model:

Stateflow supports a large number of operations that cannot be covered here. To see an extensive list, search for
Supported Operations on Chart Data in the Simulink help.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

66

Instrumentation and Microcontrollers Using Automatic Code Generation

Note that the chart executes once every time step. In the previous model, we specified a fixed time step of 0.5
seconds, and this model started as a copy of the previous model. Thus, the transitions are checked each fixed
time step, or 0.5 seconds in this example.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

67

Demo II.5: Demo the ring counter using a counter implemented with the Stateflow chart.
As another example, we will create an up-down counter, where the counter counts up from zero to 7, and then
back down to zero. The Stateflow chart for this model is shown below:

We see one new item in this chart (besides the added logic) which is a transition action. In the default transition
we see the text /{Count=-1;}. This command is different from then en:, ex:, and du: commands mentioned
earlier which execute a statement upon entering, exiting, or while in a state. /{Count=-1;} is called a transition
action. The action Count=-1; is executed when the transition is taken and happens before it enters the next
state. Here, we are using the transition action to initialize the counter when the controller first starts. Note that
we can implement the same logic function using transition actions for all of the transitions:

Demo II.6: Demo the up-down ring counter using a counter implemented with the Stateflow chart.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

68

Instrumentation and Microcontrollers Using Automatic Code Generation

Exercise II.4: Using Stateflow and a digital input, create a ring counter that shifts to the right when a switch is
open and shifts to the left when the switch is closed.
Exercise II.5: Using Stateflow and a second digital input, modify your solution to Exercise II.4 by adding a
switch that will hold the count at its present value. The first switch will still determine the direction. Note that
&& is the logical AND in Stateflow syntax.

D.

Debugging Tools

We will discuss two debugging tools in this section. The Freescale FreeMASTER tool allows us to view
signal values on the target as our models are running in real-time. Overrun detection allows us to see if a
model executes within our specified fixed time step and does indeed operate in real-time.
1.
Overrun Detection
Inherently, a Simulink model is executed repeatedly as a loop. Blocks in the model execute in an order
determined by when data becomes available in the model. All blocks in the model are executed once (unless
there are conditional blocks or repeated loops), and then the entire model is repeated again. The fixed time
step we specify in Simulink is the rate at which the model execution is repeated. All calculations in the model
must be completed in an amount of time less than the fixed time step for the model to run in real time. Note
that the fixed time step is not the clock rate at which instructions are executed on the FRDM-KL25Z. Instead, it
is the time we have allotted to the controller to execute all calculations in the model. If the time step is longer
than the time needed to perform the calculations, the controller will wait before it loops and executes the model
again. Here we say that the calculations finish on time. When the calculations finish on time, we know how
often the model execution repeats; it repeats at the fixed time step. In this case, the model runs in real time.
If the time step is too small and the model calculations take longer to complete than the fixed time step,
the calculations are said to have finished late and we have what is called an overrun. When the calculations
finish late we have no idea how often the model execution repeats; it repeats at a rate determined how long the
calculations take to complete. In this case, the model does not run in real time.
Having a fixed time step that is too small can have three consequences: (1) The best scenario is that
the model runs, but it does not run in real time, which will make the application of the controller incorrect. This
is dangerous and sometimes hard to determine immediately. (2) The model runs, but the logic is not correct.
(3) The controller just hangs up and completely dies.
Because these problems can be quite serious, the FRDM-KL25Z has overrun detection and we have
created a Simulink overrun detection block so that we can easily determine if our model overruns. We can use
the overrun detection block to turn on an LED so that we know when an overrun occurs.
Drag the block named Overrun Flag located in the RHIT KL25Z Library / Basic Blocks into your
model and connect it to a new digital output block:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

69

Wire up an LED and resistor as described in Section I.C.2 to output pin PTC7. I will use a blue led to
distinguish it from other LEDs on my board:

Blue overrun LED.

If the LED turns on, we have an overrun. (You never want an overrun to occur, so when this LED turns on, fix
the problem 7.) Because overruns can cause your models to behave improperly, it is recommend that you
use this LED and the overrun fault block for all of the labs in this manual. (Always use overrun detection
in all labs, even if one is not specifically called out.)
Demo II.7: Demonstrate that your overrun detection works by reducing the fixed-time step until the step is too
small for the model to run in real-time and the overrun detection light comes on. What is the value of your fixed
time step? After the demo, make sure that you set the fixed-step size back to 0.5 seconds.
2.
Using Freescale FreeMASTER
The FreeMASTER tool will allow us to view signals on the KL25Z as the model is running. We can view the
values as a plot and as text values. Here we will show the use of FreeMASTER to view the value of the
counter and the pulse generator. The first thing we must do is label the signals that we would like to view. Right
click on the wire connecting the Pulse Generator to the Green LED and then select properties:

Dont fix the problem by removing the LED.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

70

Instrumentation and Microcontrollers Using Automatic Code Generation

Right-click here.

Then select Properties:

Enter a name for the signal. I will call it Pulse_Gen:

Enter the Signal name here.

Next, select the Code Generation tab and specify the signal as ExportedGlobal:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

71

Code Generation tab selected.

Exported Global selected.

Click the OK button to accept the settings. The signal should be displayed on the wire as shown:
Signal name displayed here.

Repeat the procedure to label the signal for the chart as Counter_Value. Make sure that you declare it as
ExportedGlobal as well:

Signal name displayed here.

Save your model and then build and download your model to the KL25Z target. My complete model,
showing overrun detection and signal labels is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

72

Instrumentation and Microcontrollers Using Automatic Code Generation

Next, run the FreeMASTER tool:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

73

We will go through a one-time setup for using the KL25Z boards with the SDA interface. Select Project and
then Options from the FreeMASTER menus. The Options dialog box will open. Select FreeMASTER BDM
Communication Plug-in (HCS08/12, ColdFire, Kinetis, PowerPC) as shown below:

Select FreeMASTER BDM Communication Plug-in


(HCS08/12, ColdFire, Kinetis, PowerPC)

Check this box so we dont have to do this again.

Next, click the Configure button and select the options P&E Kinetis and OpenSDA as shown below:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

74

Instrumentation and Microcontrollers Using Automatic Code Generation

P&E Kinetis selected.

OpenSDA selected.

Click the OK button to return to the main Options dialog box. The settings we have just specified will be saved
because we checked the box to save the settings as the default. The next few steps show how to display the
signals using the FreeMASTER tool. You will have to repeat these steps for every model that you wish to use
with FreeMASTER. Select the MAP Files tab:

Map Files tab selected.


Click here to locate your
.elf file.

Click the button as shown above to browse for a file. We are looking for a file that has a .elf extension.
When you build a model, the build process creates a .elf file that contains information about the signals in your
model. FreeMASTER will use this file to find the location of the signals of your model on the target. My model
was named Lab2_Project6.slx so the elf file will be named Lab2_Project6.elf. It should be in the current
directory that is being used by MATLAB. (Which is hopefully the same directory where your model has been
stored. Unless you changed directories and didnt go back to the directory where you model was stored.)
Select the .elf file for your model and then specify the format as Binary ELF with DWARF1 or DRARF2 dbg
format:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

75

Binary ELF with


DWARF1 or DRARF2
dbg format specified.

The .elf file for your


model specified here.

We have now made all of the changes, so click the OK button. To start communication, click the Start/Stop
Communication button
screen:

as shown below. Successful communication will be indicated at the bottom of the

Click here to start


communication.

This line indicates that


we are in communication
with the KL25Z board.

Right-click as shown below and then select Create New Watched Var

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

76

Instrumentation and Microcontrollers Using Automatic Code Generation

Right-click here.

Select this option.

The dialog box will allow us to create a new watched variable. Since we declared two external global signals,
these signals will be in the list of available signals to watch. In the Address box, select the signal we named
Pulse_Gen. Specify its Type as floating point IEEE (because this signal was of type double in our model),
and the Size as 8 bytes (because a double precision floating point number uses 8 bytes of data). Finally,
specify the Sampling period as fastest so we can see the data as fast as possible with the FreeMASTER
tool:
Fastest selected.
Pulse_Gen selected.

8 bytes selected.

Floating point IEEE selected.

Click the OK button. If you are in communication with your KL25Z target, the signal should be listed and the
value should change as it changes on the target:

Signal name.

Value should change in real-time.


Add the signal for the Counter_Value. When you are done viewing your target with the FreeMASTER, make
sure that you stop communication. If you attempt to build a new model while communication with the
FreeMASTER is active, the build will fail when it attempts to download the model. (You may need to wait a long
time or terminate MATLAB if this happens.)
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

77

Demo II.8: Demonstrate the FreeMASTER tool displaying the value of the Pulse_Gen and Counter_Value
signals.

3.
External Mode
External Mode is a Simulink tool that will allow us to view signals of our model in real-time as the model runs
on our target. It is similar to FreeMASTER but it has the added capability of allowing us to view the execution
of Stateflow charts. We will start with the previous model (Shown on page 72 and update it so that we can use
external model. To use external mode, we need to know which serial port the KL25Z is using. Run the
Windows Device Manager and identify the com port used by your KL25Z board 8:

My board is using COM7.

Next, we will set up our model to use External Mode. Select Simulation and then Model Configuration
Parameters from the Simulink menus. In the Solver pane, specify an end time of infinity. This means that
external mode will run until we stop it.

You can run the Device Manager by opening the Windows Control Panel and selecting the Device Manager, or by rightclicking on Computer, selecting Properties, and then selecting Device Manager.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

78

Instrumentation and Microcontrollers Using Automatic Code Generation

Stop time set to infinity.

Solver pane
selected.

Next, in the Code Generation pane, specify a Build configuration of Faster Runs:

Code Generation
pane selected.
Faster Runs
selected.

This option specifies that the generated code should run as fast as possible on the target. External Mode
generates a lot of overhead that will slow down the model execution and cause overruns. Specifying Faster
Runs will help prevent overruns and allow us to use external mode on models that would otherwise be to slow
to use external mode.
In the Interface pane, specify that we will use External Mode and specify that we will use the
serial port for communication:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

79

Interface pane
selected.
External Mode selected.

serial selected.
Com7 specified.

Note that in the MEX-file arguments, we specify 0 7. The 7 corresponds to the com port. Your COM port may
be different, so use the COM port you found with the Windows Device Manager. The 0 specifies that we will
use verbosity level 0. (This is not important for us.) We are done with these settings, so click the OK button.
We can now add blocks that will allow us to view signals on the model. Place a Display and a
Scope in your model. Both blocks are located in the Simulink / Sinks library:

External selected.
Stop time set to infinity.

Note that we have also selected External as shown above.


Next, select Code and then External Model Control Panel from the Simulink menus:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

80

Instrumentation and Microcontrollers Using Automatic Code Generation

Select the Signal & Triggering button and change the Duration to 1 and select the Select all option as
shown:
Option

Change to 1.

External Mode uses a lot of memory of which the KL25Z has a limited availability. To minimize data usage, the
Duration is set to 1. The Select all option specifies that we want to transfer data for all displays, scopes, and
charts in our model. Click the OK button twice to accept the changes.
Important Note!!! In the model above we are using PTA1 and PTA2 digital outputs. These two
outputs are used by the serial port USBRX and USBTX for communication during external mode. This conflict
will cause our models to hang and external mode communication to fail!

I used PTA1 and PTA2 for my


digital outputs. This will cause
the model to hang and
External Model communication
to fail. Change them!

I will change the two pins to PTC3 and PTC0 to avoid this conflict:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

81

New pins specified.

We need to make one last change to our model. Double click on the Scope block in your model to open the
scope:

Click here to change


the scope settings.

Click on the Parameters button as shown above to change the scope settings. Select the History tab and
uncheck the box as shown:

Box is unchecked.

This setting will tell the scope to save all of the data collected for the plot. (This data is saved in your laptops
memory, so memory capacity is not an issue.) Click the OK button to accept the changes.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

82

Instrumentation and Microcontrollers Using Automatic Code Generation


Build your model and download it to your KL25Z. After you model is downloaded, click on the

Connect to Target button

Stop time set to infinity.


Click on this button.

After a few moments, you will notice that the display changes as the pulse changes. Also note that the clock in
the lower right of your window also changes:

This value changes as the


pulse changes.

When connected to the


target in External Mode,
the time is displayed and
increases here.

If you open the Scope block you will see a plot similar to the one shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

83

Finally, if you open the chart, you will see an animation as it transitions from state to state:

To terminate External Mode, click on the Disonnect from Target button

. Do not click on the stop button:

Click here to terminate


External Mode.

One last note is in order. Many of the settings that we specified to enable External Mode can be specified with
a block called External Mode Setup. This block will be covered in Section III.C.4 on page 134.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

84

Instrumentation and Microcontrollers Using Automatic Code Generation

Demo II.9: Demo your model using External Mode. Show the operation of the Display block, the Scope Block,
and the Stateflow chart animation.

E.

Using Truth Tables to Implement Logic

Truth tables provide a convenient way to document and implement logic functions. They do not provide
memory the way a Stateflow chart does. However, they allow us to specify a large number of conditions and
allow us to manipulate combinations of those conditions. As a simple example, we will use the last model of
the up-down counter with the Stateflow chart and replace the Compare to Constant blocks with a truth table.
The Truth Table block is located in the Stateflow library:

Double-click on the Truth Table block to open it:

First we must add the input variable, which we will call Count. Select Add, Ports, and then Input from the
Truth Table menus:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

85

Specify the name of the variable as Count:

Click the OK button. We will have 8 outputs called Bit0, Bit1, Bit2, , Bit7. Use the same procedure but specify
the port as an output. When we placed the Truth Table, it had a default input parameter called u and a default
output parameter called y. We need to delete these. From the Truth Table menus, select Add and then Edit
Data/Ports:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

86

Instrumentation and Microcontrollers Using Automatic Code Generation

Delete these.

If you made a mistake,


like I did here, you can
fix your errors with this
window. I will change all
of the Bit signals to
outputs.

The Ports and Data Manager allows us to modify and delete any of the ports in the Truth Table. Delete the y
output and the u input and close the Port and Data Manager. If you made a mistake in defining the ports, you
can use the Ports and Data Manager to fix your errors. Next, we need to add rows and columns to our table:

Right-click here
to add a row.
We need 8.

Right-click here to
add a column. We
need 9.

Right-click here
to add a row.
We need 8.

After adding rows and columns, fill in the table as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

87

Note that the descriptions are plain English and for documentation only. We have simple conditions but they
can be more complex using logical AND (&&) and logical OR (||) constructs. Note that columns D1 through D9
are decisions. For example column D1 will be used if condition 1 is true and conditions 2 through 8 are false.
If these criteria are met, then Action 1 will be taken, which sets Bit1 to a one and all the other bits to a zero:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

88

Instrumentation and Microcontrollers Using Automatic Code Generation

If Condition 1 is
true (Count==0),
and all of the other
conditions are false,
then do Action row
1.

Action row 1.

Similarly for decision column D2, if Condition 2 is true and all of the other conditions are false, Action row 2
will be used:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

89

If Condition 2 is
true (Count==1),
and all of the
other conditions
are false, then do
Action row 2.

Action row 1.

The only other column that is a bit strange is decision column D9. Note that we have eight conditions and each
of those can be true or false. From Simulinks point of view, any of the conditions can be true or false
independent of the other conditions. This is not possible for our case because of the function of the counter,
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

90

Instrumentation and Microcontrollers Using Automatic Code Generation

but Truth Tables dont know the limitations of the inputs and the conditions. Since we have 8 conditions, and
any condition can either be true or false, there are 28 possible combinations of how those conditions can be
true or false. To cover them all, we would actually need 28 decision columns. Since we know that none of these
are possible for our counter, we can catch these all in decision column D9, which is the default decision if none
of the other decisions are true. Having all dashes means that if we have a combination of conditions that are
not covered by the decisions in D1 through D8, it will use D9, which specifies action 1. For our example, D9
should never occur. In practice, the default column can be used to catch an error and take appropriate action.
After saving the Truth Table, return to Simulink and resize the table and connect it as shown:

Note: Keep the LEDs wired up on your proto-board and use different I/O pins for the future portions of
the course. You will reuse the LEDs in some of the future labs.
Demo II.10: Demo the up-down ring counter using a counter implemented with the Stateflow chart and a truth
table as a decoder.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab II: Counters, Digital Input, Stateflow, Truth Tables

91

Exercise II.6: Modify the Truth Table from Demo II.10 to light up the odd numbered LEDs when the count is
odd and light up the even numbered LEDs when the count is even.
Exercise II.7: Modify the Truth Table from Demo II.10 so that two adjacent LEDs travel up and down the LED
display. Two LEDs must be illuminated at all times.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

III.

Analog Input, Sensors, Subsystems, and Lookup Tables

Lab III
Analog Input, Sensors, Subsystems, and Lookup
Tables

The FRDM-KL25Z Analog Input block uses an analog to digital converter to convert an analog voltage
between 0 and 3.3 V to a floating point number between 0 and 1. We will use the Analog Input for two
applications. The first is a linear control reference where we can specify a parameter with an analog input. The
second is to read analog sensors. Many sensors output an analog voltage, and we can read these sensors
with the analog input.

A discussion on analog and digital signals is appropriate. A digital input or output is a 1-bit
signal that can have two values. We can interpret these values as 0 or 1, true or false, high or low, cats or not
cats, or any anything where we have something or we do not have something. Electrically we represent these
values as a low voltage or a high voltage. Depending on how we build the logic gate, the low voltage range and
high voltage range differ. For the KL25Z with a 3.3 V power supply, the range of low voltages is from 0 to 1.15
V and the range of high voltages is 2.31 V to 3.3 V. Note that one of the benefits of using digital signals is
noise immunity. The range of low input voltages and the range of high input voltages give us what are referred
to as noise margins. For a low input signal of say 0 V, we can 1.15 V of noise and the input will still be
considered a low input. For a high input voltage of 3.3 V, we can still have -.99 V of noise and the input will still
be considered a high input. So, 0.1V, 0.2V, 0.7 V, 0.9 V, and any signal between 1.15 V are still considered to
have the same value of low. Likewise, any voltage between 2.31 V and 3.3 V have the same value of high.
This property makes a digital system very robust because of the noise immunity.
Analog signals have a limited range, but within that range, they can ideally have any value and
the difference between those values would be recognized by the processor. For our KL25Z, an analog signal
can be between 0 and 3.3V and 3.1415926 would be different than 3.1415927. However, the KL25Z has a 12bit analog-to-digital converter, so the resolution is (3.3 V)/(212) = 0.0008056640625 V per bit. Thus, in our
system 3.001 would be recognized as a different value than 3.002. However 3.0015 would either be rounded to
3.001 or 3.002. So, with analog signals we have basically a continuous range of values with some minimum
resolution. With digital signals, we have discrete levels. (For those of you that want to argue about it. When we
read the analog input with a 12-bit analog-to-digital converter, we are converting the signal to a representation
that has 212 or 4906 discrete levels.

A.

Analog Input Block

There are two Analog Input blocks, one in the RHIT library and one in the Embedded Coder Support Package
for the Freescale FRDM-KL25Z Board from MathWorks. The RHIT block allows you to use any of the 16
possible analog inputs and samples at the same rate as the model. (We will show how to use a different
sample rate later when we place the block inside a triggered subsystem.) The MathWorks block uses the
Arduino Uno compatible pins (A0 through A5) and allows you to specify a sample time. Except for the limitation
on the pins, the two blocks are basically equivalent. The first thing we will do is try to observe the output value
of the Analog Input blocks directly using FreeMASTER. Start with a model from Lab 1 and delete everything
except the flashing LED and overrun indication. Save it as Lab3_Project1:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

93

Add an Analog In block located in RHIT KL25Z Library / Basic Blocks to your model. Double-click on the
Analog In block and specify PTD6 as the Analog Pin. Wire the block to a terminator and then edit the
properties of the wire to name it Analog_In_Value and specify the Storage Class as ExportedGlobal:

Next, add an Analog Input block located in Embedded Coder Support Package for Freescale FRDMKL25Z Board / FRDM-KL25Z to your model. Double-click on the Analog Input block and specify A0 as the Pin
and set the Sample time to be 0.5 seconds. Note that our model has a fixed time step of 0.5 seconds, so both
blocks will sample at the same rate.

Wire the block to a terminator and then edit the properties of the wire to name it Analog_In_Value and specify
it as the Storage Class as ExportedGlobal:

Your complete model should look as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

94

Instrumentation and Microcontrollers Using Automatic Code Generation

Lastly, we need to provide an analog input voltage to pins A0 and PTD6. We will do this with a
potentiometer (pot). A potentiometer can be thought of as a variable voltage divider:
A
A
R1
10k

Pot

Equivalent circuit

R2
B
B

The potentiometer can be thought of as two variable resistors in the equivalent circuit provided that:
1 + 2 = 10
0 1 10
0 2 10

As we turn the knob/screw on the potentiometer, one resistor increases and the other decreases such that the
sum is constant. We will use the potentiometer in the circuit below:
+3.3 V

10k

Analog Input Block

The potentiometer center terminal will provide a 0 to 3.3 V signal that changes as we rotate the knob/wheel.
(The circuit is a variable voltage divider.) We will use this variable voltage as a test input to the Analog Input
blocks. Since the analog inputs of the KL25Z are high impedance, we can use the same potentiometer to
provide a signal for both analog inputs as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

95

+3.3 V

10k

Analog Input Block


Pin A0

Analog Input Block


Pin PTD6

Pictures showing a wiring example of the potentiometer are shown below:

The two outer


terminals of the pot
are connected to
power and ground.

Center terminal of the


pot is connected to
the two analog input
pins of the KL25Z.

Download and run the model on your KL25Z. We will use FreeMASTER to view the signals from the analog
input blocks. See Section II.D.2 on page 69 for instructions on using FreeMASTER. Display the signals named
Analog_In_Value and Analog_Input_Value. In FreeMASTER specify the data type as Floating Point IEEE with
a size of 4 bytes. (These signals are single-precision floating point data types. In our previous use of
FreeMASTER, we used double-precision floating point data types which use 8 bytes of data.) When
FreeMASTER displays the variables, they should have approximately the same value. The values should
change as you turn the thumbwheel on the pot and the values should have a range between 0 and 1:
This value will change
as you rotate the
thumbwheel on the
potentiometer.

Before continuing, you must terminate communication on the FreeMASTER tool. To stop communication, click
on the Start/Stop Communication button as shown on page 75.
Demo III.1: Show the operation of both types of analog input blocks with FreeMASTER.
1.
Data Types
To keep things simple, for most of this manual we will do everything in double precision floating-point
calculations. For non-ECE types, this basically means that we do not need to worry about number systems,
data representations, or loss of accuracy due to fixed bit lengths. The downside is that using double precision
calculations takes more time than single precision calculations, and a lot more time than integer calculations. If
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

96

Instrumentation and Microcontrollers Using Automatic Code Generation

we are looking to make our models run fast, then double precision is not the way to go. Also note that the
FRDM-KL25Z does not have native double precision calculations so the calculations are done in software
(which is why it is slow). However, using double precision makes the implementation easy for us, which is our
goal of using Simulink models in the first place.
a)
Number Systems
There are two kinds of engineers in this world, those who know binary and those who dont. That was a joke. If
you dont know binary, you probably didnt get it. This section is for the engineers that didnt get it.
Most of us are familiar with base 10 number systems. Valid digits are 0 through 9 (Hey! There
are 10 values!) The base is also referred to as the radix. An example is:

7384 = 7 103 + 3 102 + 8 101 + 4 100

Radix = 10

Note that the radix (or base as you might have learned it previously) is 10 in this example. Binary uses a radix
of 2. Examples are:

10110 = (1 24 ) + (0 23 ) + (1 22 ) + (1 21 ) + (0 20 )
Which can be rewritten as:

10110 = (1 16) + (0 8) + (1 4 ) + (1 2 ) + 0 = 22
Note that 10110 base 2 is equal to 22 base 10, or 101102=2210. We can also relate binary to base 10 using the
place value. In base 10 we have the 1s place, 10s place, 100s place (which is, by the way 100, 101, 102),
and so on. In binary, we have

Where 16s place is 24, 8s place is 23, 4s place is 22, 2s place is 21, and 1s place is 20.
Historically and physically our choice of 0 and 1 for a binary digit comes from switches which
can be on or off and digital logic circuits that recognize either a low voltage or a high voltage. Some
terminology is also appropriate at this point: A single binary digit is referred to as a bit. A group of 4 binary
digits is referred to as a nibble. (1011 1110) is two nibbles. A group of 8 binary digits is referred to as a byte
(10111110) is one byte. 1k (for digital guys) is 210 = 1024. 1M (for digital guys) is 1k * 1k = 210 *210= 1048576.
Since it sometimes takes a lot of bits to represent a quantity, bits are usually grouped into
groups of 3 (referred to as octal) or groups (referred to as hexadecimal). We will look at hexadecimal here. The
hexadecimal digits are:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

97

Binary

Hex

Decimal

Binary

Hex

Decimal

0000

1000

0001

1001

0010

1010

10

0011

1011

11

0100

1100

12

0101

1101

13

0110

1110

14

0111

1111

15

In decimal every digit can have ten values, 0 through 9. In hexadecimal each digit can have16
values ranging from 0 to 15. We need a single symbol for each digit! How do we do this with only 10 numeric
symbols in our mathematical vernacular. For hex numbers 0 through 9, use 0 through 9. For hex numbers 10
through 15, use letters A through F. Below are some representations of the number 74895 (base 10) in
different representations:

1011
0011

1101
0111
0110
B
D
6
7
3

B6 D 73 = (11 164 ) + (6 163 ) + (13 162 ) + (7 161 ) + (3 160 )


101101101101011100112 = B6 D 7316 = 74891510
So we see that hexadecimal is a short cut in representing large binary strings by grouping 4-bits into a single
hexadecimal digit.
Some useful MATLAB functions for converting between different representations. Bin2dec converts a binary
text string to a decimal number:
>> bin2dec('10110110110101110011')
ans =
748915
Dec2bin converts a decimal number to a binary text string:
>> dec2bin(748915)
ans =
10110110110101110011
Hex2dec Converts a hexadecimal string to a decimal number:
>> hex2dec('B6D73')
ans =
748915
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

98

Instrumentation and Microcontrollers Using Automatic Code Generation

Dec2hex Converts a decimal number to a hexadecimal text string:


>> dec2hex(748915)
ans =
B6D73
So now we have a question If we see a number like 123, how do we know if it is a
hexadecimal or decimal number? (It could actually be any base greater than 3, but we wont go there.) Ways of
indicating a number is a hexadecimal number:

hex 123 - saying it.


$123 - preceding the number with a $ sign.
x123 - preceding the number with an x which is short for hex.
12316 Indicating the base explicitly.

b)
Data Types in MATLAB and Simulink
There are tons of different data types in MATLAB and Simulink. We will only talk about a few
basic types here:

Boolean True or False (not 0 or 1 numerically)

Uint8 An unsigned 8-bit integer. It can represent values from 0 to 255.


111111112
= 27+26+25+24+23+22+21+20
= 28-1 = 25510

Uint16 An unsigned 16-bit integer. It can represent values from 0 to 65535.


11111111111111112
= 215+214+213+ + 22+21+20
= 216-1 = 6553510

Uint32 Unsigned 32-bit integer. Can represent values from 0 to 4294967295.


111111111111111111111111111111112
= 231+230+229+ + 22+21+20
= 232-1 = 429496729510

The uint8, uint16 and uint32 are unsigned numbers. There are three common ways of representing signed
numbers. With sign and magnitude, the most significant bit represents the sign. (1 is negative, 0 is positive),
so:

10001 would represent the number -1.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

99

11111 would represent the number -15.


00001 would represent the number 1.
01111 would represent the number +15.

With sign and magnitude representation there are an equal number of positive and negative values that can be
represented and there are two ways to represent 0:

1000000 negative zero!


0000000 positive 0!

We will not be using this method to represent signed integers.


A second method uses biased values. To calculate the numerical value of the code, calculate
the magnitude of the code and then subtract off a fixed bias. The example below uses 5-bit codes with a bias
of 15.

00000 value = 0 15 = -15


00001 value = 1 15 = -14
01111 value = 15 15 = 0
10000 value = 16 15 = 1
11111 value = 31 15 = 16

We will not use this method either. Instead, we will be using a method called twos complement to
represent positive and negative integers. With 2s complement, the most significant bit has a negative weight:
Note this (-) sign.

10110 = ( 1 24 ) + (0 23 ) + (1 22 ) + (1 21 ) + (0 20 )
= 16 + 6
= 10
and

00110 = ( 0 24 ) + (0 23 ) + (1 22 ) + (1 21 ) + (0 20 )
= 0+6
= 6

With 2s complement, if the most significant bit is a 1 the number is negative. If the most significant bit is a 0,
the number will be positive. Some examples are:

The most negative number is: 10000000 = -27 = -128

The most positive number is: 011111111 = 127

The code for -1 is: 111111111 = -27+127


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

100

Instrumentation and Microcontrollers Using Automatic Code Generation


There is only one representation for zero: 00000000.
MATLAB and Simulink use 2s compliment to represent signed integers. Some of the types are:
Int8 2s complement signed 8-bit integer. It can represent values from -128 to 127.
10000000 = -27 = -128
011111111 = 127
Int16 2s complement signed 16-bit integer. It can represent values from -32768 to 32767.
1000000000000000 = -215 = - 32768
0111111111111111 = 32767
Int32 2s complement signed 32-bit integer. Represents values from - 2147483648 to
2147483647.
10000000000000000000000000000000 = -231 = - 2147483648
01111111111111111111111111111111 = 2147483647

The MathWorks help facility has a good section on floating point numbers. The following few
pages were generated from the information contained in the MathWorks help facility. Search for the topic,
floating-point numbers in the MathWorks help facility to find more in-depth information 9.

Fixed-point numbers are limited in that they cannot simultaneously represent very large or very small numbers
using a reasonable word size. This limitation can be overcome by using scientific notation. With scientific
notation, you can dynamically place the binary point at a convenient location and use powers of the binary to
keep track of that location. Most of us are familiar with scientific notation. d is a decimal digit with values from 0

The information in this section is attributed to The MathWorks.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

101

to 9. We can move the decimal point right or left by decreasing or increasing the power of 10 by which we
multiply.

d .dddd 10 p
Decimal point.

= ddddd .0 10 p 4
= 0.ddddd 10 p +1

Binary numbers can have a fractional part just like decimal numbers:

73.84 = 7 101 + 3 100 + 8 101 + 4 102


Decimal point.

101.11 = (1 22 ) + (0 21 ) + (1 20 ) + (1 2 1 ) + (1 2 2 )

101.11 = (1 4 ) + (0 2 ) + (1 1) + (1 1 2 ) + (1 1 4 ) = 5.75

Binary point.

Radix point notation is similar. Here we show radix notation for binary (radix = 2). b is a binary digit with values
of 0 or 1.We can move the binary point right or left by decreasing or increasing the power of 2 by which we
multiply.

b.bbbb 2 p
Binary point.

= bbbbb.0 2 p 4
= 0.bbbbb 2 p +1

IEEE Floating Point Standard 754 uses the following convention for single precision:

( 1)s (2e127 ) (1. f ) ; normalised ,0 e 255, f 0

s
Value = ( 1) (2e126 ) (0. f ) ; denormalised , e = 0, f > 0
exceptional value

Exceptional values are not a number (NaN) and infinity (inf). An example of a floating point number using this
standard is:

1 10111101 10100000000000000000000

s
e
f
The sign, s = 1 we have a negative number.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

102

Instrumentation and Microcontrollers Using Automatic Code Generation

The exponent, e = 101111012=18910

The fractional part, f = 10100000000000000000000


1.f = 1.10100000000000000000000

e 127

) = (2

) (

189 127

) = (2 )

) (

62

) (

) (

) (

= 1 2 + 1 2 + 0 2 + 1 2 + 0 2 + 0 2 + ....
= 1.625
Putting it all together, our single precision floating point number is -1.62510 * 262 or -7.493989779944505 x 1018
in decimal.
The IEEE double precision floating point standard uses 64 bits:
0

( 1)s (2e1023 ) (1. f ) ; normalised ,0 e 2047, f 0

s
Value = ( 1) (2e1022 ) (0. f ) ; denormalised , e = 0, f > 0
exceptional value

Exceptional values are infinity (inf) and not a number (NaN). Infinity is defined as those values outside the
range of representable numbers. Any arithmetic operation involving infinity yields infinity. There are two types
of NaN. A signaling NaN signals an invalid operation exception. A quiet NaN propagates through almost every
arithmetic operation without signaling an exception. The following operations result in a NaN:

+
0
0/0
/
Exercise III.1: Determine the decimal value of the following bit string (it is 32 bits in length.)
10011100111011100110111000000011. Calculate the value of this string assuming the following data types:
(a) Uint32 (magnitude), (b) Int32 (2s complement), (c) sign and magnitude, (d) single precision floating point.
Optional - Create an m-file that displays all four results in a message box.
Exercise III.2: Determine the decimal value of the following bit string (it is 32 bits in length.)
01000000111010000110100000000011. Calculate the value of this string assuming the following data types:
(a) Uint32 (magnitude), (b) Int32 (2s complement), (c) sign and magnitude, (d) single precision floating point.
Optional - Create an m-file that displays all four results in a message box.
c)
Displaying Data Types in Simulink
What we will do here is use a facility to determine the data type of a signal, and if it is not a
double precision data type, convert it to double. In advanced courses, we will look at making calculations with
data types other than double precision. In our model, select Display, Signals & Ports, and then Port Data
Types to turn on the diagnostic:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

103

When you return to the model, type Ctrl-D to update the diagram. Since we enabled Port Data Types, the
data types should be displayed on the signal lines:

We see that the output of the Analog blocks are single precision floating point numbers (single). If we perform
calculations between a single and another data type, double for example, the result can be unpredictable. To
eliminate this possibility, we will convert the data type to double precision. Place a Data Type Conversion
block from the Simulink / Commonly Used Blocks library in your model as shown below. Open the block and
specify the Output data type as double. When you update the diagram, the output data type of the block
should be Double:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

104

Instrumentation and Microcontrollers Using Automatic Code Generation

The single and the double signals will have the same numerical values, just different representations. Now that
we have the value as a double precision representation, we can use it in calculations with other signals that
also have a double precision representation.
2.
Analog Voltmeter
We are now ready to use the Analog Input block in a circuit that does something more significant. In this case,
we will make an analog voltmeter where the output voltage is displayed by lighting up a number of LEDs in
proportion to the voltage. We will start with the up/down counter we demonstrated in Demo II.10. Open the
model and save it as Lab3_Project2. Delete the Stateflow chart and add the analog input we used in the
previous model. Do not forget the Data Type Conversion block. Change the Fixed-step size to 0.1 seconds
and specify the Discrete solver. Display port data types to make sure that all non-double data types are
converted to double:

The truth table was set up to check for an integer count between 0 and 7. We now have a number between 0
and 1. Modify the truth table as shown:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

105

Note that we added a new row and that the default decision chooses that row. The lights should illuminate
linearly as the input voltage increases. As the voltage becomes higher, more LEDs should turn on.
Demo III.2: Demonstrate the working linear analog voltmeter.
Exercise III.3: Modify the linear voltmeter of Demo III.2 to use a base-2 logarithmic scale. That is, the next LED
should only light up when the size of the signal doubles. This makes the bar graph very sensitive for small
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

106

Instrumentation and Microcontrollers Using Automatic Code Generation

signals and less sensitive for larger signals. Hint: Multiply the analog signal by 255 and remember your factors
of two (1, 2, 4, 8 ,16, etc)
3.
Sampling Time and Triggered Subsystems
In the MathWorks Analog Input block the sample time was specified by the sample time parameter in the block
setup. In the RHIT Analog In block, the sample rate was the same as the model fixed-step time. Typically, we
would like analog inputs to sample at a different rate than the fixed time step and at different rates from one
another. If we have multiple Analog input blocks in our model, it could be required that they sample their input
signals at a different sampling rate because different sensors will output signals at different frequencies. By
specifying different sampling rates, we can sample slowly varying signals less often (say a temperature sensor)
and quickly changing signals (say an accelerometer) more often. A sensor output has to change as fast as or
faster than the quantity it is measuring. As an example, a temperature signal may only change one degree in
several minutes or hours such as when we are measuring air temperature. A signal of this type does not need
to be sampled very often (low sample frequency). On the other hand, an accelerometer measuring the
acceleration of a vehicle as it accelerates and brakes must measure an event that happens in a few seconds.
Here sampling every 100 ms or so might be acceptable. This would be a 10 Hz sample frequency. And, if you
were measuring an audio frequency of 1 kHz with a microphone, corresponding to a period of 1 ms, you would
need to sample the signal faster than one 1 ms (a sampling frequency higher than 1 kHz). If you take a signal
processing course, you will learn that you have to sample a 1 kHz signal at 2 kHz or higher. Thus, the rate at
which you measure a signal from a sensor depends on the sensor you are using and the physical quantity you
are measuring.
We can also partition our model so that different portions execute at different speeds allowing us to
make more efficient use of the microcontroller. With the MathWorks Analog Input block, the sample rate is
specified in the block. For the RHIT Analog In block, we can place the block inside a triggered subsystem and
trigger the block as desired. This is a more general method that can be used to control the execution rate of
any group of blocks, not just the analog input block. Furthermore, triggered subsystems allow us to specify a
small fixed-step time. The small time step allows algorithms to run fast while the triggered subsystems allow us
to reduce the execution rate of specific portions of the model.
To illustrate a triggered subsystem and modifying the analog sampling rate, we will create a model that
uses a switch to select between two different analog inputs. One samples every 100 ms, the other every 1
second. First, change the fixed-step size to 0.01 seconds. This will allow our model to run quickly:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

107

Fixed-step size set to 0.01


seconds.

Next create the model below. Instead of analog input blocks we have added a switch and two edge triggered
subsystems (part Simulink / Ports and Subsystems / Triggered Subsystem)

The subsystems are positive edge triggered. The contents of the subsystem only execute when they receive a
positive edge. This edge can be used to control how often a set of blocks execute, or make the execution
conditional. (We can even choose not to execute a set of blocks) For now, both subsystems are triggered by
a pulse generator which produces a set frequency pulse. In this way, we can control the frequency at which a
set of blocks executes. The top pulse generator has a Period of 0.1 seconds and a Pulse Width of 50%:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

108

Instrumentation and Microcontrollers Using Automatic Code Generation

The bottom pulse generator has a period of 1 second and a pulse width of 50%. Thus, the top subsystem will
execute at a rate 10 times faster than the bottom triggered subsystem. A switch and a digital input (connected
to a pushbutton on your proto-board) will select between the two triggered subsystems.
If you double-click on the triggered subsystem, you can open the block and see its contents.
Modify the top triggered subsystem to contain the blocks shown below:

Notice that this subsystem reads an analog input on pin PTD6 and then converts the data type to a double
precision floating point number. The bottom triggered subsystem contains a similar set of blocks:

This subsystem reads the analog input on pin PTB0 (which happens to be the same pin as A0 used in the
previous model, so no rewiring is required.)
The complete top-level model is shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

109

Both analog inputs are connected to the same potentiometer. When the slow input is chosen by pressing the
pushbutton, there is a large delay between when the input changes and the LEDs respond. When the
pushbutton is not depressed, the LEDs respond quickly to a change in the input. Although this model is not all
that profound, you should always choose an appropriate sampling rate for the signal you are measuring.
Note in the model above that we always use a flashing LED to let us know that the model is
operating and we always use the overrun detection LED to alert us to an overrun. Ideally, we should never
have an overrun.
Demo III.3: Demonstrate the working linear analog voltmeter with different sampling rates.

B.

Temperature Sensor

As an example of a sensor, we will measure the rooms temperature using a thermistor. A thermistor is a
resistor whos resistance varies with temperature. It is a two-terminal passive device, just like a resistor, and
you will wire it in your circuit as if it was a resistor. Thermistors come with positive or negative temperature
coefficients (PTC or NTC). With a positive temperature coefficient a thermistors resistance will increase with
temperature. For a negative coefficient, the resistance goes down as temperature increases. For this example,
we want the sensor voltage to increase as temperature increases. We can use one of the two circuits below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

110

Instrumentation and Microcontrollers Using Automatic Code Generation


+3.3 V

+3.3 V

R
Vo

PTC
Thermistor

NTC
Thermistor
Vo

Use the appropriate circuit for the thermistor you have. We will use a resistor that is equal in value to the value
of the resistance of the thermistor. My thermistors have a room temperature resistance of 10 k, so I will use a
resistance of 10 k. We will first use Simulink with FreeMASTER so that we can see the output of the sensor.
We will use the model shown below:

The triggered subsystem contains the blocks below:

The pulse generator has a period of 1 second to sample the temperature slowly and the fixed-size step was set
to 0.01 seconds to allow the model to react quickly. (We dont need a fast response just yet.). What we see is
that the temperature sensor does change its voltage with temperature, but it does not vary greatly and certainly
does not use the full range of 0 to 3.3 V available to the Analog Input block. The way to fix this limited voltage
range in order to get the most accuracy would be to use an analog circuit to convert the sensor voltage to 0 to
3.3 volts and take advantage of the full range of analog to digital converter input. This is beyond the scope of
this class. Here, however, we will fix the problem with Simulink. Before we do this, we will generate a plot of
the values produced by sensor. We will let the sensor sit at room temperature for a while, and then warm it up
by heating it with a hair dryer or some other heat source. We will use plotting capabilities of FreeMASTER to
generate a plot of the sensor output.
We will now generate a plot with FreeMASTER. We will assume that you have already
completed the previous section and the signal Temp_Sens_Analog_Out has been added to the Variable watch
list in FreeMASTER. Right-click on New Project as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

111

Right-click here.

Select Create Scope and then fill in the dialog box as shown:

Name the plot here.

The plot will display one


minute of data.

Select the Setup tab:


Setup tab selected.

Your watched variables are listed here.

Select variable Temp_Sens_Analog_Out and specify the voltage range as 0.4 to 0.6:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

112

Instrumentation and Microcontrollers Using Automatic Code Generation

Axis limits specified here.

Variables listed here.

Select the variable here.

Click the OK button:

Plot listed here.


Click here to display the
plot.

Click on the plot as shown above to display the plot. If your communication is established, you will see a plot
similar to the one below as you heat and cool the sensor:

The sensor only uses a small portion of the converter range. To fix this problem, we will do the following. We
will sample the sensor when we first start our controller. We will use this value as a baseline. We will then
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

113

subtract this value from the real-time temperature measurement to generate a value that is the difference in
temperature from the baseline. We will then amplify this difference so that it lights up all the LEDs over a
specified range. When cold, no LEDs will illuminate. When we heat the sensor with a hair dryer, eventually all
the lights will illuminate.
1.
Triggered Subsystems
We can sample the sensor at start-up by using a triggered subsystem. By default, all blocks in our models
execute once every fixed time step unless we place them inside a triggered subsystem. We are using a
triggered subsystem to control the sample rate for our analog input which is sampled repeatedly at a constant
frequency. We can also use a triggered subsystem to trigger a block at other times when we want to perform
specific operations at certain times. For this example, we want to record the temperature once at start-up. The
blocks within the subsystem only execute when the subsystem is triggered. Place a Triggered Subsystem
and Step in your model as shown:

Note that by default, this subsystem is triggered by a rising edge. We will use a step function to trigger this
subsystem. Note that the default settings of the Step is that the output is initially zero, and then increases
abruptly to a value of one at a time of one second (a unit step at a time of one second). Also note that the
Sample Time of the Step block is specified as 0:

0 specifies continuous time.


Change this to -1.

A Sample time of zero designates the block as a continuous time block, which cannot be used in a fixed-step
size system. This will generate an error when we build the model. To fix the model, change the Sample Time
to -1 which means it will have an inherited sample time. With an inherited sample time, the blocks sample time
is set to the sample time of the block in which it resides. For example, if the step was inside a subsystem, its
sample time would be the same as the subsystems sample time. This Step block is in the top level of the
model and thus it has a sample time that is the same as the fixed-step size of the model.
Since the Step function stays at 1 forever after the initial step, the Triggered Subsystem is only triggered
once. We will not place anything inside the Triggered Subsystem:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

114

Instrumentation and Microcontrollers Using Automatic Code Generation

When the subsystem triggers, the output will be set to the input at the moment of the trigger. After that, the
output of the Triggered Subsystem will hold the output value until it receives another trigger. Since a step
provides one positive edge, the subsystem will hold the value until we restart the microcontroller.
Next, we will subtract the reference from the measured signal to create a signal that starts at
zero and then increases as the temperature goes up. The signal will also become negative when the
temperature goes below the reference. (Use a Sum block and change its properties.) Finally, we will add a
gain block to amplify the difference so that we can light up all of the LEDs:

To test this sensor signal conditioning model, we will plot the three signals on a scope using the FreeMASTER.
Note that we have labeled three signals Temp_Sens_Analog_Out, Temp_Sens_Initial_Value, and
Temp_Difference. All of these signals are declared as ExportedGlobal so that we can view them with
FreeMASTER. Build and download the model. Run FreeMASTER and add the three signals as watched
variables:

Use the method discussed on pages 110 to 112 to create a plot. The Main tab for scope properties is shown
below and is similar to our previous plot:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

115

The Setup tab now has three variables plotted. Two are on one plot, and the third variable is plotted on a
separate plot:

Setting up the window as shown takes a few steps, so we will go through it carefully. First, use the pull down
menu to select variable Temp_Sens_Analog_Out

Temp_Sens_Analog
_Out should appear
here.

Note that BLOCK0


should have been
selected by default.

Select Temp_Sens_Analog_Out here.

Next, click as shown below:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

116

Instrumentation and Microcontrollers Using Automatic Code Generation

Click here. It should


become highlighted
as shown.

After highlighting the line shown above, select variable Temp_Sense_Initial_Value:

BLOCK0 still
selected.

Temp_Sense_Initial
_Value should appear
here.

Select Temp_Sense_Initial_Value here.

The last thing we need to do is specify the signal range for BLOCK0. Specify the range as 0.4 to 0.6 as shown:

Range specified
here.

BLOCK0 still
selected.

Lastly, hold down the CTRL key and select the two variables and BLOCK 0 to select all three:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

117

Block selected.

Both variables
selected.

After selecting the three


items, click here.

Click on the Assign vars to block button as shown above. After clicking on the button, your window should
appear as shown:

We are now done with BLOCK0. Select BLOCK1 as shown below and select an empty variable slot:

Block1 selected.

Empty variable slot


selected.

Select variable Temp_Difference and then specify the axis range of -1 to 1:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

118

Instrumentation and Microcontrollers Using Automatic Code Generation

Range specified
here.
Variable
added.
BLOCK1 still
selected.

Finally, Click the Assign vars to block button. Your window should appear as shown:

We are done setting up the plot. Click the OK button. Start communication and select the plot:

Plot selected.

Temp_Sens_Initial_Value

Temp_Sens_Analog
_Out

Temp_Difference

Demo III.4: Demonstrate the FreeMASTER tool displaying the three signals from the thermistor sensor circuit.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

119

2.
Temperature Meter
We are now ready to connect our sensor to the Analog Voltmeter developed earlier:

Adjust the value of the gain block so that all 8 LEDs will illuminate when the sensor reads the maximum
temperature that your heating source provides. (Your gain will not be 10.)
The last thing we will do is clean up our model by placing all of the blocks that contain the
sensor signal in their own subsystem. Select all of the blocks used in creating the temperature sensor signal:

Next, right-click on the selection and select Create Subsystem from Selection from the menus:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

120

Instrumentation and Microcontrollers Using Automatic Code Generation

The selected blocks will be placed in a subsystem. Rename the subsystem Temperature Sensor:

If you look inside the Temperature Sensor subsystem, you will see the selected blocks:

Demo III.5: Demonstrate the working linear temperature meter.


Exercise III.4: Modify the temperature meter so that when it zeros out, 4 LEDs are illuminated. Then when the
sensor is warmed up to the maximum temperature, all 8 LEDs are illuminated. If the sensor becomes colder
than the reference, less than 4 LEDs are illuminated. This is essentially a sensor that indicates temperatures
both above and below the reference point.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

121

Exercise III.5: Modify the temperature meter of Demo III.5 to use a pushbutton to sample the temperature
rather than the step source. This will allow the user to zero the meter at any time, rather than zeroing the meter
automatically at power-up.
Exercise III.6: Modify the temperature meter of Demo III.5 to use a pushbutton and the step source to sample
the temperature. This will automatically zero the meter at power up as well as allow the user to zero the meter
at any time.

C.

Lookup Tables

The last project we will do in this lab is to make a variable speed up-down counter whose counting frequency
varies linearly with the analog input from 1 Hz to 10 Hz. We will do this by making a ramp and square wave
whose frequency is dependent on the input voltage. The only problem is that our analog input voltage is
interpreted as a number between 0 and 1 and we want to map this to a number between 1 and 10. We could
do this with an algebraic function using the Simulink Fcn, MATLAB Function, or Polynomial blocks or other
Simulink primitive blocks. Instead, we will use a lookup table to map the input values to the needed output
range.
1.
Stateflow Charts with Events
We will start with the model of the up-down counter that was implemented with a state flow chart and
truth table (Demo II.10) Open the model, and save it as Lab3_Project7. This model uses a Stateflow chart that
executes at the fixed-step rate, 0.5 seconds in this model. This is because the chart has no event triggers. We
will add an event so that we can control how often the chart executes.

Open the chart and then select Chart, Add Inputs & Outputs, and then Event Input From Simulink.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

122

Instrumentation and Microcontrollers Using Automatic Code Generation

Name the event Clock:

Click the OK button to return to the Stateflow chart. Then switch to the Simulink model. You will notice that the
Stateflow chart now has an event input at the top:
Event input.

We also notice that the event is positive-edge triggered. Every time the input has a rising edge, the Stateflow
chart will execute. We will provide a square-wave input for the Clock event, and change its frequency to see
how the model reacts.
Since we will be trying frequencies between 1 and 10 Hz, we need a smaller fixed-time step.
Change the Fixed-time step to 0.01 seconds (Simulation, Model Configuration Parameters). Also specify a
discreet solver. Finally, add a Pulse Generator and specify the Amplitude as 1, Period as 1, and Pulse
Width as 50 percent. Connect the Pulse Generator to the Event input of the chart:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

123

Verify that you can change the speed of the counter by changing the frequency of the pulse generator.
2.
Integrators, Timing, and Signal Generators
There are several ways to generate timing functions in Simulink: (1) We can use the Stateflow temporal
commands (after, before, at, every, etc). (2) We can use some of the Simulink sources and specify a sample
time for the sources. (3) We can use Stateflow and count a number of events that occur. Instead, we will use
math and, on the way, generate a triangle wave and a square wave.

The integral of a constant is a ramp, = ( ). This is the equation of a straight line of slope

a. If a is a positive constant, then the ramp increases at a rate of a. If a is a negative constant, then the ramp
decreases at a rate of a (or -|a|). We will start by creating a ramp of slope 2 by integrating a constant value of
2. The ramp will start at zero and then integrate positive. When the ramp hits a value of 1, we will change the
input of the integrator to -2 so that the integrator ramps down. When the ramps hits zero, we will again change
the input to +2 and ramp up once again. This process will repeat indefinitely. For the integrator we will use a
discrete integrator because we are using a discrete solver. Note that integration can take a lot of computation
time. We chose a discrete solver to make the models execute as fast as possible and high accuracy on a this
ramp generator is not necessary. We will use a Stateflow chart to toggle the ramp and output at 1 and -1 as
needed. The added blocks are shown below:

The settings of the integrator are shown below:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

124

Instrumentation and Microcontrollers Using Automatic Code Generation

The Gain is set to one which means that the output is just the time integral of the input. The initial condition is
zero which means that the ramp starts at zero. The Stateflow chart is shown below:

The reason we have a slope of two instead of 1 is because we wish to generate a frequency of 1 Hz, which
means that the ramp has to integrate up to 1 in second and integrate back down to zero in second. To
verify that this portion of the model works, we can simulate it in Simulink as a separate model:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

125

See pages 134-136 for the steps to display two plots on a screen. To make a variable frequency signal
generator, all we need to do is vary the input to the integrator as shown:

Simulation shows that the frequency is now three times faster:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

126

Instrumentation and Microcontrollers Using Automatic Code Generation

As a check, place this portion into the full model, and then verify its operation using FreeMASTER:

Demo III.6: Demonstrate that the up-down counter can vary between a counting frequency of 1 and 10 Hz by
changing the value of the constant.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

127

3.
Tuning Variables with FreeMASTER
In previous examples we were able to view signal values on the KL25Z with FreeMASTER as the
model was running in real-time. FreeMASTER also has the ability to change the values of some of the model
blocks in real-time as well. This feature gives us the ability to tune model parameters to achieve a desired
response as the model is running. As an example, we will change the value of the constant that determines the
clock frequency in the previous example. We will also add a gain block to show that we can tune the gain value
as well. In the previous model, change the value of the constant block to Const_Param. Instead of specifying
a numerical value for the constant, we use the parameter called Const_Param. We will define this parameter
later. However, since we are using a parameter, we can change the value with FreeMASTER. Also add a gain
block and specify the value of the gain to be Gain_Param. Then label the signals as shown. Make sure that
you specify the storage class of the signals as ExportedGlobal. (See Section II.D.2 on page 69 for specifying
signal names and properties.) The modified area of the model is shown below:
Value of this constant
block is specified as
Constant_Param.

This signal is labeled and the


storage class is specified as
Exported Global.

Value of this gain


block is specified as
Gain_Param.

Signal label added here.

Signal label added

We have shown previously how to label signal wires, change their properties, and view the
signals on FreeMASTER. Here we want to show how to change the value of the Constant and Gain blocks.
The next thing we need to do is define the parameters Const_Param and Gain_Parameter. This is done with
the Model Explorer. To open the Model Explorer, click on the Model Explorer icon
select View, Model Explorer, and then Model Explorer from the Simulink menus:

, type CTRL-H, or

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

128

Instrumentation and Microcontrollers Using Automatic Code Generation

The model explorer will open:

Click the left mouse button on Base Workspace to select the Base Workspace:

Click here.

We note that there are


no parameters listed
here.

We see that there are no parameters listed in the base workspace. We will add them now. Select Add and
then Simulink Parameter from the Model Explorer window:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

129

A new parameter will show up in the Base Workspace:

Base
Workspace
selected.

Left-click
here.

Parameter
added.

Left-click on the text Param as shown above to edit the name of the parameter. Change the name to
Const_Param as shown below. Also change the Value to 1, the Data Type to double, the Minimum to 0.1,
the Maximum to 100, and the Storage Class to ExportedGlobal:

Name
changed
here.

Values
changed
here.

Repeat the procedure to add the parameter named Gain_Param:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

130

Instrumentation and Microcontrollers Using Automatic Code Generation

We are now done with the Model Explorer, so you can close it. Open the MATLAB window. You will notice that
the two parameters we defined are listed in the workspace:

Parameters listed here.

These parameters are not saved with the model. To save the parameters, type save Lab3_Project8 at the
MATLAB command prompt. The parameters we just created will be saved in a file named Lab3_Project8.mat.
Note that all variables that were defined in your workspace will also be saved in this file. We can now define
these parameters in the future by repeating the process we covered earlier or by loading this file. Next, we will
set up the Simulink model to automatically load this file each time we run the model. Open the Simulink model
and select File, Model Properties, and then Model Properties:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

131

In the dialog box that appears, select the Callbacks tab and then select the InitFcn item. Add the text
load('Lab3_Project8.mat') as shown:

Callbacks tab
selected.

InitFcn selected.

Line added.

Every time the model executes, the commands in the InitFcn window will execute. For our model, the
parameters that are saved in the .mat file will be loaded each time the model is built, having the effect of
initializing the variables. Click the OK button to save the changes. Save your model and then build and
download it to the KL25Z target.
Run FreeMASTER and add the variables Const_Val, Ramp_Signal, and Clock_Signal to the list of Watched
Variables. Generate plots for Ramp_Signal and Clock Signal:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

132

Instrumentation and Microcontrollers Using Automatic Code Generation

We have added watched variables and plots previously. We will now show how to change the value of the
parameters as the model is running. Create a new watched variable for Const_Param. Set the options as
shown:

Next, select the Modifying tab and specify the options listed below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

133

Option
selected.

Option
selected.

The selections allow us to change the value of the global parameters after we enter a new value and press the
Enter key. Click the OK button. If you change the value of the parameter, you will notice that the frequency of
the ramp and clock changes as you change the value of Const_Param:

Const_Param = 1.
Const_Param = 5.

Const_Param = 10.

Change the value of Const_Param here.

In a similar fashion, add watched variable Gain_Param and specify that it can be modified. As you change its
value, the size of the ramp will change:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

134

Instrumentation and Microcontrollers Using Automatic Code Generation

Gain = 2.

Gain = 5.

Gain = 1.

Demo III.7: Demonstrate the operation of the variable speed counter using FreeMASTER to change the speed
of the counter and magnitude of the ramp in real-time.
4.
Tuning Variables in External Mode
We will now use External Mode to tune parameters in the model and a Scope block to view
signals graphically. This offers the similar utility as we found using the FreeMASTER except that it is a little
easier to setup. We will start with the previous model and change the gain on constant values to a numerical
value. In the last example, we used Simulink parameters. We have also added a Scope block to the model
(located in library Simulink / Sinks):
Value
changed to 1.

Value
changed to 1.

Scope block
added.

Double-click on the Scope to edit its properties:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

135

Click here.

Click on the parameters button

to edit the scope parameters. Set the Number of axes to 2:

Number of axes set to 2.

Next, select the History tab as uncheck Limit data points to last 5000:
2.5

This box is unchecked.

Click the OK button. You will notice that the scope now has two plots:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

136

Instrumentation and Microcontrollers Using Automatic Code Generation

When you return to the model, you will notice that the Scope block now has two inputs. Connect these inputs
as shown:

Next, we need to set up the model to run in external mode. In Section II.D.3 we specified the setting manually.
Here, we will place a block called External Mode Setup in our model. This block is located in RHIT KL25Z
Library / Miscellaneous Functions:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

137

The block reminds us that External Mode uses pins PTA1 and PTA2, so if you model uses those pins, you
need to select different pins for those blocks. Communication is through the COM port, so you need to use the
Windows Device Manager to determine which COM port you KL25Z is using. Run the Windows Device
Manager and identify the com port used by your KL25Z board:

My board is using COM7.

Open the External Mode Setup block and change your port to the appropriate one. Make sure that you enable
external mode and log all of the signals:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

138

Instrumentation and Microcontrollers Using Automatic Code Generation

Click the OK button. Next, select External as shown below:

The disadvantage to using External Mode is that there is a lot of communication between the
target and your Windows computer which limits the fixed step size of the model you can use. In order to view
the plots, we need to increase the step Size. When we used FreeMASTER, we had a Fixed-step size of 0.001
seconds. This is much too small to use with a scope in external mode so change the Fixed-step size to 0.1
seconds as shown below:

Stop time set to infinity.

Fixed-step size set to 0.1.

Build your model and download it to your KL25Z. After you model is downloaded, click on the
Connect to Target button

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

139

Click on this button.

After a few moments, you will notice that the clock in the lower right of your window changes:

Stop time set to infinity.

When connected to the target in


External Mode, the time is displayed
and increases here.

If you open the Scope block you will see a plot similar to the one shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

140

Instrumentation and Microcontrollers Using Automatic Code Generation

The jagged steps are because we have a fixed step size of 0.1 seconds. With a fixed step of 0.001 seconds,
as we had in the original model, the ramp would look straight. However, we cannot use this small step size with
External Mode.
If you open Stateflow chart1, you can see it change states as the chart walks through the logic. Note that it flips
when the ramp reaches 0 and 1:

We have seen the Stateflow chart and Scope in previous External Mode demonstrations. Here,
we want to show that we can tune blocks in the model in real-time as the model is running. First, we will
change the value of the Constant. Double-click on the Constant block and change its value from 1 to 2.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

141

Change the value of


this constant while the
model is running in
External Mode.

After you change the value of the constant to 2, you will notice that the slope of the ramp increases:

Constant changed to 2 at this point.

Next, change the constant to 0.5:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

142

Instrumentation and Microcontrollers Using Automatic Code Generation

We can change several other model parameters. For the next example, change the gain from 1 to 2:
Change the value of this Gain
block while the model is running
in External Mode.

After entering the new value, you should see the amplitude of the ramp change:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

To terminate External Mode, click on the Disonnect to Target button

143

. Do not click on the stop button:

Click here to terminate


External Mode.

Demo III.8: Demonstrate the operation of the variable speed counter using External Mode to change the speed
of the counter and magnitude of the ramp in real-time. Show plots on the scope and show the animation of the
Stateflow charts.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

144

Instrumentation and Microcontrollers Using Automatic Code Generation

5.
Lookup Tables
The last thing we need to do is to replace the constant block by a set of blocks that reads the analog input and
scales that value to a range of 1 to 10. If you recall, the Analog Input block reads an analog voltage between 0
and 3.3 V and outputs a number from 0 to 1. We need to scale this output linearly to a range of 1 to 10. We
could do this by implementing the function = 9 + 1 in many different ways in Simulink. Examples are
shown below:

Instead of using one of these methods, we will use a lookup table. With a lookup table, a set of input and
output points are specified. The points are connected by straight-line segments. If the input matches a point,
then the output is set to the output coordinate of the point. If the input is between points, then linear
interpolation is used to approximate the output between the points. (Basically, a point on the straight line
connecting the two data points.) Lookup tables are typically used to model measured data. For example, a
torque curve measured from an electric motor. The lookup table would contain data of output torque versus
input rpm. An example lookup table of this type I shown below:

Max Torque Versus rpm


400

350

300

Torque (Nm)

250

200

150

100

50

0
0

1000

2000

3000

4000

5000

6000

7000

rpm

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

145

Data like this is usually provided by manufactures and can be easily used in a Simulink model with a lookup
table. In this example we are using the lookup table to implement a straight line with specific end points. In
general, lookup tables are a way to include complex measured data in your models.
Lookup tables can contain many points or just a few, depending on the complexity of the function you
want to model or the amount of measured data. Most lookup tables are used to represent data that is highly
nonlinear or very hard to represent mathematically. Our lookup table is straight forward. We have two points
connected by a straight line. The input ranges from 0 to 1 (represented by a vector [0 1]), and the
corresponding output is 1 to 10 (represented by a vector [1 10]).
Place a 1-D Lookup Table in your model. Double-click on the lookup table and fill it in a shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

146

Instrumentation and Microcontrollers Using Automatic Code Generation

The Table data is the vector of output values and the Breakpoints is the vector of input values. If you think of
these vectors as coordinates on the x-y plane with y being the output and x being the input, then we are
specifying two points, (0,1) and (1,10). If the input is between 0 and 1, then the output is calculated along the
straight line connecting the two points. The Interpolation method specifies that if the input is between the two
points, a linear approximation (straight line) should be used to calculate the value of the output. The
Extrapolation method specifies what should happen if the input is outside the range of 0 and 1. The chosen
options specify that if we are outside the range, the endpoint values should be used. When you click the OK
button, a plot of the data points will be displayed on the block. Notice that it is a straight line:

6.
Variable Speed Ring Counter
We are now ready to test the entire model. The fixed-step size should be set to 0.01 seconds. The complete
model is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab III: Analog Input, Sensors, Subsystems, and Lookup Tables

147

Demo III.9: Demonstrate the operation of the variable-speed up-down counter.


Exercise III.7: Create a model that switches between three modes of operation for the up-down counter. When
you push and release a pushbutton, the mode of operation changes. The three modes are: (1) constant 1 Hz
frequency, (2) constant 5 Hz Frequency, and (3) Variable frequency between 1 and 10 Hz based on an analog
input.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

IV.

Analog Output (PWM and DAC)

Lab IV
Analog Output (PWM and DAC)

The FRDM-KL25Z has two methods to generate an analog output voltage. The KL25Z has a digital to analog
converter (DAC) that can output a high quality analog signal to pin PTE30. This is a very easy way to produce
an arbitrary waveform, but we are limited to a single output. The KL25Z has 27 pins that can produce a pulsewidth modulation (PWM) waveform that can be used for many different purposes including the generation
analog output voltages. An external low-pass filter is required to convert the PWM waveform to an analog
output voltage. The benefits of this method are that it is inexpensive to implement on a microcontroller, so
there are many PWM outputs on the FRDM-KL25Z. Another benefit is that many devices can be directly
controlled with a PWM output (provided you add a high current driver) and do not require a low-pass filter.
These devices are typically slow and respond to the average of the PWM waveform. Examples are motors that
have a large inertia and incandescent light bulbs. The down side of using PWM outputs is that if you want a
true analog output voltage, the cutoff frequency of the low-pass filter must be well below PWM frequency,
placing an upper limit on the frequency of the desired analog output.

A.

KL25Z DAC Output

We will first generate waveforms with the KL25Z DAC which is connected to pin PTE30. The block accepts an
input from 0 to 1 which produces an output voltage between 0 and 3.3 volts. As a first example, we will
generate a 10 Hz sine wave output with the model shown below. (Important note: If you start a new project
for this example, create the new project using the procedure shown in Section I.C.) The Analog Output
block is located in the Embedded Coder Support Package for Freescale FRDM-KL25Z Board / FRDMKL25Z library:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

149

The settings for the sine wave are:

The Bias of 0.5 gives the sine wave an offset of the 0.5. The output of this block will be 0.5 + 0.5 sin(210).
Since the sine wave goes from -0.5 to + 0.5, the output of the block will be from 0 to 1. Since the sample time
was set to -1, the block will use the same sample time as specified by the fixed time step for the model.
To get a nice sine wave output we will need a small fixed-step size. Type CTRL-E and specify
the Fixed-step size as 0.0002 as shown. This is the smallest fixed-step size we can use with the KL25Z
without having an overrun:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

150

Instrumentation and Microcontrollers Using Automatic Code Generation

Download and run your model. Connect pin PTE30 to an oscilloscope as shown below:
Scope probe connection
KL25Z analog output.
Scope probe connection
KL25Z ground.

Scope probe connection to


the oscilloscope.

Try pressing the Auto Set button on the scope controls to see if it displays the waveforms shown below. If it
does not, set the volts per division for Channel A to 500 mV/div and the time per division to 20 s/div:

High frequency noise


spikes.

High frequency noise.

We see that the output has some high frequency noise that we will remove with a low-pass filter later. For now
we see that the waveform has a frequency of 10 Hz, a peak-to-peak voltage of 3.42 V, a minimum voltage
close to zero, and a maximum voltage of 3.26 V. These values will change slightly when we use a filter to
remove the noise. Note that the noise spikes occur more frequently and are therefore at a higher frequency
than the signal. We see two types of noise. One is the spikes which may come from the digital switching of the
DAC. Since these spikes are very narrow, they contain very high frequencies. The other noise we see is the
small hash which is most noticeable at the peaks of the 10 Hz sine wave. This is high frequency noise that
we might be picking up from the power supply or the environment. In either case, the noise is a part of the
signal we do not want.
Next, change the frequency to 100 Hz and observe the output:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

151

We can easily see the effect of the fixed step size. If you zoom in, you will see that each flat step is 0.0002
seconds (200 s) long:

Cursor X1

Cursor X2

Step size
is 200 s.

Since a step size of 200 s is the smallest fixed step size we can have on the KL25Z, this places a limitation
on the frequencies we can produce. For example, increase the sine wave frequency to 500 Hz. Note that the
period of this waveform is 2 ms so one cycle of the sine wave will be broken into 10 time slices:

This is not exactly a nice looking sine wave. Change your model back to displaying a 10 Hz sine wave:
We will now use the low-pass filter below to remove the high frequency noise we saw on the
waveforms:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

152

Instrumentation and Microcontrollers Using Automatic Code Generation

R
+

+
Filtered Output

Pin PTE30 In

This is a first-order low-pass filter with a cutoff frequency of = 12 . In the example below, the cutoff
frequency is approximately 5 Hz.

Low-Pass Filter Response


0
-5
-10

FC

-15

Gain (dB)

-20
-25
-30
-35
-40
-45
-50
-2
10

10

-1

10

10

10

10

Frequency (Hz)

We want to pass our frequency of 10 Hz and attenuate the high frequency noise. To do this, we need to
choose FC much higher that 10 Hz and much lower than the noise. Luckily, the noise is very high frequency
(very narrow pulses are high frequency). We will choose FC =1000 Hz, a factor of 100 higher than our signal.
Choose C=10 nF and R = 16 k. In general we want resistors in the k range so that the filter will not draw a
lot of current. We like capacitors in the F or nF range so that they are small and inexpensive. Measure the
output of your filter with the oscilloscope:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

153

Demo IV.1: Demo the DAC output for a 10 Hz sine wave.


Exercise IV.1: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 10 Hz, (2) a sine wave at 100 Hz, (3) a 10 Hz saw tooth, and (4) a 10 Hz triangle wave. All waveforms
have 1 V in amplitude. Demo with an oscilloscope monitoring the output. Use the Analog Output block to
generate the waveforms.

B.

Pulse-Width Modulation (PWM)

A pulse-width-modulated waveform is a square wave of constant amplitude and period (or frequency), with
varying on time (ton). In the waveform below, the period is 50 s, the amplitude is 5 V, and the on-time is 12.5
s:

The average voltage of the waveform is:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

154

Instrumentation and Microcontrollers Using Automatic Code Generation

12.5
= () = 5 + 0 = 5 = 5
= 1.25

50

Note that the average output voltage is the analog output voltage we are after. For a PWM waveform, we
keep the amplitude and period constant. The waveform below shows the output for an increased on-time,
yielding a different average output voltage:

And just to be totally redundant:

25
= 2.5
= 5 = 5

50

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

155

37.5
= 5 = 5
= 3.75

50

Thus we see that we can obtain an analog output voltage between 0 and 5 V by varying the on time (ton) from 0

is

to T. Also note that

referred to as the duty cycle (D) and is expressed as a percent. As the duty cycle

varies between 0 and 100 %, the output varies between 0 and 5 V.


1.
FRDM-KL25Z PWM Output Block
We will observe one of the FRDM-KL25Z PWM outputs to get a better idea of how PWM waveforms
behave. Note that the frequency of the FRDM-KL25Z PWM output is selected by the user and can be chosen
between 20 Hz and 100 kHz, corresponding to periods between 50,000 s and 10 s 10. The inputs to the
block are the Pulse Width and the Period (corresponding to ton and T in the previous discussion), both are
data type double and both are in microseconds. Valid ranges for the pulse width ton are zero to T. We will use
the model shown below. The PWM Output block is located in RHIT KL25Z Library / Basic Blocks library

This block is a constant.

This block is a constant.

The period and pulse width are specified by constants. A 100 s period corresponds to a PWM frequency of 10
kHz. Build and download the model for various values of the pulse width between 0 and 100 while keeping the
period constant at 100 s. Shown below are a few waveforms:

- Pulse Width = 25

10

For large periods (20,000 to 50,000 s), you will need a large fixed time step for the block ( around 0.1 seconds or so).
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

156

Instrumentation and Microcontrollers Using Automatic Code Generation

- Pulse Width = 50

- PWM input = 75
We see that the output waveform is approximately a 0 to 3.3 V square wave with a variable pulse width. You
can set up the constants using Simulink Parameters and specify their storage class as ExportedGlobal. You
can then change the period and pulse width in real-time using FreeMASTER. This would be an easy way to
generate the three waveforms show above, as opposed to changing the constants and building the model each
time a constant value is changed.
Next, we will create a model to vary the pulse width automatically. The Pulse Width input is a Repeating
Sequence Stair:

The settings of the Repeating Sequence Stair are shown below:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

157

The output of the block changes every 2 seconds. The output values are listed in the vector [10 25 50 75 90].
Every two seconds, the output is set to the next value in the vector and the output is held constant for 2
seconds. When we reach the end of the vector, the sequence restarts at the beginning of the vector. Since the
output is held constant at each step, we get a stair step waveform that repeats. Build and run the model and
observe the output waveform on an Oscilloscope.
Demo IV.2: Demonstrate the PWM output of the FRDM-KL25Z on the oscilloscope using the Repeating
Sequence Stair input.
2.
Low-Pass Filter
We can extract the average (DC) value of the waveform using a low-pass filter. For this course, we will
use the same topology first order low-pass filter as we did in Section IV.A:

R
+
PWM Waveform In

+
C

Analog Voltage (Average)


Out

This filter has a cutoff frequency of = 12 . Frequencies below the cutoff frequency are passed through

the filter. Frequencies above the cutoff frequency are attenuated (reduced in amplitude). The more a frequency
is above the filter cutoff frequency, the more it is attenuated. We will use a PWM waveform with a frequency of
10 kHz. This means that its fundamental frequency is 10 kHz and it contains higher order frequencies. We
would like our filter to have a cutoff frequency of at least a factor of 100 below the PWM frequency, so we will
design our filter for a cutoff frequency of 100 Hz. Choose values of R and C that you have available in the lab
to make a filter with a 100 Hz cutoff frequency. A frequency response plot for this filter is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

158

Instrumentation and Microcontrollers Using Automatic Code Generation

The plot is in Decibels. The gain plot is, = 2010

Note that a gain of 0 dB corresponds to

= 1, a gain of -20 dB corresponds to = 0.1, and a gain of -40 dB corresponds to a gain of =

0.01. From the plot we see that DC, which is a frequency of 0, will go through the filter with no attenuation. Low
frequencies in the range 0.1 Hz to 10 Hz are also passed through with little or no attenuation. At the cutoff

frequency of 100 Hz, the gain is 3 dB, or


rapidly (- 20 dB per decade).

= 0.707. At frequencies above the cutoff, the gain decreases

3.
DC Output
We will now use a scope to observe the filter input and output. The input should be a PWM waveform of
varying duty cycle. The output should be a DC voltage. Screen captures below for varying inputs to the PWM
output block are shown:

DC Voltage.

Average (DC)
Value.

- Pulse Width = 25

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

159

DC Voltage.

Average (DC)
Value.

- Pulse Width = 50

DC Voltage.

Average (DC)
Value.

- Pulse Width = 75
Demo IV.3: Demonstrate the PWM and DC outputs of the FRDM-KL25Z on the oscilloscope.
4.
Sine Wave Output
We would now like to see some analog waveforms produced by the FRDM-KL25Z and the low-pass filter.
From the frequency plot of the filter, we should be able to pass frequencies of 10 Hz or less. We will use the
model below:

Note that the Sine Wave block is set to produce a waveform from 0 to 100 at a frequency of 10 Hz. Note that
the frequency you specify in the block is in rad/sec, so you must convert frequency in Hertz to frequency in
radians per second by the equation, =2F. Note that the units of frequency (F) are cycles per second (Hz)
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

160

Instrumentation and Microcontrollers Using Automatic Code Generation

and the units of angular frequency () are radians per second. Since there are 2 radians per cycle, =2F.
The parameters for the Sine Wave block are:

Note that the sample time is set to -1 so the block will execute at the model fixed time step. Make sure that you
set the model fixed time step to 0.001 seconds so that we have a small time step so that the output of the Sine
Wave block changes frequently. Even if we build a good filter it cannot correct a low fidelity input. The output
waveforms are shown below. The PWM frequency is too fast to see it on a time scale when the sine wave is
displayed properly:

Demo IV.4: Demonstrate the PWM and sine wave output of the FRDM-KL25Z on the oscilloscope.
Exercise IV.2: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 10 Hz, (2) a sine wave at 100 Hz, (3) a 10 Hz saw tooth, and (4) a 10 Hz triangle wave. All waveforms
have 1 V in amplitude. Demo with an oscilloscope monitoring the output. Use the PWM Output block to
generate the waveforms.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

C.

161

Variable Brightness Light Bulb

As our next example we will drive a slightly larger load. PWM modulation can be used to drive a large variety of
loads, as long as that load is slow enough to respond to the average rather than the instantaneous waveform. The
requirement is that the PWM frequency be high enough so that the load cannot follow the waveform. An example is an old
incandescent light bulb in your house (if you still have one). These bulbs are powered from the 60 Hz line. You cannot see
the light intensity vary at a 60 Hz rate for two reasons. One is that your eye does not respond to light changing that fast.
The second is that the amount of light is dependent on the temperature of the filament, and the filament has a large
enough thermal mass so that the temperature does not vary significantly at a 60 Hz.
We will demonstrate driving a 5 V incandescent light from our PWM output. The intensity will vary with the
duty cycle, and your eye will never notice that the current and voltage are actually a 10 kHz pulsed waveform. We cannot
just hook the light bulb up to the PWM output because the bulb requires 60 mA of current and the FRDM-KL25Z cannot
drive that large of a load. Plus, the FRDM-KL25Z output is only 3.3 V. Although this is not a huge amount of current, we
will show how to drive larger loads using an npn bipolar junction transistor (BJT) as a high current driver. The circuit below
is used to drive currents up to a few hundred milliamperes:
VCC

LOAD

ILOAD

RB
Vin

2n2222

IB

A BJT is a current amplifier that we can use as a switch or an amplifier. In this example, we are using it as a switch. When
used as an amplifier, the collector current is the current gain times the bas current, IC=hFEIB. The current gain is typically
between 50 and 350, but that depends on the specific BJT you are using. In the circuit above, the collector current is also
the load current ILOAD. You can use any transistor that meets your current requirement. Note that VCC is not limited to 3.3
V. It can be any DC voltage available that is referenced to the ground on your board. The FRDM-KL25Z has an available
5 V supply that we will use for this example. Typically the load current is specified by the manufacturer of the load you
want to drive. In this case the load current is 60 mA, so we need to find a transistor that can handle 60 mA. A second
parameter that we will need to know is called the current gain, and is referred to as hfe, or hFE. hfe is referred to as the
small signal current gain while hFE is called the DC current gain. Portions of the ON Semiconductor PN2222A data sheet
are shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

162

Instrumentation and Microcontrollers Using Automatic Code Generation

We would like a specification for the value of hFE for a collector current near 60 mA. A section of the data sheet
is shown below:

We see that at a collector current (IC) of 10 mA, the minimum value of hFE is 75. For a collector current of 150
mA, the minimum value of hFE is 100. We do not know what hFE is at 60 mA, but the plot below shows us that
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

163

the curve is well behaved 11 and smooth between 60 and 150 mA and that hFE is a little higher at 60 mA than at
10 mA:
The curve is
pretty flat here.

Thus, we will use a minimum value of 75 for hFE.


The design equations for our BJT driver are as follows. To guarantee that the switch is on when
Vin is high, we need IB ILOAD/hFEmin. To satisfy this constraint, we will choose
= 1.1

60

= 880
= 1.1
75

Next, we need to calculate IB from the circuit, which is repeated below:


VCC

LOAD

RB
Vin

2n2222

IB

VBE

From the base loop, we have:


=


880

11

By well behaved we mean that we can estimate a pretty good value from the plot, since the line is pretty much constant
in the range in which we are interested.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

164

Instrumentation and Microcontrollers Using Automatic Code Generation

The base current flows when the input is high. We will assume that when the PWM output is high, the voltage
can be anywhere between 12 2.8 and 3.3 V. Remember that a larger base current guarantees that the BJT will
be an on switch, so if we have to round component sizes or choose parameter limits, we will choose the ones
that make the IB larger. Solving the above equation for RB, we get:

We chose because if we meet the minimum value of IB with the minimum input voltage, IB will be even
larger when VIN is larger. Solving, we get:

2.8 0.7
= 2386
880

We will round RB down to the next closest 5% resistor, which happens to be 2.2 k. We will use the same
Simulink models as before to control the brightness of the light except that we will change the input Sine Wave
source to have a frequency of 0.3 Hz. For the VCC power supply, use the pin named P5V_USB. This pin will
provide 5 V for your load:

P5V_USB

Light
Bulb

100U

2N2222A

PTA13
2.2k

Remember to use the transistor driver and not hook the light bulb directly to a pin of the FRDM-KL25Z board.
Also note in the circuit above that we have added a 100 F supply bypass capacitor to the circuit. Locate this
capacitor as close to the light bulb as possible. It turns out that the switching current through the light bulb
generates enough noise to hang the KL25Z. You may also need to place a 100 F capacitor across the 3.3 V
supply. (Connect the capacitor between 3.3 V and ground on your proto-board.)
Demo IV.5: Demonstrate that your PWM output can directly control the brightness of the light bulb by having
the brightness follow a 1 Hz sine wave.
Exercise IV.3: Create a model that uses a pushbutton to switch between the following waveforms: (1) A sine
wave at 1 Hz, (2) a sine wave at 0.5 Hz, (3) a 1 Hz ramp, and (4) a 1 Hz triangle wave. Drive the light bulb with
all of these waveforms.

12

The Kinetis KL25 Sub-Family datasheet specifies that the minimum high output voltage of a digital pin is VDD-0.5 V
where VDD is the supply voltage. Assuming that our supply voltage is indeed 3.3 V, the minimum high output voltage will
be 2.8 V.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IV: Analog Output (PWM and DAC)

D.

165

Variable Speed Motor

We can drive a DC motor the same way we drive any large load. However, since the motor is inductive 13, we
need to add a diode as shown:
VCC

Motor
LOAD

IMotor

RB
2n2222

Vin

When the switch is on, the diode is reverse biased (off) and current flows as shown above. Note that current
can only flow through the diode in the direction of the arrow. When the switch turns off, the current through the
switch goes to zero instantaneously. The motor current, however, cannot go to zero instantaneously and must
continue to flow because the motor has a large amount of inductance. The diode provides a path for current to
flow when the switch turns off:
VCC

IMotor

Motor
LOAD

RB
Vin

2n2222

The current will circulate as shown until the energy stored in the motor inductance is dissipated, or the switch
turns on again. A diode used in this configuration is called a flyback diode and is needed whenever we drive
an inductive load with a switch. If the flyback diode were not present, when the switch turns off, the inductor will
generate a large voltage in an attempt to keep current flowing. If the voltage is large enough, it will damage the
switch.
Demo IV.6: Demonstrate that you can control the speed of your motor using the PWM output of the FRDMKL25Z. You may need to change the driver transistor and the base resistor depending on the current
requirements of your motor. Make sure that you use a supply bypass capacitor for the 5 V and 3.3 V supplies.
Applying a switching voltage to a motor can generate a lot of noise.

13

A motor is made by winding a large amount of wire into a coil. This coil has a lot of inductance and the current through
an inductor cannot change instantaneously. In our example with a switch, the current through an inductor cannot go to
zero instantaneously when the switch turns off.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

V.

A.

Serial Communication

Lab V
Serial Communication

Introduction

We will now look at using the serial communication ports of the Freescale FRDM-KL25Z. The KL25Z
has three logic-level serial ports. Traditional RS-232 serial ports have a minimum of three wires for
communication: a ground wire, a transmit (TX) wire, and a receive (RX) wire. When connecting two serial
devices together, you would connect the grounds together and then connect the RX of device 1 to the TX of
device 2, and the TX of device 1 to the RX of device 2. This allows two devices to communicate with each
other, but does not allow networking of several devices. Traditional RS-232 devices used +/- 12 V signal
levels. The FRDM-KL25Z serial ports differ in that they use 3.3 V logic level signals of 0 to 3.3 V rather than +/12 V signal levels. We cannot connect an FRDM-KL25Z serial port directly to an RS-232 port as the higher
signal voltages of the RS-232 port could damage the FRDM-KL25Z board. There are, however, a number of
devices that have logic-level serial ports, and we will use the FRDM-KL25Z to communicate with devices that
have these types of ports.
We will use an LCD display that has a 3.3 V logic-level serial interface 14. The LCD-09066 is a
16x2 serial-enabled LCD display. 16x2 means that it can display 2 lines of text, each with a maximum of 16
characters. The datasheet for the serial LCD module is shown in Appendix XI.A on page 287. Note that the
Serial LCD display only receives and displays text, so it only has an RX input port:
Create a new model and place a Serial Transmit block in your model. This block is located in
library Embedded Coder Support Package for Freescale FRDM-KL25Z Board / FRDM-KL25Z:

If you double-click on the Serial Transmit block, you will see a list of the available ports:

14

This device is available from SparkFun Electronics.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

167

To use the serial device, from an electrical interface point of view, all we need to do is hook up power and
ground (VDD on the Serial LCD connects to 3.3 V on the Freescale FRDM-KL25Z, and GND on the Serial LCD
connects to GND on the Freescale FRDM-KL25Z), and connect one of the transmits outputs on the Freescale
FRDM-KL25Z to the receive input (RX) on the serial LCD. We will use the Freescale FRDM-KL25Z UART1 to
connect to the LCD RX input:
3.3 V Connection.

Wiring interface
for the Serial
LCD. Only RX,
GND, and VDD.

Connect this pin


to PTC4 on the
KL25Z.

Note that even though the LCD daughter board says 5 V, this LCD is designed to work with a 3.3 V supply and
logic.
You can use any of the Freescale FRDM-KL25Z transmit ports. However, UART0 (USBTX and
USBRX) are also used for communication between the FRDM-KL25Z board. To avoid any possible conflicts,
we will not use UART0. Connect the TX output of the FRDM-KL25Z port you select to the Serial LCD RX port:

LCD power connections (3.3 V and ground).

UART1 TX (PTC4) of the FRDM-KL25Z


KL25Z connected to RX of the Serial LCD.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

168

Instrumentation and Microcontrollers Using Automatic Code Generation

Do not forget to hook up the power and ground for the Serial LCD as well.
Serial RS-232 communication sends text as a series of 8-bit codes referred to as ASCII (American
Standard Code for Information Interchange). The Serial LCD will respond to and display many of the ASCII codes. The
codes include standard text characters like A through Z, a through z, 0 through 9, punctuation, and others. ASCII also
includes special characters like ESC, carriage return, and bell. The serial LCD will display many of the standard printable
characters, but uses a few of the codes as its own control codes.
You can find tables for ASCII codes on the internet and in many archaic text books that were used in the
era that the person writing this book attended college. The table below is from Wikipedia [1]:

Figure V-1: ASCII table of printable characters.

Typically, text strings and the ABS function in MATLAB will do the ASCII conversion for us, so we do not
usually need to know the codes. Occasionally, we may need to send a character that does not work out well
with MATLAB text strings, and we will need to specifically insert the ASCII code for that character.
A text string is a one-dimensional array of characters. An example would be, This is a text
string. In memory, this text string would be saved as a one-dimensional array of ASCII codes, [84 104 105 115
32 105 115 32 97 32 116 101 120]. Some commands to illustrate text strings in MATLAB are shown below:
>> txt_str='This is a text string.'
txt_str =
This is a text string.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

169

>> abs(txt_str)
ans =
Columns 1 through 13
84

104

105

115

32

105

115

32

97

114

105

110

103

46

32

116

101

120

Columns 14 through 22
116

32

115

116

>>
The rate that information is transmitted on a serial line is referred to as the BAUD rate. In serial
communication, that can be symbols per second or bits per second. Since an ASCII symbol is represented by
an 8-bit code, there is quite a difference between symbols per second and bits per second. For serial ports,
speed is usually specified in bits per second (bps). If you are having trouble with serial communication, you
may want to verify that the speeds on both ports are the same.
Before we start our first model, we need to find out how to clear the LCD screen and position
the cursor at the beginning of the first line. (Though we may not need to do this if we always send 32
characters to the LCD, the unused ones being blanks (ASCII 32 in decimal)). Referring to the Serial LCD data
sheet, sending the LCD a code of decimal 254 tells the LCD that the next character it receives will be a
command code. Following 254 by the code 01 clears the display and positions the cursor at the top left position
of the LCD screen. Thus, we will always prepend our text strings with the codes [254 01].

B.

Useful MATLAB Commands

Before we use our LCD screen, we will review some MATLAB commands that are useful with text strings. First,
text strings are enclosed in single quotes, for example, This is a test. Entering this command in MATLAB is
shown below:

The MATLAB ABS command, among other things, converts a text string to an array of ASCII codes:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

170

Instrumentation and Microcontrollers Using Automatic Code Generation

Arrays can be concatenated by placing them inside square brackets and separating the strings by a comma:

Note that concatenation means to combine multiple strings into a single new string by placing them one after
another. Or, some slight variations:

And finally, just for fun:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

171

We can use the concatenate command to concatenate strings or arrays. We need to send the LCD an array of
ASCII codes. To create the array of codes that clears the LCD screen and display the text, This is a test! we
can use the command below:

Or, alternatively:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

172

Instrumentation and Microcontrollers Using Automatic Code Generation

C.

Displaying Text on and LCD Display

We are now ready to create a model with Simulink that displays text on the LCD display.
1.

Displaying a Single Line of Text

Create the model below:

Double-click on the Serial Transmit block and specify UART1. Note that UART1 uses pin PTC4 as the
transmit pin:

The putc option specifies that the block transmits the numerical values specified in our input array. With the
putc option, if the input to the block is the numerical value of 64, the block sends out the numerical value 64,
not 54 and 52, the ASCII codes for 6 and 4.)
When complete, this model should display the text message This is a test! on the LCD screen.
Note that the Constant block will output a 1-dimensional array of double precision numbers. The Data Type
Conversion block will convert the array to a 1-dimensional array of 8-bit integers, appropriate for serial
transmission. Set up the Model Configuration Parameters to use the discrete solver with a Fixed-step size
of 1 second:

Discrete solver.
Fixed-step size
of 1 second.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

173

The default BAUD rate of the SparkFun LCD display is 9600. (Note that yours may be different.) We need to
make sure that the BAUD rate of UART1 is the same as that of the LCD. To specify the BAUD rate, select the
Coder Target pane of the Configuration Parameters window.

BAUD rate specified for UART1.


UART1 Selected.
Coder Target selected.

Note that the model will run once every second, meaning that the test message will be resent to
the LCD display every second. This is unnecessary because we only need to send it once and the LCD will
continue to display the text until a different text message is sent to the LCD or the power is removed from the
LCD. Make sure that you still have your flashing LED and overrun detection blocks in your model and on your
board.

Serial transmission tends to take a lot of time and can cause overruns. For this example, however, sending a
text message at a 1 Hz rate should not be a problem. (You may need to change the properties of the Pulse
Generator to eliminate an error that we created by changing the step size.)
Important Note! It appears that if you have a load connected to pin PTA4, and you do not program pin
PTA4 to do anything, it will cause your KL25Z to hang. If you have something connected to pin PTA4
from a previous lab, and you do not have a digital output block for PTA4 in the current model,
disconnect whatever is connected to pin PTA4. (This issue does not arise if you have a load connected
to PTA4 and use a digital output for PTA4 as well.)
Also note: The SparkFun LDC will not display any text if you send text to it within the first second of
power up. It appears that if you send text to the LCD during its boot-up sequence, it prevents the LCD
from displaying any text. Therefore, you should place a delay in your model to wait for at least one
second before sending text to LCD display.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

174

Instrumentation and Microcontrollers Using Automatic Code Generation

Demo V.1: Display the text, This is a test! on your LCD screen at a fixed step size of 1 second.

For our models to do any type of serious control or instrumentation functions, we usually need a
fixed time step smaller than 1 second. Change the fixed time step to 0.01 seconds and rerun the model. You
will notice that the LCD displays dimmed out or jittery text:

The text appears this way because it takes time to transmit the text over the serial line, the LCD is fairly slow to
display text, and we are rapidly resending the text string, the first two characters of which clear the screen.
Thus, if we have a small fixed time step, we need to find a way to reduce the rate at which we send a text
string to the LCD. We actually only need to send the text string once and then never send it again until we
need to change the text string. We will fix this problem in the next section by using triggered subsystems. You
will also note that we have an overrun because sending text through the serial port takes a lot of time.
We will fix the overrun in Section V.C.1.b) where we study atomic and multirate subsystems.
a)
Triggered Subsystems 1 Hz Rate
Typically we would like our FRDM-KL25Z to run with a fast fixed time step so that it can control external
systems quickly or respond to sensor inputs quickly. However, we only need to send information to the LCD at
a slow rate because humans can only read so quickly and because the LCD display reacts slowly. A solution is
to place the serial transmit block inside a triggered subsystem. We introduced triggered subsystems in Section
III.B.1 on page 113. Triggered subsystems allow us to run different sections of the model at different rates.
(Note, however, that all of the triggered systems will use the same fixed time step as the top-level model.) In
this case, we will run the complete model with a fixed time step of 0.01 seconds and place the LCD
communication portion of the model inside a triggered subsystem such that it runs once every second. This
allows the LCD module to display text properly, since updating the LCD text string too frequently caused the
text to fade out.
We will start with the previous model and select the Data Type Conversion block and the
Serial Transmit block:
Block selected.

Block selected.

Selected.

Right-click on one of the selected blocks:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

175

Right-click here.

Select Create Subsystem from Selection:

The two blocks are placed inside a conventional subsystem. Rename the subsystem LCD Display. Doubleclick on the subsystem to open it and rename the input port to Text String In. To make the subsystem a
triggered subsystem, place a trigger block
and Subsystems library:

in the subsystem. This block is located in the Simulink / Ports

By default, the trigger is positive edge triggered. If you want to change the trigger type you can double-click on
the block and change the trigger type to positive edge, negative edge, both, or a function call trigger. We do
not need to change the trigger type, so navigate back to the top level of the model and place a Pulse
Generator in the model and set the period to one second:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

176

Instrumentation and Microcontrollers Using Automatic Code Generation

With a Pulse Generator period of one second, the LCD display subsystem will run once every second, even
though the model uses a fixed time step is 10 ms. Download and run your model. The LCD display should
work properly. Note that the text displays properly, but we still have an overrun. The text displays properly
because the text string is only sent once a second, and the LCD can easily respond at a 1 Hz rate. An overrun
occurs because when the text string is sent, it must still send the text string and execute the entire model within
one 10 ms time step. Even through the text string is sent only once a second with this method, when it is sent,
it must perform all of the communication within one fixed-step time, of which 10 ms is too short. Thus, using the
triggered subsystem allows us to time how often we send a text string, but it does not fix the problem that
sending a text string takes a long time and will not fit within a single small fixed-step time.
Demo V.2: Display the text, This is a test! on your LCD screen at a fixed step size of 0.01 second and using a
triggered subsystem to update the text screen once every second. (You should still have an overrun.)

Exercise V.1: Using a switch, have the LCD automatically switch at a 1 Hz rate between displaying the text My
name is xxxx. and This class is fun! You can use a switch to select between text strings. Note that the text
strings must be the same length, so you may need to pad one of the strings with spaces.
b)
Atomic Subsystems and Multirate Models
Triggered subsystems allow us to control how often certain parts of a model execute. In the last
example, the main model would run once every 10 ms, while sending a text message at the slower rate of
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

177

once every second. We will use triggered subsystems in the future to control how often certain functions occur
in a model. We were, however, left with the problem that once a triggered subsystem executes, it must
complete within one fixed-step time slice. This can be an issue if we have two things we need to control. One
that must execute very quickly and must be repeated at a very fast rate, and a second that requires a lot of
computation, but only repeats at a much slower rate. We have one function that does not require much
computation, must be completed quickly, and requires a small fixed-step size. We have a second function that
requires a lot of computation, has a much longer time to complete those computations, and therefore, can have
a much larger fixed-step time.
The function that needs to be repeated quickly determines the fixed-step size of the model, as
this is the fastest rate at which the model executes. The problem is that if we use a single rate system, both the
high speed function and the slow, high computation functions must execute within the fixed-step-time, which is
determined by the function that needs to repeat the fastest. This usually leads to an overrun.
We can fix this problem by placing the high-computation, slow function inside an atomic
subsystem and specifying a longer time step for the atomic subsystem. If we specify the model as a multirate
model, then the blocks within the atomic subsystem must complete within the time specified by the atomic
subsystems step size rather than the models very short fixed-step time. Thus, we can place slower functions
inside atomic subsystems, freeing the microcontroller to execute critical high-speed functions.
We will start with the model below that has overrun issues. Remember that the fixed-size step
for this model was 0.01 seconds, too short of a time for the controller to send the text string without an overrun:

Make a subsystem out of the uint8 and Serial Transmit blocks as we did in the previous section. (Do not add a
trigger!) Your model should look as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

178

Instrumentation and Microcontrollers Using Automatic Code Generation

Right-click on the LCD Display Subsystem and select Block Parameters (Subsystem) as shown below:

Specify the subsystem as atomic and the Sample time as 1 second:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

179

The subsystem is specified


as atomic.

The Sample time is


specified as 1 second.

The blocks within this subsystem will execute once a second and they will have one second to complete the
task that they perform, in this case sending a text message. Click the OK button to accept the changes.
Next, we must specify the system as a multirate system. Select Simulation and then Model
Configuration Parameters to open the configuration parameters for the model. In the Solver pane, specify
the Tasking mode as MultiTasking:

Solver pane
selected.

MultiTasking
selected.

Click the OK button to accept the changes.


To display the sample times on your model, select Display, Sample Time, and then All:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

180

Instrumentation and Microcontrollers Using Automatic Code Generation

The different sample times will be displayed in different colors on your model:

Note that the legend tells us the sample rates for the various colors. Everything in the model executes at the
fixed-step size of the model (0.01 seconds) except the atomic subsystem, which executes once a second. Run
your model on your target. You will notice that the text displays correctly because the text string is sent only
once a second and the overrun is now gone.
Demo V.3: Display the text, This is a test! on your LCD screen at a fixed model step size of 0.01 second using
an atomic subsystem to update the text screen once every second. Show that there is no longer an overrun.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

181

Exercise V.2: Using a switch, have the LCD automatically switch at a 1 Hz rate between displaying the text My
name is xxxx. and This class is fun! Note that the text strings must be the same length, so you may need to
pad one of the strings with spaces.
2.
Displaying Text Based on User Selection
Next, we would like to change the text we display every time we press a switch. Instead of updating the LCD
periodically, we will only update the LCD at the time we want to change the text. This is possible because the
LCD display remembers the text string we send and will continue to display the text until it is changed. This has
the benefit of freeing up the processor to perform other tasks rather than periodically sending the same text
string to the LCD.
a)
Stateflow Switch Debounce
In order to implement this model, we will need to recognize that when a switch changes from high to low or low
to high we are responding to the edge of the change rather than the low state or high state. An example of
positive and negative edges are shown below:
Positive edge.

Negative edge.

Some devices or functions are level sensitive, such as an enable or disable signal where the systems perform
their function when a signal is high or low. Some devices are edge triggered where the systems start to
perform their function when an edge occurs. Edge triggered functions can be used for timing or sequencing
operations.
Inside a microcontroller, a signal edge is usually pretty reliable. However, we would like to
sense the edge of a signal when it is generated from a switch that is outside the microcontroller and connected
to it with relatively long wires. When a switch changes from one state to the other, the output voltage may
bounce as shown in the figures below:

Toggle switches use a spring to throw a hammer contact against a metal ball contact. When they collide, the
hammer momentarily makes contact with the ball and then mechanically bounces away from the ball. The
spring then forces the hammer back towards the ball and the bouncing continues until it dies out. The bouncing
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

182

Instrumentation and Microcontrollers Using Automatic Code Generation

causes intermittent electrical contact between the ball and the hammer resulting in the waveforms show above.
Switch bounce is a fairly common problem and different logic solutions have been devised to change the
bouncing edge into a single edge. Here, we will make a switch debounce using Stateflow logic.
The Stateflow chart shown here is a slightly modified version of the switch debouncer found in
the Stateflow help from The MathWorks. To find the original version from which this example was derived, type
doc Stateflow debounce at the MATLAB prompt. The top level of the chart is shown below:

The input to the chart (SW) is the undebounced switch signal. This signal is usually steady at a high or low
level, but when the switch changes state, there may be several edges. The Stateflow chart eliminates the
multiple edges and passes the steady high or low value. The logic inside the chart is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

183

During a transition, the switch changes state, and the chart will enter into the debounce states. During the
transition, SW may bounce between 0 and 1 several times before it settles down. While this bouncing occurs,
the chart will bounce back and forth between the Debounce0 and Debounce1 states. However, while it is
bouncing, it remains in one of the two Debounce states and the output of the chart does not change.
The after command is referred to as temporal logic and allows us to time how long we have
been in a state or how long a condition has been true. In this case, the chart will not transition into the High
state until the chart has been in the Debounce1 state for 0.1 seconds, or SW has been constant at 1 for 0.1
seconds. SW will not be constant at 1 until the bouncing has stopped. The same temporal logic is used for the
transition to zero. The chart will not change to the low state until the SW has been at 0 for 0.1 seconds. Thus,
while the switch is bouncing, the chart will stay in the debounce states while the switch voltage is bouncing.
The chart will only enter the High or Low states after the switch voltage has been constant for 0.1 seconds.
Note that there are several Stateflow temporal operators: after, before, at, every, and
temporalCount. Search for Temporal Logic in the MathWorks help for more information. 15
b)
Function-Call Triggers
Now that we have debounced a switch, we want to make a Stateflow chart that will switch between displaying
one of three different messages when the button is pressed. The text message should only be sent to the LCD
once after the button has been pressed, not periodically as in the previous examples. This task requires us to
sequence events after the button has been pressed. First, we must increment a counter that selects the
message to be displayed. Second, we must select a text message. And third, we must send the text message
to the LCD display. All of these are triggered by the pushbutton being pressed. To sequence events in a
specific order, we need to use a different kind of trigger called a function-call trigger 16. Conceptually, they
operate the same as an edge trigger; you can have blocks generate a function call trigger, and you can make
subsystems execute when they receive a function call trigger. The difference is that we can use a demux to
split a single function trigger into several function triggers, all of which execute in sequence.
We will start with the system below, most of which we generated previously:

15

Switch debouncer subsystems are located in the RHIT FRDM-KL25Z library under the Miscellaneous Functions.
We do not need to use function call triggers to sequence the series of events in this specific example as Simulink would
do it automatically. However, the method is presented so that if you have a sequence of events that must execute in a
specific order, you can use this method.
16

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

184

Instrumentation and Microcontrollers Using Automatic Code Generation

We will set the fixed time step to 0.001 seconds. We know that the LCD and UART blocks cannot run this fast.
However, we will use this fast time step to allow our controller to run other tasks fast (even though we will not
program these tasks here) and then use an atomic subsystem to allow the text message portion of the model
to run at a lower speed.
The output of the debouncer is a digital signal that switches between 0 and 1. Since we are
using a pull-up resistor, the output of the switch is normally high and will go low when we press the pushbutton.
We will use the inverter
to convert the output to normally low and then switch to high when the pushbutton
is pressed 17. (Note that an inverter is also referred to as a NOT gate.) If you look inside the RHIT Switch
Debounce block, you will notice that it contains a chart that has a starting state of 0, consistent with the starting
position of our pushbutton. The output of the switch debouncer will be used to generate positive and negative
edges that we will use to trigger edge triggered subsystems.
For this example, we need to convert a positive edge to a function trigger. Place a Triggered
Subsystem (Simulink / Ports & Subsystems) in your model:

Double-click on this block and


specify the operator as NOT.

Open the Triggered Subsystem, delete the input port and place a part called Function-Call Generator
(Simulink / Ports & Subsystems) in your model:

This subsystem executes every time it receives a positive edge. All the subsystem does is generate a functioncall trigger. Thus, it converts a rising edge trigger to a function-call trigger. Since this Function-Call Generator
is inside a triggered subsystem, we need to change its sample time. Open the Function-Call Generator part
and change its Sample time to -1 (inherited):

17

An inverter converts a 0 to a 1 and a 1 to a 0. Note that an inverter is also referred to as a NOT gate.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

185

Sample time changed to -1.

Next, we need to generate a counter that increments every time it receives a function-call
trigger. We will do this with Stateflow using the chart shown below:

Make sure that you add an output for variable Count. To make this chart execute every time it receives a
function-call trigger, select Chart, Add Inputs & Outputs, and then Event Input From Simulink:

Name the input PB and specify the Trigger as a Function call:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

186

Instrumentation and Microcontrollers Using Automatic Code Generation

Function Call
selected here.

Click the OK button to accept the changes. When you return to the top level of the model, you will notice the
event input displayed as PB() indicating that the event is a function-call trigger.

Next, we need to create another subsystem that selects the text message. Place a Function-Call Subsystem
(Simulink / Ports & Subsystems) in the top-level of your model:

To accomplish the same thing, you could have also placed a Subsystem and added a trigger or placed a
Triggered Subsystem and changed the trigger type. Here, we just placed a Function-Call Subsystem to save a
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

187

few steps. Note that the name of the trigger is function() indicating that it is a function-call trigger. Open the
Function-Call Subsystem and change the name of the trigger as shown:

It was this.

Change it to this.

We will be using this subsystem to specify the text message. We could use a Multport Switch (Simulink /
Signal Routing) or even a Stateflow chart. Instead, we will use the Truth Table below:

Dont forget the transpose


operator.

A few notes are important. First is that all of the text strings are 32 characters. Second, the text strings are
enclosed in single quotes. Third, the total length of the array is 34 elements. Fourth, we are using the
transpose operator () to convert a row vector to a column vector.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

188

Instrumentation and Microcontrollers Using Automatic Code Generation

This truth table emits one of three text messages based on the count being between 1 and 3. If,
for some reason our Stateflow chart has a count outside this range, the truth table will send out an error
message. This should never happen if our logic is correct. The complete subsystem is shown below:

Finally, at the top level, we need to add our triggered serial output subsystem that we created earlier:

A problem with the LCD Display subsystem is that it is edge triggered, so we need to change the trigger type.
Open the LCD Display subsystem:

Double-click on the Trigger to edit its properties. Change the Trigger type to function-call:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

189

Function-call trigger type


selected.

Apply the changes and return to the subsystem. You will see that the trigger type has been changed to a
function-call:

f() indicates that the trigger type


is a function-call.

Change the name of the trigger to PB as shown below:

At the top level, we now have three function-call triggered subsystems. Wire them as shown:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

190

Instrumentation and Microcontrollers Using Automatic Code Generation

The last thing we need to do is sequence the events. Place a Demux (Simulink / Commonly Used Blocks) in
your model. Rotate it, change the Number of outputs to three, and stretch it:

The Demux splits the function-call trigger input into three function-call outputs. The triggers are sequenced
from left to right, so the chart will receive the trigger first, then the Function-Call Subsystem, and finally the
LCD display. Using function-call triggers in this method allows us to specify a sequence of events. Rename the
subsystems to document the functions they perform:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

191

These trigger lines may


appear as dash-dot lines
on your display. This
indicates that they are a
function trigger.

The last thing we need to do is enclose our text message portion of the model in an atomic subsystem. We
have set the model fixed-step size to 0.001 so that it can run other (unspecified) tasks quickly. We know from
previous models that the text messages cannot be displayed at such a fast rate. To fix this, we will enclose the
blocks in a subsystem, specify it as atomic, and specify the sample rate of the atomic subsystem to be 0.1
seconds. See Section V.C.1.b) for the steps to create an atomic subsystem. In the screen capture below, we
have named the subsystem Message Center:

Download and run the model to verify its operation.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

192

Instrumentation and Microcontrollers Using Automatic Code Generation

Demo V.4: Demo the working LCD display. The text message should change after the pushbutton is pressed
and cycle through the three text messages.
Exercise V.3: For the model of Demo V.4, if you cycle the power, you will notice that the LCD displays a blank
screen until the user presses the pushbutton. This could be confusing to the user. Modify the model so that at
power up, the model will wait 2 seconds and then display the text, 'Press the pushbutton to start. ' When the
user presses the pushbutton, it will display the first text message and then cycle through the three text
messages when the button is pressed. The message 'Press the push button to start.' will never be seen again
unless the power is cycled.
Exercise V.4: Create a model that switches between three functions when a pushbutton is pressed. The
functions are displayed on the LEDs we used in previous labs. The functions are a ring counter, an up/down
counter, and an analog voltmeter. You should have models that solved these problems before. In addition to
this requirement, the LCD should display the text, Ring Counter, Up-Down Counter, or Analog Voltmeter
as appropriate.
Exercise V.5: Use the LCD display to create a bar-graph display representing an analog input voltage. An input
of 0 should display 0 bars and an input of 3.3 V should display 16 bars. Use a potentiometer to supply a
variable input voltage to one of the FRDM-KL25Z analog input pins. On the top line of the LCD display, show
the text Bar Graph with appropriate spacing. On the second line of the LCD display, show the bar graph. To
display a square, you can send an ASCII code of 6. To display a blank use an ACSII code of 32. As an
example, the array Bar = [6 6 32 32 32 32 32 32 32 32 32 32 32 32 32 32]'; will display 2 bars and 14 blanks.
You may also want to use the Simulink block Vector Concatenate to concatenate strings. Examples are
shown below:

3.
Formatted Text Output
Now that we know how to generate text strings and send them to the LCD display, we will look at
generating formatted numerical output, such as the The temperature is 72.4 Degrees where the number
comes from a Simulink signal. Simulink does have a method for converting a signal to a formatted text string.
However, we will use the Simulink MATLAB Function block to use MATLAB functions within Simulink to give
us more flexibility. We will use the MATLAB sprint function which will make some of MATLABs numerical
formatting available to us. For these examples, we will use the %d formatting string for converting an integer to
a text string. Note that the formatting strings %f, %g, and %e are not available to us. To display a floating point
number such as 3.14, we will have to break the number up into its integer and fractional parts.
a)
MATLAB Functions
The MATLAB function block allows us to use a subset of the MATLAB language within a Simulink
block. The subset of MATLAB functions can be found by searching for functions supported by code
generation within the MATLAB/Simulink help system. A simple example is shown next. First, the block is
shown below. Note that it has three inputs called a, b, and c, and one output called y:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

193

The code for this block is shown below:

Note that the inputs to the function are a, b, and c, and they correspond to the three Simulink input signals. The
output of the function is y, and this corresponds to the Simulink output signal. This is a fairly trivial example,
and given your comfort level with MATLAB programming, you can make quite complex functions. In a future
lab, we will use MATLAB functions to create memory blocks.
a)
Displaying Formatted Text Output
It turns out that the sprintf function is not one of the supported MATLAB functions. So, what do we do?
We call technical support and ask for help. They can write the MATLAB function for us 18. The function is
presented below:

18 Actually, we call Peter Maloney, a MathWorks Sr. Principal Consulting Engineer, and good acquaintance through the
Challenge X, EcoCAR, and EcoCAR2 Hybrid Vehicle competitions. He actually wrote the function presented here. And we
also call James Kristoff, Educational Technical Evangelist for Student Competitions at The MathWorks, for help with
finding the whole and fractional parts of the number so we do not need to use the %f formatting string.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

194

Instrumentation and Microcontrollers Using Automatic Code Generation

The input signal name is Number_In. The numerical value of this signal will be placed in the text string. Since
we are displaying text on the LCD screen, we have limited the size of the text string output to a maximum of 32
characters. The lines data_array = ones(1,lenMax, 'uint8').*space; and Output_String =
ones(lenMax,1, 'uint8').*space; allocate the storage and initialize the arrays to the value 32, which is
the ASCII code for a space.
Since we are required to use the %d format string, we need to break the number into its integer
and fractional portions. This is accomplished with the lines
[Sign, Mag, Frac]=float2strparts (Number_In, 5);
Mag=Mag*Sign;
The 5 in the line above is the number of decimal places we would like to have in the number.
The line coder.ceval('sprintf',coder.wref(data_array),coder.opaque('const
char *','"The number is:
%2d.%05d. "'),int16(Mag),int16(Frac)); does all of the
work. It specifies sprintf as the function we are calling and uses the text between the double quotes as the
output string. Note that the string must be contained within double quotes, "The number is:
%2d.%05d. ". Also note that this string should be 32 characters long (not including the double quotes). The
numerical value of mag will be placed in the format string %2d and the numerical value of frac will be placed
in the format string %5d. Thus the number itself will take a total of 8 spaces if we include the decimal point, and
be displayed as xx.xxxxx.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

195

The purpose of the if statement is to handle negative numbers and allocate the proper number
of blank spaces for the two different cases. It also shows that we can use MATLAB programming techniques to
output different text strings if needed.
If we use less than 32 elements, some of the values of the array will be zero. When an ASCII
code of zero is sent to the LCD, it displays a strange character that we do not want. To fix this problem, we add
the line, data_array(data_array==0)=space; This command scans the data_array for zeros and
replaces them with the value of 32, the ASCII code for a space. Finally, the line
Output_String=data_array(1:lenMax)'; converts the row vector to a column vector. Remember that
we used column vectors when we used the truth table for selecting one of three text strings.
Finally, we note that this function does not prepend the string with [254, 01], the commands to
clear the LCD screen. We will do this with the Simulink Vector Concatenate block. As a first example, create
the model below for displaying the text string, The value of pi is 3.142. Note that the Sprintf function is
contained in the RHIT FRDM-KL25Z Library. The sprintf function is located in the Serial String Functions
section of the RHIT library. In the model below, you can reuse as much of the previous models as you would
like.

Note that the Vector Concatenate part is needed because the sprint block does not output the control
characters (254, 0) to place the cursor at character 1 row 1 of the LCD display. Thus, we use the Vector
Concatenate block to prepend these codes to the beginning of the text string. Pi is a predefined function in
MATLAB and has the value of . We need to modify the Sprintf block to suit our needs. The block is intended
to be used as an example and it is expected that you will modify it. Since the block is linked to our library, we
need to unlink it and break the link. To disable the library link, right-click on the sprintf block and then select
Library Link and then select Disable Link:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

196

Instrumentation and Microcontrollers Using Automatic Code Generation

Next, right-click on the sprintf block and then select Library Link and then select Break Link:

After taking these two steps, any changes we make to the block will not affect the block saved in the library.
We can now edit and modify the sprintf block. Right-click on the sprintf block and then select
Mask and then select Look Under Mask:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab V:Serial Communication

197

The editor will open the MATLAB Embedded function and you can modify it:

Inputs specified here.

Format string specified here twice.


Once for positive numbers. Once for
negative numbers.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

198

Instrumentation and Microcontrollers Using Automatic Code Generation

You can now modify the function as needed. Typically we will need to change the number of inputs and modify
the format string. For this example, since we only have a single input all we need to do is modify the format
string. Change the format string to '"The value of pi is %1d.%03d.
"'; and change the
number of decimal places to 3 in the line [Sign, Mag, Frac]=float2strparts(Number_In, 3);
Demo V.5: Demo the sprint MATLAB Function block displaying the text string, The value of pi is 3.142.
Exercise V.6: Create a model that increments a counter from 1 to 10. This value is multiplied by the constant
pi. Both numbers are passed to a modified sprintf function. The sprint function generates a text string that
outputs the following, The value of x*pi is y. where x is the counter, and y is the value of the constant times pi.
Example outputs are:
The value of 1*pi is 3.14.
The value of 3*pi is 9.42.
The value of 8*pi is 25.13.
The text displayed on the screen should change once every second.
Exercise V.7: Modify the bar graph of Exercise V.5 so that the first line on the LCD displays the text Bar Graph
xxx.x% where xxx.x is the numerical value of the percent, between 0 and 100. The second line of the LCD
should still display the bar graph as in Exercise V.5. You will need to use the %c format string to display a %
sign on the LCD screen.

Exercise V.8: The LCD splash screen is the text that the LCD displays at power-up. The text is displayed for
half a second and then the LCD goes blank. The datasheet for the LCD gives the procedure for changing the
LCD splash screen. This text string should only be sent once. Create a model that sends one text string to the
LCD screen such that it changes the splash screen. Change the splash screen so that it displays your name. A
data sheet for the LCD screen can be found in the appendix on page 287.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

VI.

Intelligent Sensors

Lab VI
Intelligent Sensors

In this section we will look at intelligent sensors. Typically, these sensors measure some
physical quantity, digitize the signal, then perform some signal processing and mathematical transformations
on the signal to remove noise and linearize the signal. Typically, analog sensors are non-linear and we need to
do some compensation in our circuit to correct the signal. With intelligent sensors, all of the compensation is
done inside the sensor. The output signal could be analog or digital. If the sensor output is analog, then we
would just read the sensor with one of the FRDM-KL25Zs analog inputs, and we have already demonstrated
this with the thermistor. For this section, we will look at sensors that have a digital output and communicate
their value as a serial bit stream. In this lab we will study the I2C bus which is a standard two wire serial data
link used by several manufactures for many different types sensors. The RHIT FRDM-KL25Z Library also
contains blocks for a DS1821 temperature sensor which is a one-wire serial communication method proprietary
to Maxim Integrated.
Note that serial communication and all of the calculations for filtering and linearization take time.
Typical sensors that use a serial communication link are slower than analog sensors. For the digital sensors
we demonstrate here, we will poll the sensor once a second or slower. You would typically use analog sensors
if you want higher speed sensors.

A.

What is I2C?

A typical I2C sensor has four pins, Vcc, ground, SDA and SCL. Vcc and ground are the power pins. Vcc
is typically 3.3 V or 5 V. SDA is the bi-directional serial data line and SCL is the serial clock line. If you have
multiple sensors, all of the SDA lines are connected together and all of the SCL lines are connected together.
An example of four sensors connected on a single I2C bus is shown below:
VCC

VCC

R1
10k

R2
10k

SDA

SCL

Sensor 4

SDA

SCL

Sensor 3

SDA

SCL

SDA

Sensor 2

Sensor 1

SCL

SCL

SDA

KL25Z

Note that the SCL line and the SDA line require pull-up resistors. 10 k resistors work well for the sensors
used in this manual. Keep in mind that other sensors or applications may require different pull-up resistors.
Each sensor will have a unique address specified by the manufacturer. You can distinguish between sensors
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

200

Instrumentation and Microcontrollers Using Automatic Code Generation

through their address. In our example, the addresses are specified by the manufacturer. If two sensors have
the same address, you cannot use them on the same bus.

B.

TC74, TMP101, and TMP102 Temperature Sensors

Here is where it gets hairy. To use a sensor we need to make a Simulink driver block specific to that
sensor. The driver is written in C or C++. Dont panic! The blocks for the sensors used in this manual are
contained in the RHIT FRDM-KL25Z Library. For this example, you can use any of the supported sensors. We
will demonstrate using a TMP101, but the use of the other sensors will be similar.

Datasheets for the TMP101 are readily available on-line and are available from a button on the Simulink
TMP101 block. For this lab we will be using a surface mount package that is mounted on a breakout board
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VI:Intelligent Sensors

201

fabricated by Rose-Hulman. If you do not have this sensor mounted on a breakout board, you can get the
TMP102 from SparkFun or you can use the TC74.
Note that the TMP101 can have one of three addresses which are selected using the ADD0 pin.

You can wire the ADD0 pin to ground (0), the 3.3 V supply (1) or not connect it at all (float). The three
addresses are provided so that we could use three TMP101 sensors on the same I2C bus without an address
conflict. We only have a single sensor, so you can choose which one you would like to use.
The pin connections for the TMP101 are shown below:

You will need to wire the TMP101 to your KL25Z as shown below. Do not forget about the pull-up resistors for
the SDA and SCL pins. Do not forget to hook up the power and ground. For the TMP101. The GND pin goes to
ground on the KL25Z and the V+ pin goes to the 3.3 V supply on the KL25Z. Note: If you are using the
TMP102 breakout board from SparkFun, the pull-up resistors for SCL and SDA are already on the breakout
board, so do not add your own pull-up resistors. The complete schematic is shown below. I have shown ADD0
connected to ground, but you can choose a different address.
3.3 V

3.3 V

3.3 V

3.3 V
R3
10k

GND

V+

SCL

SCL

PTC8

SDA

SDA

GND

KL25Z

PTC9

R4
10k

ADD0

TMP101
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

202

Instrumentation and Microcontrollers Using Automatic Code Generation

Create the top-level model shown below. Note that we are using triggered subsystems with
function call triggers. This is because, every second we want to measure the temperature and then display the
temperature we just read. To enforce this sequence, we use function call triggered subsystems.

Generate a function
trigger from an edge
trigger.

TMP101
sensor read
inside this
block.

Demux block. Used


to sequence events.

Sprintf function to
display the value.

In the TMP101 Inside block, place the TMP101 block and a function call trigger block. Note that a block of the
TMP101 is located in the Sensor Read Functions portion of the RHIT KL25Z Library:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VI:Intelligent Sensors

203

If you double-click on the TMP101 block, you will see that you have several options available:

In addition to the address, you can select the sensor resolution (higher resolution slows down the sensor,
which is not an issue for the example), and you can choose which of the I2C busses and KL25Z pins you would
like to use. For this example, you can select any of the settings, as long as you connect the pins that you
select.
We would like to read the temperature sensor every two seconds, and after reading the sensor,
display the value of the sensor on the LCD display. Almost everything in this model has been covered in earlier
labs. The contents of the Edge Trigger to Function Call Trigger subsystem is shown below and was covered
in Section V.C.2.b) on page 184:

We use this function so often that we created a block for it and placed it in the KL25 library. (Do not modify
this block.) Remember also that we can sequence events using a function trigger and a Demux block. (See
page 190.) The pulse generator will produce a square wave with a period of 2 seconds (1/2 Hz). The Edge
Trigger to Function Trigger subsystem will convert the positive edge to a function trigger. The Demux will
pass the function trigger to the two subsystems, triggering the Read Temperature Sensor subsystem first and
then the LCD Display subsystem second.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

204

Instrumentation and Microcontrollers Using Automatic Code Generation


The contents of the LCD display subsystem are shown below:

We have seen all of this subsystem previously. The remainder of the LCD Display subsystem has been
covered earlier. The format string used in the sprintf MATLAB Function block is: " The temperature is:
%3d.%04d F. " Note that the format string %04d is used instead of %4d. The format string %04d will display
leading zeros as 0 while the %4d will display leading zeros as blanks. If we had a number like 74.05, the
format string %4d would display the number as 74. 5, which is not quite right.
We are done with the modifications to the file. Save the changes. You should be able to build
and download the model to your Freescale FRDM-KL25Z now. Important note about the TMP101/102
sensors. If you use the TMP101 or TMP102 and you change the address by rewiring the address pin,
you will need to cycle the power on the board before the sensor recognizes the change.

Demo VI.1: Demo the TC74/TMP101/TMP102 temperature sensor with the temperature being displayed on the
LCD screen.

Exercise VI.1: Demonstrate the difference between when the TMP101 is used with 9-bit resolution and 12-bit
resolution.
1.
SparkFun BMP085/BMP180 Pressure and Temperature
Sensors
For a second example of an I2C sensor, we will use a BOSCH BMP085 pressure and temperature sensor. This
device has been superseded with the BMP180. The two devices can be used interchangeably in this example.
These sensors are surface mount devices, so we need to use a breakout board from SparkFun Electronics to
access the pins on the sensor. A breakout board is basically a small printed circuit board with large pins on it
so that we can use surface mount devices on our protoboards that would otherwise be too small for us to work
with. The SparkFun website has a large amount of documentation on the BMP sensors and the breakout
board.
First, we will look at the schematic for the breakout board. This schematic was downloaded from
the SparkFun Electronics website:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VI:Intelligent Sensors

205
[2]

We see that all this board really does is provide access to the sensor so that we can easily hook up power,
ground, and the I2C bus wires SCL and SDA. We do note that the board has pull-up resistors already installed,
so we do not need to add pull-up resistors. If you place this sensor on an I2C bus with the TC74 of TMP101 we
used in the previous section, remember to remove the pull-up resistors we used in that example. If we place a
bunch of I2C sensors on the same bus, we only need to have one pull-up resistor on each of the bus wires.
Also, the maximum sensor voltage for the BMP085/BMP180 is 3.6 V. Make sure that you use the 3.3V
power supply from your FRDM-KL25Z board.
Before we create our model, we need to see the format and scaling of the data that the sensor
will provide. Referring to the BMP085 data sheet, we see the following:

The temperature measurement is between 0 and 65 C.


The resolution of the temperature measurement is 0.1 degrees per bit.
The pressure measurement is between 700 hPa and 1100 hPa. Note that hPa is hectopascal, where 1
hPA is equal to 100 pascal.
The resolution of the pressure measurement is 0.01 hPa per bit.

The BMP085/BMP180 have four modes of operation, Low Power, Standard, High Resolution,
and Ultra-High resolution. It is left as an exercise for the reader to review the datasheet for this component to
see the difference between these modes. From a programming point of view, the different modes require
different amounts of time for the sensor to make a measurement. The way the driver works, a command is
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

206

Instrumentation and Microcontrollers Using Automatic Code Generation

issued to begin a measurement. The microcontroller waits a specified amount of time and then the driver reads
and returns the measured value. During the wait time, the processor is not doing anything. Because the
microprocessor is not required by the sensor during the wait time, it is recommended that you place sensor
block inside an atomic subsystem and specify the Tasking Mode as MultiTasking. The BMP180/BMP085
block requires a long sample time because of the wait time. During this wait time, the sensor requires no
attention from the microcontroller. Using an atomic subsystem and specifying the Tasking mode as
MultiTasking will allow the microcontroller to do other tasks during the wait time for the sensor.
A driver block for the BMP085 is provided in the RHIT FRDM-KL25Z Library. The top level of
the model is shown below:

The different colors specify the different sample rates for the blocks in the model 19. Both the BMP085 Inside
and the LCD Display are atomic subsystems with different sample times. See Section V.C.1.b) on page 176
for the steps to set up an atomic subsystem.
The LCD Display subsystem is specified as an atomic subsystem with a Sample Time of one
second. This means that the text display on the LCD screen will be updated once a second. The subsystem is
shown below:

19

To display the sample time colors on your model, select Display, Sample Time, and then All from the Simulink menus.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VI:Intelligent Sensors

207

Since the BMP085/BMP180 outputs the temperature in Celcius, we need to convert the value to Fahrenheit.
There are several ways in which we could have converted the number. Here we choose the MATLAB function
shown below:

The sprintf function has changed slightly because we have modified it to convert two numbers
rather than one. Some of the comment lines have been removed so that the functional code can be displayed
in a single screen capture:

Two input variables specified here.

The two input variables are used here.

Format string modified.

The contents of the BMP085 Inside subsystem are shown below:


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

208

Instrumentation and Microcontrollers Using Automatic Code Generation

The only reason we placed the sensor block inside a subsystem is so that we could make the subsystem
atomic and specify the sample time appropriately. Double-click on the BMP085/BMP180 driver block:

The block tells us the different modes of operation and how long the measurement delay is. When you specify
the sample time for your atomic BMP085 Inside subsystem use the time specified in the screen above. For
this example, you can use any of the available modes. Do not forget to specify the BMP085 Inside subsystem
as atomic and specify the appropriate sample time. If you do forget, your model will overrun.
The last thing we need to do is specify a Fixed step time for the model and specify the tasking
mode as MultiTasking.

Fixed-step size is 0.01.

MultiTasking mode selected.

You should now be able to download and run your model on your FRDM-KL25Z.
Demo VI.2: Demo of the BMP085/BMP180 sensor by displaying the temperature and pressure on the LCD
screen. The values should update once every second.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VI:Intelligent Sensors

209

Exercise VI.2: Create a model that reads the temperature twice with two different temperature sensors. The
model displays both temperatures on the LCD screen for comparison. The display should indicate which
temperature is for which sensor. Note that if you use the TMP101 or TMP102 and you change the address by
rewiring the address pin, you will need to cycle the power on the board before the sensor recognizes the
change.
2.
Real-Time Clock
For a final example, we will work with a real-time clock module that communicates through an I2C bus. We will
use the SparkFun Electronics Real Time Clock Module which is a breakout board for the Maxim Integrated
DS1307 Serial Real-Time Clock / Calendar. This semiconductor uses I2C serial communication to provide date
and time information. Two blocks are provided:

Read Real Time Clock This function reads the current time. This read will fail if the real time clock has
not been set yet.
Set Real Time Clock This function writes a set time to the real time clock module. If the RTC has not
yet been set, you will need program it with the current date and time. Once set, the RTC breakout
board has a battery that will maintain the current date and time. All this block does is program the RTC
once and then it does nothing else.

Note that the RTC module uses a 5 V supply rather than a 3.3 V supply. You will need to connect the 5
V pin of the RTC module directly to the P5V_USB pin on the KL25Z board.

Exercise VI.3: Create a model that programs the RTC with the current date and time. After running this model
once, do not run it again as it will reset the date and time to the values you specified the last time you set the
clock. Note that you need to specify the current time and date in the block parameters.
Exercise VI.4: Create a model that displays the date and time in the format shown below. The display time
should update once a second. You might need to use the %c format string to display a / on the LCD display.
Time: 10:48:59
Date: 04/14/2012
Exercise VI.5: Create a model that reads the three I2C sensors we have studied and flips the display between
the information received from each. The LCD display should change screens once a second. You might need
to use the %c format string to display a / on the LCD display. The alternating screens are shown below:
Time: 10:48:59
Date: 04/14/2013
Temp: 37.9 F.
Barr: 29.50 in.
TC74 Temperature
Temp: 37.9 F.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

210

Instrumentation and Microcontrollers Using Automatic Code Generation

3.
KL25Z On-Board Sensors
The KL25Z has two on-board sensors. A 3-axis accelerometer that uses a Freescale MMA8451 sensor and a
capacitive touch slider. Blocks for both of these sensors are in the RHIT KL25Z libraries and the sensors are
already wired on your boards. Thus, all you have to do is place the blocks in your model and it will work. Well
Nothing is ever that simple, but it is close. The Accelerometer uses the I2C bus 0, so it is possible that it might
conflict with other I2C sensors on your board if you use BUS 0 as well. The accelerometer outputs double
precision numbers between -1 and +1. The touch sensor outputs a number between 0 and 100.
Exercise VI.6: Using the on-board accelerometer, display the acceleration of all three axes on the LCD with at
least 2 decimal places of accuracy. An example output could be:
X: -0.02 Y: +0.05
Z: +0.99
Note that you will need to display the sign properly, and the magnitude can be zero. Remember that we will
need to display both +0 and -0, which is actually tricky. (Because -1 times 0 is 0, not -0)Thus, you may need
to display the sign with the %c formatting character.
Exercise VI.7: Using the on-board Touch Sensor Interface (TSI), display the value returned by the sensor. An
example output could be
TSI Sensor
Slider %: 95
Note that you may need to use the %c format string to display a % symbol.
Exercise VI.8: Create a model that uses a pushbutton to display one of 4 items. The output should change
when the pushbutton is pressed. The output should remain unchanged when the pushbutton is released. The
information displayed should be:
1.
2.
3.
4.

The date and time read from the RTC module.


The temperature read from a TMP101 sensor.
The values of the accelerometer.
The value from the Touch Sensor Interface

It is suggested that you reuse as much of the previously developed models as possible.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

VII.

Memory

Lab VII
Memory

In this section we will look at ways to store data on the FRDM-KL25Z microcontrollers built-in
memory. We will use volatile RAM for these examples. Volatile means that when we cycle the power to or
reset the microcontroller, the information is lost. With the FRDM-KL25Z, we do not have access to the flash
memory for storing non-volatile information.
There are several ways to store variables in Simulink. One obvious method is Stateflow.
Inherently, a Stateflow chart has memory because the chart remembers where it is and knows here it has
been. Also, you can define array variables in Stateflow if needed. Simulink has the Memory block
. The
output of this block is the input value from the previous time step. Thus it remembers its last value. Simulink
structures like those shown below can be used as counters and integrators:

The Simulink Data Store blocks also allow us to store data and access them at their current level or below:

Instead of using these blocks or Stateflow, we will use the MATLAB Function block to create the data
structures we need.

A.

Array Memory

The MATLAB Function block provides access to a subset of MATLAB commands in the Simulink environment.
This will allow us to use many of the MATLAB data structures in Simulink. Here we will set up a simple array to
store values we read from the BMP085/BMP180 pressure and temperature sensor we developed in Section
VI.B.1. (If you do not have a BMP085 or BMP180, you can use any of the sensors we looked at earlier.) You
should be able to reuse parts of those models here. We will start with the BMP085/BMP180 model developed
in Lab 6:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

212

Instrumentation and Microcontrollers Using Automatic Code Generation

In addition to sending the measured values to the LCD, we will store them in memory. We will record the time,
temperature, and pressure signals in an array of ten values. We will create the memory structure using the
MATLAB Function block. We have changed the sample times of the LCD Display and BMP085 Inside
atomic subsystems to be 2 seconds, so no rate transition is needed between the two. The complete model is
shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

213

Period is 1 second.

Sample Time is 2 seconds.

Period is 10 seconds.

External Mode Setup


block added.

Lab VII: Memory

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

214

Instrumentation and Microcontrollers Using Automatic Code Generation

The BMP085/BMP180 sensor and LCD portions of the model are copied from Section VI.B.1. This portion of
the model reads the sensor every two seconds and displays the values on the LCD screen. The new portions
of the model, detailed in the screen below, records the time, temperature, and pressure every 10 seconds and
stores them in static RAM on the controller board:

Instead of using the RTC clock module from Section VI.B.2, we will create our own timer using an integrator.
The timer subsystem is shown below:
This is an Out block
renamed as Time.

The output of the subsystem is the time integral of the input, which is constant at 1:

= 1 =

to is the time we turn on our microcontroller and start integrating. We will let to equal zero, so the output of the
block is just the time since we started the microcontroller.
The Ring Memory block in our model from page 213 is actually a subsystem that contains an
edge trigger and a Ring memory block from the RHIT Library

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

215

The MATLAB Function is shown below 20:

The line r=10; defines the size of the memory storage. We are going to create three one dimensional arrays.
r defines the size of these arrays. For this example, each array will have 10 elements. You can change the
size of the arrays by changing the value of r.
The line persistent time_arr temp_arr pressure_arr count; defines the listed
variables as persistent. This means that these variables retain their values between the times the block is
executed. Without this line, each time the MATLAB Function block is executed, the variables would be re20

This block is contained in the RHIT KL25Z library, so you do not need to create the entire function yourself.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

216

Instrumentation and Microcontrollers Using Automatic Code Generation

initialized and not retain any of their previous values. Effectively, the persistent command allocates our
memory storage in RAM and instructs the controller to retain the values until the controller is restarted.
if isempty(count)
count=0;
time_arr=zeros(r,1);
temp_arr=zeros(r,1);
pressure_arr=zeros(r,1);
end
The first time the function runs, the persistent variables will not be defined. The code segment below checks to
see if the persistent variables are defined. If they are not defined, the arrays are defined, the memory is
allocated, and the variables are initialized to zero. If the variables have been previously defined, the lines will
be skipped and the values will not be set to zero. (They will retain the values they had from the previous time
the block was executed.)
The code segment below implements a rolling counter.
if count == r
count = 1;
else
count = count + 1;
end
For r elements, the count goes from 1 to r. When the count hits the value of r, the next value of count is
reset to 1. The count then increases again. Thus count, which is the index to our memory, counts from 1 to
the max value, and then restarts again at 1 and continues circulating until we stop the microcontroller. With this
method, the memory records the last r data points. We will have to keep track of the beginning and end of the
array, but that is the task of a future lab. For now, we will just record values. Also note that you could just have
the count go from 1 to the end and stop there, recording only the first r values. In either case, the goal here is
memory storage. With the flexibility of MATLAB, you can design your memory storage for your particular
application.
The lines below:
time_arr(count) = Time;
temp_arr(count) = Temp;
pressure_arr(count) = Pressure;
store the present values in the array. Only one value for each measurement is stored. The next lines specify
the output of the function.
time_data = time_arr;
temp_data = temp_arr;
pressure_data = pressure_arr;
Note that the outputs of the function are the complete arrays of all of the stored data. Note again that we could
select a single point if we wanted.
Lastly, we will have the output of the arrays go to Display blocks (Simulink / Sinks library). We
have them elongated because each block will display an array of values, in this case 10 elements each.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

217

Lastly, we will look at the Model Configuration Parameters. First, we are choosing a fixed step size of 0.1
seconds and a discrete solver. Since we have atomic subsystems, we also specify the Tasking mode as
Multitasking:

Stop time specified as


infinity.

MultiTasking selected.

Run your model on your target and enable external mode. (See Section II.D.3 on page 77 for the steps to set
up External Mode.) You will see the memory add a new value every 10 seconds. The LED should flash at a 1
Hz rate. Data values are read from the BMP085/BMP180 once every two seconds. Data is stored in the
memory every 10 seconds. Below are several screen captures showing that the memory is updated every 10
seconds:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

218

Instrumentation and Microcontrollers Using Automatic Code Generation

The screen capture below shows that the memory index has rolled over and restarted at the beginning:

New
values
here.

New
values
here.

Demo VII.1: Demonstrate the working memory block with 10 elements.


Exercise VII.1: Determine the maximum size of the ring memory that you can use on the Freescale FRDMKL25Z. When the memory is too large, you will get an error stating that you had a RAM overflow:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

219

Exercise VII.2: In Demo VII.1 we are saving data as double-precision floating point data types that use 8 bytes
of data per number stored. Since each number has at most 2 decimal places of accuracy, we could multiply the
numbers by 100 and then save the data as 16-bit unsigned integer data types (assuming that the temperature
is never negative). This would allow us to save 4 times as many data points in the available memory. Rewrite
the model to save the data as 16-bit unsigned integers. The MATLAB command uint16(x) converts x to an
unsigned integer and saves it as an unsigned16-bit value using two bytes of memory.

B.

Min Max Memory

In the next example, we will keep track of the min and max values of the BMP085/BMP180 sensor outputs
using a MATLAB Function block. The top level of the model is shown below:

The model looks similar to what we had before. However, the LCD subsystem has been modified. Looking
inside the Min-Max LCD Display subsystem, we see the following:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

220

Instrumentation and Microcontrollers Using Automatic Code Generation

We have added two new MATLAB Function blocks called Min_Max_Memory and modified the sprintf function.
Both Min_Max_Memory blocks are the same and shown below:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

221

The function defines Max_u and Min_u as persistent, so that the function will remember those values. Min_u
is initialized to infinity so that the next valid reading will be less than the initial value and recorded as the
current minimum. Max_u is initialized to negative infinity so that the next valid reading will be more than the
initial value and recorded as the current maximum. Finally, the first two readings are ignored as the initial
values returned by the sensor are not always valid. The block outputs the maximum and minimum values, and
these values are held until the FRDM-KL25Z microcontroller is reset or the power is cycled.
The sprintf function has been modified to display the minimum value, current value, and the
maximum value of the temperature and pressure values. Remember to add spaces so that text lines up
correctly when displayed on the LCD screen.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

222

Instrumentation and Microcontrollers Using Automatic Code Generation

and

Demo VII.2: Demo the operation of the BMP085/BMP180 with the Min_Max_Memory block and the LCD
displaying the following
Min_Temp,
Actual_Temp,
Max_Temp
Min_Pressure, Actual_Pressure, Max_Pressure
Display values with one decimal place of accuracy.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

223

Exercise VII.3: Modify the Min_Max_Memory block so that it has a reset input. When the reset occurs, the
minimum and maximum values are reset to the current value. For testing, use a pushbutton to reset the values.

C.

Stateflow Memory and the Switch Case MATLAB Command

In this section we will look at using a Stateflow chart for memory. We will also look at using some of the more
complicated MATLAB programming structures to display different messages on the LCD display. The top level
of the model is shown below:

The model fixed-step size


is 0.01 seconds.

Atomic subsystem with a


sample time of 0.2 seconds.

Atomic subsystem with a


sample time of 2 seconds.

The Fixed-step size of the model is 0.01 seconds. Although for this example we do not need such a small
step, we are using it in case we wanted to add other applications that required a fast response. The
BMP085/BMP180 subsystem has a Sample time of 2 seconds because temperature and pressure are a
slowly varying signals and we do not need to sample them any faster. The LCD display system has a Sample
time 0.2 seconds. Although the displayed information does not change rapidly, we do want the display to
change quickly when we press a pushbutton.
The Mode Select and Function Select subsystems use a Stateflow chart to keep track of how
many times a pushbutton has been pressed. The Mode Select subsystem is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

224

Instrumentation and Microcontrollers Using Automatic Code Generation

This digital input reads a


pushbutton switch that
uses a pull-up resistor.

Both of the memory subsystems use a digital input to read the pushbutton and a debouncer to clean up the
signal. Since the pushbutton uses a pull-up, the output of the switch is normally high, and goes low when we
press the pushbutton. We need an output that is normally low, so we added a NOT gate after the digital input.
The output of the NOT gate is normally low, and goes high when pushbutton is pressed. (We could have used
a pull-down resistor and eliminated the NOT gate.) Note that this subsystem has a second output called
Button_Press. Whenever the pushbutton is pressed, this output will change to a 1. This output will be used to
reset the second chart we will discuss later. The debouncer was covered in Section V.C.2.a). Here, we are
interested in the looking at the chart called SF Memory 1:

This chart keeps track of the pushbutton. As the pushbutton is pressed and released, the value of the output
cycles through one of three values. Note that the value of the output changes when the pushbutton is pressed.
When the pushbutton is released, the output stays at its current value. This chart is a simple counter that
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

225

remembers how many times a pushbutton was pressed. Remember to declare State as a chart output and SW
as a chart input.
The Function Select subsystem is shown below:

The subsystem looks similar to the Mode Select subsystem except for the Reset input. The SF Memory 2
chart is shown below:

When Reset is equal to


1, we exit the superstate.

Superstate.

If we did not have the superstate shown above, this chart would be equivalent to the previous chart. To make a
super state, all you need to do is make a state large by dragging one of its corners. Then you can place it on
top of other states, drag states into it, or place new states inside of it. Make sure that no edges overlap or the
states will display in red indicating a problem. The reason for the super state and the Reset signal is that no
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

226

Instrumentation and Microcontrollers Using Automatic Code Generation

matter what state we are in, when we receive the Reset signal, we return to the initial state, State_00. The
chart above is logically equivalent to the one shown below:

Both implementations work the same. However, the implementation with the superstate is a lot cleaner, easier
to understand, and will be easier to modify if we update it or change its function.
The reason for the two pushbutton subsystems is the following functionality. The Mode Select
pushbutton selects between displaying the pressure and temperature, the temperature, and the pressure. The
Function select switches between displaying the current value, the maximum value, or the minimum value.
Whenever you change the mode, the function select is reset to display the current value of whatever it is
displaying. Or, as a list of functionality:

Mode Select 0 Display the pressure and the temperature on the LCD.
o Function select has no effect.
Mode Select 1 Display the temperature on the LCD screen.
o Function Select 0 Display the current temperature, maximum temperature, and minimum
temperature.
o Function Select 1 Display the maximum temperature.
o Function Select 2 Display the minimum temperature.
Mode Select 2 Display the pressure on the LCD screen.
o Function Select 0 Display the current pressure, maximum pressure, and minimum pressure.
o Function Select 1 Display the maximum pressure.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

227

o Function Select 2 Display the minimum pressure.


Whenever the Model Select is changed, the Function Select is set back to 0.

We have created the Stateflow charts to keep track of the Mode and Function selections. Now we need to
modify the sprintf function to display different information. The Min-Max LCD Display subsystem is shown
below:

The sprintf function has been significantly modified. The first few lines look similar to what we had before
except we added Mode and Select as function inputs:

We have added a switch-case statement to select between several different sprintf lines to emit the correct
text string:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

228

Instrumentation and Microcontrollers Using Automatic Code Generation

Instead of having a single sprintf statement, we can use many of the available functions in MATLAB to choose
between one of several sprintf statements. We could have implemented this logic in Simulink with switches,
but it is far easier and cleaner to do it in a MATLAB function block, especially since we are required to use the
sprintf function in a MATLAB Function block. Note also that we could have used nested if statements to
implement the logic shown above. However, we have illustrated the use of if statements in previous MATLAB
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VII: Memory

229

Functions. The reader is encouraged to view the many resources available in MATLAB to see the extent of
functions available for programming.
Demo VII.3: Demo the BMP085/BMP180 with the Mode Select and Function Select pushbuttons.

D.

Multiple Sensor Projects

Note that blocks for all of the sensors used in this section are available in the RHIT library.
Exercise VII.4: Modify the model created in Demo VII.3 to implement the functionality below:

Mode Select 0 Display the pressure and the temperature on the LCD display.
o Function Select has no effect.
Mode Select 1 Display the temperature on the LCD screen from the BMP085/BMP180 sensor.
o Function Select 0 Display the current temperature.
o Function Select 1 Display the maximum temperature.
o Function Select 2 Display the minimum temperature.
Mode Select 2 Display the temperature on the LCD screen from the TC074 sensor.
o Function Select 0 Display the current temperature.
o Function Select 1 Display the maximum temperature.
o Function Select 2 Display the minimum temperature.
Mode Select 3 Display the temperature on the LCD screen from the TC074 sensor, the
BMP085/BMP180 sensor, and the average of the two sensors.
o Function Select has no effect.
Mode Select 4 Display the pressure on the LCD screen.
o Function Select 0 Display the current pressure.
o Function Select 1 Display the maximum pressure.
o Function Select 2 Display the minimum pressure.
Mode Select 5 Display the time and date as read from the RTC module.
o Function Select has no effect.

Exercise VII.5: Modify the model created in Demo VII.3 to implement the functionality below:

Mode Select 0 Display X, Y, and Z components from the on-board accelerometer.


o Function Select 0 Display all three components.
o Function Select 1 Display the X component only.
o Function Select 2 Display the Y component only.
o Function Select 3 Display the Z component only.
Mode Select 1 Display the temperature on the LCD screen from a temperature sensor.
o Function Select 0 Display the current temperature.
o Function Select 1 Display the maximum temperature.
o Function Select 2 Display the minimum temperature.
o Function Select 3 Not allowed to happen. In Model Select1, the Function Select counter
should count from 0 to 2. Three should not be an available choice in Mode Select 1.
Mode Select 2 Display the value of the on-board slider in percent.
o The Function Select switch has no effect.
Mode Select 3 Display the time and date as read from the RTC module.
o Function Select has no effect.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

VIII. Collecting Data 1

Lab VIII
Collecting Data 1

In this lab and Lab IX we will look at collecting data with a sensor and storing that data. In this lab we will
record data on the FRDM-KL25Z controller using the volatile RAM. The data will be sent over a serial data line
to a Windows computer. We will use MATLAB to read the data from the serial port and store it in a MATLAB
array. Once read, the data will be in the MATLAB workspace where it can be saved to the hard disk, plotted, or
manipulated with MATLAB to suit our needs.
This method has two major limitations. First, the data is stored in RAM on the FRDM-KL25Z. If
the board loses power or the board is reset before we transmit the data to the Windows computer, all of the
data stored in RAM will be lost. Second, since we are using a serial link, the data takes time to transmit and is
error prone. Furthermore, we are limited in the amount of data we can collect because of the errors and the
amount of time it takes to transmit the data. These limitations are eliminated in Lab IX when we use an onboard SD card to record the data. Although this method is not reliable for collecting a large amount of data over
a long period of time, the methods here can be used to create a monitor that will allow us to view the status of
our controller by sending and viewing signals over the serial link.
For this lab, we will develop a single large model that collects data from sensors, saves the data
in the controller RAM using a memory structure similar to what we developed in Lab VII, displays the most
recent sensor data on the LCD screen, and transmits that over a serial link. We will also develop a MATLAB
script to read and record the data.

A.

Serial Communication with Simulink

We will use the SparkFun FTDI Basic USB to TTL serial converter shown below 21:

Connect to a USB port.

This board plugs into a USB port and adds a serial communication port to your computer. When you plug this
board into a USB port, a driver should be installed and then a new serial communication (COM) port should be

21

You can use any FTDI communication board for this application. You can also use the SDA port and UART0 for this
chapter. However, if you use UART0, you will not be able to use external mode to monitor your model.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

231

created. Use the Windows Device Manager 22 to see that the device was added and determine the name of the
newly added port. On my system, the port was labeled as COM18:

Newly added port

We will need to know the COM port number when we read data with MATLAB.
We will connect the USB serial port to UART2 of the FRDM-KL25Z. When connecting two RS232 serial devices together (its not really RS-232 because the voltage levels are TTL compatible), the RX line
of one device must connect to the TX line of the other device. Connect the serial port to your FRDM-KL25Z
board as shown below:

Connect to PTD5 on the FRDM-KL25Z.


Connect to PTD4 on the FRDM-KL25Z.
Do not connect the 3V3 pin.

Connect to ground on the FRDM-KL25Z.

Note that the power for the FTDI will come from your computers USB port and not the 3.3 V supply of the
KL25Z. (If you connect the 3V3 pin on the FTDI to the 3.3 V supply on the FRDM-KL25Z, the KL25Z will lose
power.) Next, we will create a Simulink model that sends out a single line of text. The top level is shown below
and consists of many of the blocks and subsystems we have used previously:

22

To open the Device Manager in Windows 7, open the Start menu, right click on Computer and then select Properties.
The System window will open. In the upper left corner, click on Device Manager to open it.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

232

Instrumentation and Microcontrollers Using Automatic Code Generation

When the pushbutton is pressed, the model will transmit a single line of text on UART2 which we will display
with a terminal emulator and later read with MATLAB. Nearly the same line of text will be sent out on UART 1
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

233

to be displayed on the LCD screen. We are using a pushbutton so that we transmit a single line of text at the
time of our choosing. The Push Button subsystem is shown below:

It uses the switch debouncing Stateflow chart developed in Section V.C.2.a). When the pushbutton is pressed,
the output (of this entire subsystem) will go high. Electrically, the pushbutton switch is using a pull-up resistor.
When the pushbutton is released the output will go low. We are using the debouncer because our subsystems
are edge triggered and we want to guarantee that each press only generates a single edge.
The Counter chart is a simple counter that starts at zero and increments every time the
pushbutton is pressed. We use this so that we can tell that we are emitting a new and unique text string every
time we press the pushbutton:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

234

Instrumentation and Microcontrollers Using Automatic Code Generation

The two sprintf MATLAB embedded functions are nearly identical. The only difference between the two is that
we need to tack on a \n character when the data is to be read by MATLAB and the terminal emulator. The
Sprintf for Data Transfer MATLAB Function is shown below:

This line was also updated.

Note this \n.


This text string is 32
characters long. The \n
counts as one character.

Note that we have added a \n to our output string. You may recall that in formatted output with the sprintf or
fprintf functions, a \n in the text string generates a new line character. We will use this new line character to
jump to the next line when we display the text on a terminal emulator. When we read the text with a MATLAB
function, the \n will mark the end of the text line. The Sprintf for LCD MATLAB function is almost the same
except it does not contain the \n.
No \n here.

Space added to keep the text string 32


characters long.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

235

It is important to note that both embedded functions output a text string that is 32 characters long. Make sure
that you pad your text with spaces so that each is 32 characters in length.
The Edge to Function Call subsystem is an edge triggered subsystem that outputs a function call trigger:

We use this subsystem to convert an edge trigger to a function call trigger. We convert edge triggers to
function triggers so frequently that we added a block to the RHIT library to perform this function.
Putting function call triggers into a Demux allows us to sequence subsystems in time. When the
Demux below receives a function call trigger, the Write Text to Serial Port (UART2) subsystem executes first.
When it is done, then the Write Text to LCD (UART1) subsystem will execute:

When used with a function call, the Demux generates a function call for the left most subsystem. When this
subsystem has completed its task, the Demux generates a function call for the next subsystem closest to the
left. The systems are executed from left to right. Note that this method works for function call triggers only, and
the subsystems attached to the Demux must use a function call trigger (not an edge trigger).
Subsystem Write text to Serial Port (UART2) converts the text string an array of uint8 data
types and then outputs it on UART2:
Select UART2 for this block.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

236

Instrumentation and Microcontrollers Using Automatic Code Generation

Note that there are no control characters prepended to the text string as we did with the LCD. The Write Text
to LCD (UART1) subsystem is shown below:
Select UART1 for this block.

This is the same function we have used previously to drive the LCD. Note that the control characters [254,
hex2dec('01')] that we prepend to the text string instruct the LCD to clear the screen and place the cursor at
position 1 of the LCD. We do not want these control characters prepended to the text string that we send to
UART2 as they contain no data.
Make sure that you specify the BAUD rate for both UARTs on the FRDM-KL25Z. To do this,
open the Model Configuration Parameters window (type CTRL-E) and select the Coder Target pane. Specify
the BAUD rate for UART1 and UART2 as 9600:

BAUD rate
specified here.
Coder Target
selected.

UART2
selected.

Demo VIII.1: Now that we have a model that outputs a text string to a UART, we can test that model using a
serial communication program on your computer. Connect the SparkFun FTDI Basic USB port to a USB port
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

237

on your computer. Run a communication program (such as SecureCRT 23) to verify that the model is sending
out text and that your hardware is correct. The LCD display and serial communication program should display
a new line of text every time you press the push button. Note that your communication program will have to
specify the port used by the FTDI (COM18 in my case) and the same BAUD rate (9600).You should see
something similar to that shown below:

When done, exit your serial communication program because it uses the COM port that MATLAB will need to
use in the next section. Remember that the communication settings of your communication program must be
set the same as the Simulink settings. We set the BAUD rate to 9600 so make sure that your communications
settings specify 9600. Other settings that might be set by Windows include the parity, number of data bits, and
number of stop bits. By default, these are usually set to no parity (N), eight data bits (8), and one stop bit (1).

B.

Serial Communication with MATLAB

Now that we can output a text string to the serial port of the FRDM-KL25Z, and that serial port is connected to
the USB port of our Windows computer, we need to read the data on the port with MATLAB. Note that in this
example, we are reading data with MATLAB and not the communication program as in the last example. Close
the communication program that you were using earlier. Create a new MATLAB .m file and save it with the
name Lab8_Matlab1.m. Enter the code segment below:

23

A 30-day free trial of Secure-CRT is be available on-line.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

238

Instrumentation and Microcontrollers Using Automatic Code Generation

When we looked at the Windows Device Manager, we noticed that the USB to serial port device was labeled
as COM 18. The line s1 = serial('COM18'); creates a serial port object (s1) associated it with COM18.
The line fopen(s1); opens the port for reading and writing. The line x=fscanf(s1,'%s') reads a text
string from COM18 and stores it in variable x. The fscanf command will read every character in the COM port
buffer until it encounters a \n character, where it will stop. If there are more characters in the buffer after the \n
is read, we will need to call the fscanf command one or more times to read the remaining characters. The
line fclose(s1) closes the COM port and the line clear s1 removes variable s1 from the MATLAB
workspace. After we issue the commands fclose(s1) and clear s1, we can reopen the port using the
commands s1 = serial('COM18') and fopen(s1). If we do not close the port and clear s1, we will get an
error if we try to reopen the port again.
The code segment:
s1 = serial('COM18');
fopen(s1);
x=fscanf(s1,'%s')
fclose(s1);
clear s1;
opens the COM port, reads a single text string (up to the first \n character), and closes the COM port. This is
not how we want to use this facility. We want to open the COM port. Then every time we press the pushbutton
to send a text string, we want to issue the command x=fscanf(s1,'%s') to read the text string. We will
keep pressing the pushbutton and using the x=fscanf(s1,'%s') command to read the test strings until we
have convinced ourselves that the system works. When we are done, we can use the commands
fclose(s1) and clear s1 to close the port.
It does take MATLAB a long time to open the port, so we have modified the script to emit a text
message when the port has been opened:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

239

Run the script and then press the pushbutton after you receive the text message from MATLAB. Note that the
text message, Press the Pushbutton now. Will appear in the MATLAB command window. Note that it takes a
while for the message to be displayed and data to be received.

Command window.

When you press the pushbutton, the value of x should be:


x =
Thisisatest.Count=1.
Note that spaces have been removed from the text string. This is because the fscanf command with the %s
format string removes the spaces from the text strings. Thus, the communication works as it should. The
second time we run the script and press the pushbutton, we get:
x =
Thisisatest.Count=2.
Note that if you issue the command x=fscanf(s1,'%s') before data is present, it will wait for data on the
port. In our case, it will sit there and wait for you to press the pushbutton. If you wait too long, it may timeout
and generate an error, as shown below:
>> x=fscanf(s1,'%s')
Warning: Unsuccessful read: A timeout occurred before the Terminator
was reached.
x =
''
Finally, if we use the %c format string, we will read the spaces in the text string as well. Change the %s to a %c
in the .m file and run the script again. Press the pushbutton when you receive the text message:
>> x=fscanf(s1,'%c')
x =
This is a test.
Count =
8.
>>
Note that when we use the %c format string, x is a 1x32 array of type char. When we use the %s format string,
x is a text string. (If you look in the workspace, you will notice that they are listed differently.) We will be using
text strings (%s format) in the next example because spaces in the data are not necessary and will be ignored.
Demo VIII.2: Demonstrate the operation of sending serial text with the controller and receiving the text with
MATLAB.

C.

Data Collection Simulink Model

We will now create a model for measuring data from a sensor, storing that data in a memory structure, and
then transmitting that data over a serial port. The complete model is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

240

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

241

The model contains two atomic subsystems. Read Sensors and Display on LCD is an atomic subsystem with
a sample time of 2 seconds. This subsystem reads the BMP180/BMP085 pressure and temperature sensor
and also displays the current measurement on the LCD display. We are sampling data every two seconds, so
we do not need to execute this system at a faster rate. Furthermore, both the BMP180/BMP085 sensor and the
serial transmit used in this subsystem take a long time to execute while requiring little processor power. These
properties make it ideal to place these functions in an atomic subsystem as we will avoid overruns and free the
microcontroller for other tasks. The Transmit Collected Data Using UART transmits a large amount of
collected data using another serial transmit block. Because we are transmitting a large amount of data, it takes
a long time as well. Further, we only need to send data rarely, and we do not care that it takes a long time to
transmit. Thus we have placed this function inside an atomic subsystem with a sample time of 1 second.
Many portions of this model have been covered previously, and you should make use of models
that you developed previously. First, we need to measure some data. For this example, we have chosen the
BMP085/BMP180 to measure pressure and temperature 24. The sensor block is contained within the Read
Sensors and Display on LCD subsystem:

To monitor that the system is working, we continue to use the flashing LED and we also display the most
recent sensor values on the LCD display. The display updates every 2 seconds. The LCD will also display the
number of samples collected and saved in the FRDM-KL25Zs memory, which we will discuss later. The LCD
Display subsystem is the same as we have used numerous times with the slightly modified format string
shown below:

This sensor gives us temperature and pressure. We would also like to record the time at which the samples
were taken. We will integrate a constant input of 1 to create a time signal:

24

You can use other sensors if you wish. You need to measure at least two different quantities.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

242

Instrumentation and Microcontrollers Using Automatic Code Generation

We will store the data in a linear memory similar to what we did in Section VII.A . Note that we only store a
value in the memory every 10 seconds even though we sample the sensor every 2 seconds. The block
uses the Linear Memory located in the RHIT libraries:

The memory uses the MATLAB embedded function below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

243

The memory stores ten rows of data (r=10). You can store more data if you desire. The data is stored in
column arrays, in this case 10 rows by 1 column. Note that the outputs of the function are the complete data
arrays, not a single value. Also note that the function has an input called Reset. When the array fills up with
data, it stops saving data. When the Reset signal is set to one, the counter is reset to zero, allowing the
subsystem to overwrite data in the array and start saving values again. We will not use Reset functionality yet.
Finally, we are also outputting the index into the array. If we use arrays larger than 10 elements,
we might not use the entire memory structure. The variable Num_Data_Points is the number of rows of data
that we have collected. We will use this value to only transmit the data that has been collected and not transmit
an array full of zeros.
The new part of this model is the Transmit Collected Data Using UART subsystem. It contains
a triggered subsystem that runs when the Linear Memory indicates that is full:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

244

Instrumentation and Microcontrollers Using Automatic Code Generation

We see that the subsystem is triggered when the Linear Memory indicates that ten rows of data have been
collected. The triggered subsystem, called Write Data, contains a For Iterated loop that repeats for the
number of rows of non-zero data saved in the array:

Inside the For Iterator Subsystem, we have:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

245

The For Iterator starts at 1, and then every block in the subsystem is executed. Then the For Iterator
increments, and the blocks in the subsystem are executed again. The process repeats until the For Iterator
hits the maximum count. Thus, the For Iterator Subsystem is used to repeat a set of blocks for a specified
number of times. In this application, the For Iterator counts from one to the number of rows of non-zero data
contained in the Linear Memory block. The number of rows is specified by signal Num_Data_Points and is
equal to 10 in this example. The For Iterator block outputs the value of the count so that we can use it as an
index into the arrays:

Output the index so we can


use the value.

Start the count at 1.

The Index Vector block

allows us to address a specific value stored in a vector. In our case each vector holds up to 10 values. The
Index Vector block allows us to pick out a specific element. In this case, we will pick out the value indicated by
the For Iterator counter. Since the For Iterator counts from 1 to the number of rows of data, this subsystem
allows us to step through all of the data and transmit one line at a time. The Index Vector block should also
specify ones-based indexing:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

246

Instrumentation and Microcontrollers Using Automatic Code Generation

Specify that the first


element in the array has an
index of 1.

The output of the Index Vector blocks is one row of data for the time, temperature, and pressure. We then
transmit these on UART2 with the following format:

Note that the values are separated by semicolons. In this application, the semicolon (;) is called the delimiter
and will be used to parse individual values. Also remember that the line is terminated with a \n. The reader we
will create will separate the numerical values based on the delimiter (;) and determine the end of a line by the
\n. Note that the format of the data is three real numbers separated by semicolons (;). Example output is
shown below:
9.9;
20.0;
30.0;

70.8;
29.31;
70.8;
29.31;
70.8;
29.31;
Note that the For Iterator loop takes a different amount of time to execute based on the number
of rows of data. Because transmitting this data could take a long time, subsystem Transmit Collected Data
Using UART is an atomic subsystem. For the model to run in real-time, this atomic subsystem, which includes
the For Iterator Subsystem, must finish within sample time specified by the atomic subsystem. We have
specified the sample time to be one second, which should be more than enough to transmit ten rows of data. If
you collect and transmit more than ten rows, you may need to increase the sample time.

D.

Data Collection MATLAB Script

The script for reading the data will now be discussed. The code to open the serial port and initialize the
arrays is:
%% Open the port
s1 = serial('COM18');
fopen(s1);
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

247

dat=zeros(1,3);
data=[];

The lines s1 = serial('COM18') and fopen(s1) create a serial port object and open the port. These
lines were discussed in detail in Section VIII.B. The line dat=zeros(1,3) initializes the array named dat and
fills it with zeros. This variable will be used to store one row of transmitted data. data=[] initializes variable
data to an empty matrix. This variable will be used to store all of our data and will be constructed by using
concatenation. We will grow the array as we add data.
The lines for reading and parsing data are:
%% Wait for and receive data
Data_Received=0;
fprintf('Waiting to receive data.....\n');
while Data_Received==0
if s1.BytesAvailable>0
pause(2);
while s1.BytesAvailable>0
x=fscanf(s1,'%s');
a=textscan(x,'%f%f%f', 'delimiter',';');
for j=1:3
dat(j) = a{j};
end
data=[data;dat];
end
Data_Received=1;
end
end

The sequence of events is as follows. You will start the data collection model running on the
FRDM-KL25Z target. It will be a long time until ten rows of data have been collected and that data is
transmitted. In the meantime, you execute this script. Variable Data_Received is initialized to zero, which
means that the outer while loop will repeat until data is received. Serial port object s1 has several fields.
s1.BytesAvailable tell us how much data is available at the port. Until data is transmitted
s1.BytesAvailable will be zero, meaning that the if s1.BytesAvailable statement is false. For most
of the time, no data will be present, meaning that the if statement will be false and the outer while loop will
repeat but do nothing.
Once data becomes available on the port, the if statement becomes true. We pause for 2
seconds to allow all of the data to be transmitted by the FRDM-KL25Z. The inner while loop will then repeat
until no more data is available, which means that all of the data will be read. The next few lines read the data
and save it as numeric data in variable data. The line x=fscanf(s1,'%s') reads text from the serial port
until it encounters a new line character (\n), where it stops. Remember that x will be a text string with the
spaces removed. The line a=textscan(x,'%f%f%f', 'delimiter',';') scans through text string x and
parses it into three floating point numbers using a semicolon (;) as a delimiter. Variable a is a structure with
three values. The lines
for j=1:3
dat(j) = a{j};
end
take the values in structure a and place them in the row victor dat. Finally, the line data=[data;dat] builds
the matrix named data. It does this using a process called concatenation. The new value of data is the old
value of data with a new row added to the bottom. The new row being the data contained in row vector dat.
Note that matrix data grows each time we add a new row to the matrix. This type of matrix is called a dynamic
matrix because it changes in size as the program runs. In general, this method is discouraged because the
process of growing a matrix means that we have to allocate memory each time the matrix grows. This process
is very slow and memory intensive. The method has the benefit that the matrix has the correct size when we
are done, not too big and not too small. A different way of doing it would have been to declare data at the
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

248

Instrumentation and Microcontrollers Using Automatic Code Generation

beginning, such as data=zeros(10,3). The problem with this is that we need to pick a size that we know is
greater than or equal to the amount of data we will collect. In this application, it is easy to size this array. In a
real world application, we may need to pick a giant array to accommodate the largest amount of data we
anticipate collecting.
When all of the data on the port has been read, the while loop will exit. We then close the port and clear s1
with the code:
%% Close the port
fclose(s1);
clear s1;
The last thing we will do in the script is display the data nicely:
%% Display the collected data.
fprintf('Data Received!\n\n');
fprintf('Time
Temp (C)
Press (inHg)\n');
fprintf('------ ------------------------\n');
[r,c]=size(data);
for i=1:r
fprintf(' %4.1f
%5.1f
%5.2f\n', data(i,:));
end
An example of the collected data is shown below. Note that it will take some time before the
data is collected and sent to MATLAB. Be patient while you collect data. (For testing purposes, you might
want to shorten the sample period to 2 seconds so that collecting 10 data points takes 20 seconds
rather than a long time. Especially if you need to run the script several times to debug it.)
Note that you should run the .m file first and then reset your KL25Z so that it collects new data and then sends
the data. The model on the KL25Z only sends data once after it has been collected. If the data was sent before
you ran the data collection script, the script will sit forever waiting for data since the data will never be resent.
>> Lab8_Matlab2
Waiting to receive data.....
Data Received!
Time
Temp (C)
Press (inHg)
------ -----------------------9.9
71.2
29.28
20.0
74.8
29.27
30.0
76.8
29.28
40.0
77.5
29.28
50.0
77.9
29.28
60.0
82.0
29.28
70.0
83.1
29.28
79.9
84.2
29.29
89.9
81.3
29.28
99.9
79.5
29.28
We can now use MATLAB to generate plots and do cool stuff with the data:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab VIII: Collecting Data 1

249

Demo VIII.3: Demonstrate the operation of your data collection routine. Collect sensor data every 10 seconds,
store a total of 10 rows of data, transfer the data to MATLAB, show the contents of the data array, and then
plot the temperature data versus time.
Exercise VIII.1: Create a Simulink model and MATLAB script that accomplish the following task. The Simulink
model collects time, temperature and pressure data the same as in Demo VIII.3. When the memory is full with
10 rows of collected data, the data is automatically transmitted on the serial port. After transmitting the data,
the Simulink model collects another 10 rows of data, which is again automatically transmitted when available.
The MATLAB script waits for the data and automatically concatenates the received data to the data array
without user intervention. After receiving the data and appending it to the data array, the script waits for more
data to be sent. This process should continue until the script collects 100 rows of data, all of which are saved in
a single array. The MATLAB script should output a status message each time it receives data so that we can
monitor its progress. When done, the script will plot the temperature and pressure data. An example would be:
Received
Received
Received
Received
Received
Received
Received
Received
Received
Received

10 rows of data. Time = 99.9


20 rows of data. Time = 199.9
30 rows of data. Time = 299.9
40 rows of data. Time = 400
50 rows of data. Time = 500
60 rows of data. Time = 600
70 rows of data. Time = 700
80 rows of data. Time = 800
90 rows of data. Time = 900
100 rows of data. Time = 1000

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

IX.

Collecting Data 2

Lab IX
Collecting Data 2

We will continue our quest to collect data in this lab and also expand our toolkit to include
storing data on an SD card, which will give us the ability of storing gigabytes of data in non-volatile flash
memory. This solves the two problems encountered in Lab VIII of storing data in volatile RAM and transmitting
the data over the serial port. Here, we will write the data to a MicroSD card in a fashion that we will not lose
data if the FRDM-KL25Z is reset or loses power, and we transfer data to another computer by removing the
MicroSD card from the FRDM-KL25Z and inserting it into another computer.
For this application, we will be using a MicroSD Breakout board from Adafruit Industries [3]. The
one difference between this example and previous examples is that this breakout board uses a Serial
Peripheral Interface (SPI) BUS rather than the I2C Bus covered earlier.

A.

The SPI BUS

The SPI bus is a 3-wire bus, as compared to the I2C bus which uses two wires. There will be one
master device and then one or more slaves. Unlike the I2C bus that requires an address to determine the slave
that is being addressed, the SPI bus uses a dedicated Slave Select (SS) line. The lines are usually referred to
by the following terminology [4]:

SCLK Serial clock provided by the master.


MOSI Master output, slave input
MISO Master input, slave output
SS Slave select (active low and output from the master)

In our case, the master will be the Freescale FRDM-KL25Z and the slave will be the MicroSD breakout board.
The terminology for the MicroSD card is slightly different:

CLK Serial clock (Should connect to SCLK on the master.


DO Data out (Output data of the slave; connect to MISO of the master.)
DI Data In - (Input data of the slave; connect to MOSI of the master.)
CS Chip select (active low and output from the master.)

The SPI pin connections for the Freescale FRDM-KL25Z are the specified on the SD Card Write block and
you will have a choice of busses.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IX: Collecting Data 2

251

DO of the MicroSD board should go to MISO of the Freescale FRDM-KL25Z and DI of the MicroSD should go
to the MOSI of the Freescale FRDM-KL25Z. The actual KL25Z pins for MOSI, MISO, SCLK, and SS are
specified on the SD Card block that you will place in your model. We will use the wiring diagram shown below:
+5 V

KL25Z

MOSI

DI

MISO

DO

SCLK

CLK

SS

CS

GND

5V

MicroSD
Breakout

The CD pin on the MicroSD card is the Card Detect pin and is pulled low when an SD card is inserted. If you
wish to use this pin, you will need to use a pull-up resistor and then connect the CD pin to one of the digital
inputs of the FRDM-KL25Z.
Our example only has a single slave. The idea of a bus is that it can connect the master to
several slave devices. The slave select line determines which slave device the master will communicate with.
Just for illustration purposes, if we had several slaves, all of which were MicroSD Breakout boards, our wiring
diagram would look as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

252

Instrumentation and Microcontrollers Using Automatic Code Generation

KL25Z

MOSI

DI

MISO

DO

SCLK

CLK

SS1

CS

SS2
SS3
DI

GND

5V

MicroSD
Breakout
GND

5V

DO
CLK
CS

DI

MicroSD
Breakout
GND

5V

DO
CLK
CS

MicroSD
Breakout

Notice that the DI, DO, and CLK lines are all connected together and form the SPI bus, and that each slave
uses a dedicated CS line.

B.

Data Collection Model

Now that we know how to wire the MicroSD breakout board to the Freescale FRDM-KL25Z, we will
make a model that measures data with a sensor and then writes that data to the SD Card. The model will
implement the following features 25:

1 Hz flashing LED to show that the FRDM-KL25Z is alive.


Overrun detection.
A pushbutton to enable and disable data collection. Data collection can be enabled and disabled
as many times as desired by the user.
An LED to show when data collection is active.
The LCD displays the current date and time, and indicates whether data collection is active.
(Data collection being active means that data is being saved to the MicroSD card.)
The data collected includes a time/date stamp, the current temperature at the time/date stamp,
and the current pressure at the time/date stamp.
Data should never be lost if the FRDM-KL25Z is reset or if the FRDM-KL25Z loses power.

The complete model is shown below:

25

You can use different sensors than the BMP085/BMP180. However, you must use at least two sensors in addition to
the real-time clock for data collection.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

253

Note that Day of Week is


not used here.

Lab IX: Collecting Data 2

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

254

Instrumentation and Microcontrollers Using Automatic Code Generation

We will now discuss the logical design of this model. Many of the blocks have been used before
and will only be referenced in this discussion. The top-level of the model contains two atomic subsystems, one
to read the sensors and display information on the LCD display, the second to write data to the SD card. The
top level also has a digital input to read a pushbutton switch that is used to enable and disable data being
written to the SD card:

The switch uses a pull-up resistor, an inverter, and a switch debouncer. Stateflow chart PB Memory4
implements logic such that the push-button must first be released and then pressed to make a change:

This chart implements the following sequential logic:


1.
2.
3.
4.
5.
6.

The initial value of variable State is 0.


When we press the pushbutton, State changes to 1.
When we release the pushbutton, State remains at 1.
When we press the pushbutton again, State changes to 0.
When we release the pushbutton a second time, State remains at 0.
The sequence from 2 through 5 then repeats.

The purpose of this logic is that variable State changes when we press the pushbutton, but in order to change
from a one to a zero and a zero to a one, the pushbutton must be released before it is pressed again. When
State equals one, data collection will be enabled and data will be written to the SD card. The value of variable
State is used to drive an LED and also passed to the two atomic subsystems. When State equals one, the
LED will be illuminated.
Subsystem Read Sensors, Date and Time, Display on LCD is atomic with a 1 second sample
time. This large step size was chosen because we do not need to sample the sensors that quickly (ambient
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IX: Collecting Data 2

255

pressure and temperature do not change that quickly), and because sending text to the LCD screen is slow.
The subsystem is shown below:

DCE input.

Both the Real-Time Clock and the BMP085 use the same I2C bus. Also, all data from the sensors and real-time
clock are output so that we can pass thee values to the SD card subsystem. You can add additional sensors if
you wish.
We do note that the subsystem has an input called DCE, which stands for Data Collection
Enable. This signal is provided by the pushbutton input, and is used to turn on and off data collection. When
data collection is disabled, the LCD will display the date and time. When data collection is enabled, the LCD
will display the date, the time, and the word Data. The only modification to the LCD subsystem is in the sprintf
MATLAB function and the added input called DCE. The LCD Display subsystem is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

256

Instrumentation and Microcontrollers Using Automatic Code Generation

The MATLAB Function has been changed as shown below:

Test Data displayed here.

This / goes in this %c.

We notice that the if statement chooses between two different sprintf commands. If DCE is equal to one, the
text Data will be displayed as the last four characters of the first line of the LCD display. We also note that in
order to display the date as month/day/year, we need to use the %c format string to specify a single character
and specify a / as we would a string variable, /. Also note that the %d format strings are specified as %02d
rather than %2d. Both strings mean two total spaces with no decimal places. However %02d means display
leading zeros as zeros rather than spaces. Thus a number like 5 will be displayed as 05. %2d still uses two
spaces, but leading zeros are displayed as spaces. This format is needed to specify time and dates correctly
such as 08:05 rather than 8: 5 and a date as 08/22/2003 rather than 8/22/20 3.
Subsystem Write Data to SD Card is an atomic subsystem with a sample time of 1 second. An
atomic subsystem is used because the initial operation of setting up the SPI bus for the SD card takes a long
time and causes overruns. The subsystem is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IX: Collecting Data 2

257

Note that Day of Week is


not used here.

Note that the SD card will only write 8 data values to the SD card and that these values are written as 16 bit
signed integers (MATLAB data type int16). Since we can only write integers, if you have a real number and you
want to save some of the fractional accuracy, you will need to multiply the number by the appropriate factor of
10 while writing the data. When you read the data from the SD card, you will need to divide by the appropriate
factor of 10. For example, we want 2 decimal places of accuracy in our temperature and pressure data, so we
multiply those signals by 100. When we read those data values, we will divide them by 100. Also note that the
other values are inherently integers, so we can write them without multiplying by a factor of 10.
We also note that SD Write Subsystem Inside is an edge triggered subsystem that contains
the actual subsystem that writes to the SD card. This subsystem is edge triggered so that we can control how
often data is written to the card. Even though the atomic subsystem executes once a second, we will use this
trigger to determine how often we write to the SD card. For example, with temperature data we may only want
to write data once a minute or less. Note that constant Sample Time determines how often we write data to the
SD card. The value of 2 shown in the screen capture above indicates that we will save data every 2 seconds.
The Sequence Data Collection Stateflow chart is used to control the sequence of events
needed to initialize the SPI bus and write data to the MicroSD card. Note that it is triggered by the 1 Hz clock,
so this chart is run once a second. The purpose of the chart is to generate an edge trigger execute the SD
Write subsystem and write the data to the MicroSD card. The constant Sample Time is, during normal data
collection, how often a sample is taken. In the example, the Sample Time is 2, so a data point will be logged
every two clock cycles. Since the Clock has a frequency of 1 Hz, a data point will be logged every two
seconds. We chose this fast sample rate so that we can collect some data in a short amount of time. In a real
application, say measuring the air temperature throughout the day, a sample time of 10, 100 or even longer
could be used. We could go to a faster sample rate as well, but we do have limitations in the FRDM-KL25Z
speed and the fact that we have a fixed time step (which you need to choose).
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

258

Instrumentation and Microcontrollers Using Automatic Code Generation


The Sequence Data Collection chart implements the logic below:

1. After power-up or a system reset, wait. Do not initially enable data collection. Wait until data collection
is enabled.
2. When data collection is enabled for the first time:
a. Leave the Trigger at 0.
b. Wait one second (the sample time of this atomic subsystem).
c. Set Trigger to 1. This will trigger the SD Card Write subsystem for the first time which will run
the initialization portion of the device driver.
d. Wait one second.
e. Set the Trigger to 0.
f. Wait one second.
g. Set Trigger to 1. This will trigger the MicroSD card S-Function which will write the first set data
values to the MicroSD card.
h. Wait one second.
i. Set the trigger to 0.
3. When the sequence above completes, toggle the Trigger between 0 and 1 at the rate specified by the
constant Sample Time.
4. If, at any point during the sequence listed above, data collection is disabled, the trigger and counter
hold at their present value. When data collection is re-enabled, the system will continue exactly where it
left off.
The purpose of this sequence is to initialize the SD Card driver, record a set of data, and then collect data at
the specified sample time. This method is used because we are designing this system for long sample times.
Suppose the sample time is ten minutes. When you first enable data collection, nothing would happen for 10
minutes. It would make more sense to take a data point immediately and then wait 10 minutes for the next
sample. The Stateflow chart is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

259

This is a super state.

This is a History
junction.

Note that on some versions of Stateflow, the text


[Count>=Sample_Time]/Trigger=0; might
be automatically changed to
[Count>=Sample_Time]/{Trigger=0;}.

Lab IX: Collecting Data 2

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

260

Instrumentation and Microcontrollers Using Automatic Code Generation

Notice the history junction


. We will get back to it in a moment. Also
notice the Collect_Data super state and that it contains many states within
it: Init1, Init2, and so on. Super states were covered on Page 225. This
superstate makes two things easier for us. The chart follows the path Init1,
init2, Init3, Init4, Init5, and then Count. If we are in any of these states
and DCE is 0, we need to hold. Having the transition [DCE==0] on the
super state gives us an easy way to do this. The history junction
remembers where we were in a super state when we exited the super
state. Suppose we were going through the sequence of states init1, Init2,
Init3, and so on, and then data collection becomes disabled. The chart
exits the super state and goes to the Hold state. When data collection is
later re-enabled, because we are using a history junction together with the
super state, the chart will jump back into the super state where it left off
and then continue. Thus, the history junction allows us to pause and return
to the sequence of steps.
The chart to the right performs the same function without
using super states and history junctions 26:

History junction
located
here in quick access toolbar in
the Stateflow chart window.

26

I think it does. I did not test itAnd I dont want to. Its ugly
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IX: Collecting Data 2

261

The chart has the same linear progression, but is unreadable in the screen capture, so the same chart is
rearranged below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

262

Instrumentation and Microcontrollers Using Automatic Code Generation

Clearly the super state and the history junction make for a more compact and easy to understand chart than
the one shown above.
The Sequence Data Collection chart triggers SD C Subsystem Inside subsystem, which is
shown below:

The SD Card Write block writes data to an SD Card using an SD card reader/writer on the SPI bus. The block
was originally developed using the SD Card reader available from adafruit (http://www.adafruit.com).Values
Data1 through Data8 are 16-bit integer values (MATLAB type int16). The values are saved on the SD Card in a
file named Datalog.csv. The file format is a CSV file (comma separated values). The values are written with no
decimal places of accuracy. Unused inputs should be set to zero with a constant.
The block opens the data file, writes the data to the MicroSD card with each number separated
by a comma, and then closes the data file. Note that the data file is closed immediately after writing the data.
This is done to minimize the possibility that the data file is not closed properly when something bad happens.
Something bad could be a power failure or accidental reset. If these happen while the file is open, the file could
be corrupted and we might lose data. For long sample times, using this method keeps the file closed most of
the time. It is only open for the fraction of a second it takes to write the data to the file.
An example data file is shown below:
36,27,15,27,1,15,2330,2966
38,27,15,27,1,15,2330,2966
42,27,15,27,1,15,2330,2966
44,27,15,27,1,15,2330,2966
46,27,15,27,1,15,2330,2966
Note that the data values are separated by commas. This format is referred to as a comma separated values
(CSV) file, and can be read easily with most spreadsheet programs and with MATLAB.
Demo IX.1: Demonstrate the operation of your Data collection model:
Data collection can be turned on and off.
The LCD shows the current time, date, and if data collection is on or off.
The SD Card collects data.
Show the contents of a collected data file.
Exercise IX.1: Write a MATLAB script that reads your data and generates a figure containing two plots with the
following information:
A plot of temperature versus time.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab IX: Collecting Data 2

263

A plot of pressure versus time.


Display the starting date on your plot.
Prints the max pressure and date on the plot. (Date is optional.)
Prints the min pressure and date on the plot. (Date is optional.)
You may want to use the following MATLAB commands: uigetfile, csvread, datenum, datestr,
subplot, figure, text, sprintf, max, min, xlabel, ylabel, title. An example plot is
shown below:

You dont need to let your data collection run for 9 days.

Exercise IX.2: Modify your data collection Simulink model to use the Card Detect (CD) pin of the MicroSD
breakout board. Your model must enforce the logic listed below:

Data collection cannot be started if the card is not inserted.


If data collection is enabled and then the card is removed, data collection should stop independent of
the pushbutton state. It cannot be restarted until the card is reinserted and the user presses the push
button.
If the card is removed and then reinserted, and while the card is being reinserted the user also holds
down the pushbutton, data collection will not resume until the user releases the pushbutton and then
presses it again.
The correct order for starting data collection is that the card must be inserted with the pushbutton
released, and then the pushbutton should be pressed to enable data collection.

Exercise IX.3: Create a model that has the same functionality as the model of Exercise IX.2 with the addition
that LCD toggles every two seconds between displaying the time and date or the temperature and pressure.
This is a good opportunity to use the Simulink IF and IF Action Subsystem blocks. These blocks are located
in the Ports & Subsystems library. For both displays, the LCD should still display if data collection is enabled or
not.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

X.

Motors

Lab X
Motors

In this lab we will cover the use of three basic motors, a DC motor where we could control
speed and torque, a stepper motor where we will control speed and direction, and a servo motor where we will
control the angle or position. This section is only basic and introductory. Motors are used everywhere from
powering toys, precision speed control for disk drives, to high power torque sources for hybrid and electric
vehicles. This is the first step into a world where microcontrollers combine with power electronics to enable the
control of huge amounts of power intelligently. Although we will be working with tiny motors, microcontrollers
are used to control motors both large and small.

A.

DC Motor

We covered the speed control of a DC motor in Section IV.D where we used pulse-width modulation (PWM) to
control the speed of a tiny DC motor. We will use this same method here to control the speed of a cooling fan
and add some logic for more intelligent control. Note that cooling fans come in all shapes and sizes. Some fans
are AC and some DC. Here we will use a small DC fan as an example. The fan requires a larger current and
voltage than can be provided by the FRDM-KL25Z logic output, so the high current driver from Section IV.D will
be used again, and is repeated below:
VCC

Freewheeling
Diode

Motor
LOAD

IMotor

RB
Vin

2n2222

All motors are inductive, so a flywheel diode is required as shown 27. The only difference between the motor
load and the fan load is the supply voltage and the amount of current the fan motor draws. Note that this driver
allows us to drive a load that uses a different voltage than the controlling signal from the microcontroller. Signal
Vin will be a digital output of the Freescale FRDM-KL25Z and has a range of 0 to 3.3 V. The motor voltage in
this example can be any positive DC voltage. For a high power traction motor, the voltage could be 200 V or
higher. (Note that the high current driver will be more involved, but the principles are the same.) In our case,
the motor voltage will be 12 V DC. When Vin is high (3.3 V), the transistor will turn on and current will flow
through the motor, causing it to spin. If we leave the motor on long enough, it will eventually reach full speed.
When Vin is zero, the transistor is off and the motor will slow down. If we leave the motor off long enough, it will
stop. If we repeatedly turn on and off the transistor fast enough, we can control the fan speed as it will respond
to the average of the amount of time we turn on and off the transistor. This method is called pulse-width
modulation and was covered in detail in Lab IV. The only difference in this section is that the DC motor uses 12
V and the fan current is higher than our last motor example. We will use the DC fan shown below:

27

See Section IV.C for an explanation of flywheel diodes.


Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

265

Note that for this specific example, the fan we are using is a SUNON EE80251S2 and is rated at 1.4 W
maximum. (Your fan may be different. Consult the data sheet or name plate for your specific fan.) This is the
peak power that the fan will ever draw, and is the locked rotor current and the start-up current. We will design
the driver for this power even though in steady-state the motor will draw a lower current. Note that power for a
DC device is P=V*I. Since we are using a 12 V fan, V = 12 V. Thus, given a power specification, we can solve
for the current, I=P/V. Therefore, 1.4 W divided by 12 V yields a fan current of 117 mA, which we will round up
to 120 mA. Note that the data sheet for this fan shown on page 291 specifies a current of 120 mA for this fan,
which agrees with our approximation.
Looking at the PN2222A data sheet on page 292, we see that at a collector current of 150 mA
the minimum value of DC current gain (hFE) is 100:

Min hFE is 100 at 150 mA.

We will be using the PN2222A at around 120 mA. Figure 3 of the PN2222A data sheet shows that the value of
hFE at 150 mA is lower than the value of hFE at 100 mA:

150 mA

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

266

Instrumentation and Microcontrollers Using Automatic Code Generation

Thus, we expect the minimum value of hFE to be larger than 100. However, using a smaller value of hFE will
make our base current larger, and this over design tends to turn on the switch more when it is on, which is OK.
For a collector current of 100 mA, we need a base current higher than of 120 mA divided by the
current gain. We will choose a current that is 10% higher than this value to guarantee that the transistor switch
is on:
1.1 1.1 120
=
= 1.32

100

So, when Vin is 3.3 V we would like the base current to be at least 1.32 mA. (Note that the FRDM-KL25Z
digital output can source a lot more than 1.32 mA, so there is no problem driving the motor with this driver. The
FRDM-KL25Z could not, however, drive 120 mA, so the transistor driver is required.)
We need to choose the base resistor RB in the circuit below so that when VIN is 3.3 V, the base
current is at least 1.32 mA.
VCC = 12 V

Motor
LOAD
RB
PN2222A

Vin

IB

+
VBE

53.3
V

When VIN is 3.3 V, the base current IB is:


=

We want the value of base current to be greater than or equal to 1.32 mA, so

Solving for RB:

1.32


1.32

VBE is the base-emitter forward voltage drop of an NPN bipolar junction transistor (BJT). A typical value for a
silicon NPN BJT is VBE0.7 V. When the transistor is on, we will assume that VBE is approximately 0.7 V:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

267

3.3 0.7
1.32

Or, RB = 1970 . Choosing the next lower standard 5% resistor gives us a value of RB = 1.8 k, 5%. Note
that all of our design choices tended toward making RB smaller, which yields a larger base current that turns on
the transistor harder when it is on.
When the output of the controller is low (digital 0), the transistor will be off and there is no
design as far as the circuit goes. Our final circuit is shown below:
VCC = 12 V

Motor
LOAD

FRDM-KL25Z
RB1

Digital Output

PN2222A3
1.8k

We should make an important note about the 12 V DC supply for the fan, VCC. This is a separate supply and
does not power the KL25Z. This is common for high power drives. Here, the 12 V supply only powers the
motor. We also have a separate 5 V DC supply for the KL25Z. This supply comes from the USB connection
from your computer. The two supplies do share a common ground, which makes sharing the signals easy.
Here a common ground is needed so that the digital output of the KL25Z can turn on the PN222A transistor. A
more detailed schematic is shown below:
VCC = 12 V

Motor
LOAD

FRDM-KL25Z
P5V_USB

Digital Output

VCC
12V

RB2
PN2222A4
1.8k

USB Power
5V

Ground

The remainder of our design will be controlling the fan logically from the microcontroller.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

268

Instrumentation and Microcontrollers Using Automatic Code Generation

1.
Fan Duty Cycle Response
Before we make a fan controller, we would like to determine the response of the fan to a specified duty cycle.
When the fan is stationary, it will take a larger duty cycle to start the fan spinning than it will to keep the fan
spinning. Create the model shown below:

With this model we can set the duty cycle with a slider and then observe the response of the fan. Note that this
model will use External Mode to change the duty cycle. See section II.D.3 on page 77 for a review of external
mode operation.

Demo X.1: Show that the fan speed can be controlled by changing the duty cycle. Determine: (1) The minimum
duty cycle to start the fan when the fan initially is not rotating. (2) The value of duty cycle where the fan stops
after it was initially rotating.
Exercise X.1: Create a fan controller that turns the fan off for temperatures less than 70 F and full on for
temperatures greater than 80 F. Between temperatures of 70 F and 80 F, the fan speed varies linearly.
Use the LCD to display the duty cycle and temperature and use one of the temperature sensors covered in a
previous lab.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

269

Exercise X.2: Create a two-speed fan controller that implements the following algorithm. When the temperature
is greater than or equal to 75 F, the fan spins at 50% duty cycle. If the fan is on at 50% duty cycle, the fan
cannot turn off until the temperature is less than or equal to 70 F. When the temperature is greater than or
equal to 80 F, the fan spins at 100% duty cycle. If the fan is on at 100% duty cycle, it will not slow down to
50% duty cycle until the temperature is less than or equal to 75 F.

B.

Stepper Motor

For our next motor example, we will control the speed of a stepper motor. Every time you give a stepper motor
a pulse, the motor will turn a fixed number of degrees. By controlling the pulse frequency, we can control the
speed of the motor. Because of this characteristic, stepper motors are used where precise speed is required. A
stepper motor has two or more windings, and rotating the stepper motor shaft requires that we pulse the
various windings in the appropriate sequence. Also note that we can change the direction of rotation by
changing the pulse sequence.
For this example, you can use any small stepper motor as long as you can find the data sheet that specifies
the wiring diagram and the pulsing sequence. Here, we will use the bipolar Portscap 20M020D1B shown
below:

This motor has a step angle of 18 which means it takes 20 steps to complete one revolution. Note that the
complete data sheet is shown in the Appendix on page 296. The detailed specifications are shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

270

Instrumentation and Microcontrollers Using Automatic Code Generation

We see that this is a 5 V motor and that the winding resistance is 20 . Thus 5 V pulses will be sufficient to
drive the motor. We will be applying 5 V pulses across the windings. Note that if the winding resistance is 20 ,
when we apply 5 V across the winding, the winding will draw 250 mA. This is more current than the FRDMKL25Z digital outputs can supply, so we will need to use a driver integrated circuit as a buffer between the
FRDM-KL25Z and the motor. (In general a buffer is a unity gain amplifier that can provide a high output current
to drive a load. Unity gain means that the output voltage is the same as the input voltage (VO/VIN=1). We will
use this buffer to drive the motor because the output current of the KL25Z is limited to about a 1 mA, whereas
the buffer can provide currents to the motor.) This portion of the datasheet also lists the mechanical properties
of the motor such as the inertia and torque. Since we are not driving a mechanical load with this motor, we will
not consider these specifications in our design.
The fourth page of the datasheet gives the wiring diagram and the pulsing sequence:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

271

Note that when Q1 is on, the RED wire will be connected to +V which is the positive supply, 5 V in this
example. When Q4 is on, the GRY wire will be connected to ground. In this configuration, 5 V is applied across
the winding with the RED wire positive and the GRY wire negating. When Q2 is on, the GRY wire will be
connected to +V. When Q3 is on, the RED wire will be connected to ground. In this new configuration, 5 V is
applied across the winding with the GRY wire positive and the RED wire negating, Note that in these two
configurations, the polarity of the voltage across the winding has changed.
Q1 through Q8 can be thought of as switches. Q3, Q4, Q7, Q8 are low-side switches that connect a motor
winding to ground. Q1, Q2, Q5 and Q6 are high side switches and they connect a motor winding to the positive
supply. Switches in series should never be on at the same time. For example, Q1 and Q3 should never be on
at the same time. If they were, the combination of Q1 and Q3 would place a direct short across the 5 V power
supply, and this could damage the driver. It is possible to turn on transistors that are across from each other at
the same time. For example, Q1 and Q2 can be on at the same time as can Q7 and Q8. In both cases, turning
on the pair forces the winding voltage to be zero. The winding voltage would be zero so the winding draws no
current.
The transistor arrangement of Q1 through Q4 is called an H-bridge. It allows us to apply a +/- 5 V swing to a
load from a single 5 V supply. When Q1 and Q4 are on, +5 V is applied across the motor winding. When Q2
and Q3 are on, -5 V is applied across the same winding. Note that Q1 and Q3 form a half bridge or Half-H
bridge. Two half bridges form an H-bridge. An H-bridge is a common circuit topology used in power electronics.
We will not use discrete transistors for our H-bridge. Instead we will use the L293 quad Half-H
driver integrated circuit. Schematically, the device is shown as four buffers:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

272

Instrumentation and Microcontrollers Using Automatic Code Generation

Each buffer is actually a high-current half-H. Note that each pair of drivers has an enable line (pins 1 and 9).
Each half bridge is shown as a buffer, which means that the output voltage is equal to the input voltage. Halfbridges are actually current amplifiers, so the output current can be much higher than the input current. The
input impedance of the buffers is large, so we can connect the FRDM-KL25Z output directly to the buffers
input. Note that each buffer output is a high-current half bridge and each input is a high impedance emitterfollower:

We do not really care how the buffer is implemented. (We see that it is more involved than just two switches.)
All we need to know is that it is a high current output with a high impedance input. The complete data sheet for
the L293 is shown on page 302.
Instead of using the table shown previously with switches listed, we can translate the transistors
switches being on as a colored wire being high or low. The table is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

273

Step
1
2
3
4
1

RED
H
H
L
L
H

GRY
L
L
H
H
L

YEL
H
L
L
H
H

BLK
L
H
H
L
L

You will need to choose 4 digital outputs from the Freescale FRDM-KL25Z and select a buffer from the L293
for each wire on the stepper motor. A suggested schematic is shown below. The only required wires are the
ones shown for the enable, power, and ground pins. You can rearrange the buffers if so desired:
P5V_USB

L293 Half-H Bridge


1
9

KL25Z
PTA13
PTD5
PTD0
PTD2

4
5

8
16

12

15

14

RED

10

11

GRY

YEL

BLK

13
L3

L4

Stepper
Motor

If you are not familiar with the pin numbers on an integrated circuit, the pin and package layout for the L293
can be found in the appendix on page 300. The pin numbers There is a problem with this circuit. The L293 is a
5 V circuit and the KL25Z uses 3.3 V logic. Looking at the datasheet for the L293, a 3.3 V high output from the
KL25Z might work as a high input to the L293. If it does, it will not be very reliable, and certainly would not be a
circuit that you should use in a circuit intended for production. To fix this problem, we will use a TXB0104 level
translator. This integrated circuit is used to translate 3.3 V logic levels to 5 V logic levels. Note that it is
bidirectional, so we can use it for both inputs and outputs:
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

274

Instrumentation and Microcontrollers Using Automatic Code Generation

The A side is the 3.3 V side and the B side is the 5V side:

Note that a breakout board for this integrated circuit is available from SparkFun. The circuit with the level
translator is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

275

3.3 V

TXB0104
Level Translator
VCCA

KL25Z
PTA13
PTD5
PTD0
PTD2

VCCB

OE

P5V_USB
P5V_USB

L293 Half-H Bridge


1
9

4
5

8
16

12

GND
A1

B1

15

14

RED

A2

B2

10

11

GRY

A3

B3

YEL

A4

B4

BLK

13
L5

L6

Stepper
Motor

Note that we could have avoided using the TXB0104 if we could find an H-Bridge driver that accepted 3.3 V
inputs. (Something other than the L293.) Instead, we will use the L293 and a level translator because mixing
3.3 V and 5 V logic is a common occurrence.
As a first model, we will generate the pulse sequence and spin the motor. A good method to
generate the sequence is a state flow chart:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

276

Instrumentation and Microcontrollers Using Automatic Code Generation

The trigger input shown in the chart above was created by selecting Chart, Add Inputs & Outputs, and then Event
Input from Simulink from the Stateflow menus.

The contents of the Stateflow chart step the outputs through the counter-clockwise sequence of steps:

Notice that the sequence of states goes through the counter-clockwise sequence and that the arrows in the
Stateflow chart point the state transitions in the counter-clockwise direction. This was done to make
understanding the chart easier. Each time the chart transitions to a new state, the stepper motor will take a
single step. The pulse generator in the model controls the speed of the motor. Every time the pulse generator
generates a positive edge, the Stateflow chart will transition to a new state, and the stepper motor will take a
step. Thus, the pulse generator frequency is also the step frequency of the motor. (This is not the rotation
frequency as 20 steps are required for a single rotation with this motor.)
This mode has a problem which we can see when we run a simulation. The pulse outputs are
shown below for the first 15 seconds. Note that the pulse generator frequency is 1 Hz so the motor will take
one step per second:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

277

We see that for a slow rotation where the motor is taking one step per second, a pulse across the motor
winding will last for 2 seconds. (Except or the first step where we started from the Init state in the Stateflow
chart.) For a slower pulse generator frequency, the steps will be even longer. We are effectively placing a
constant voltage across the motor windings. A motor winding looks like an inductor, which will look like a short
and draw a large current for these long pulses. The current through the winding is limited only by the wire
resistance of the winding. We saw from the stepper motor data sheet that this winding resistance was 20 , so
placing 5 V across the winding will draw 250 mA. Since both windings always have voltage applied, the motor
will draw a total of 500 mA. This is a significant current that is wasteful and results in heat generation that must
be removed from the various components. This is wasteful because when we pulse the motor, the motor will
take a step in about 10 ms. (The value of 10 ms was found experimentally, and will vary for different motors.)
Once the motor has moved in response to a step, the motor will not move again even though the voltage is still
being applied and current is being drawn. Thus, the pulse makes the motor move in the first 10 ms. For the
rest of the pulse, the voltage is applied to the motor winding and the winding draws current, but the motor does
not move. To fix this problem we will generate pulse outputs that last for a short amount of time. That time is
just enough to allow the motor take a step. This method reduces the power dissipation of the motor.
The model has been modified by adding a new subsystem called One Shot as shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

278

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

279

The contents of the One Shot subsystems are shown below:

A positive edge on the Speed signal resets the integrator output to zero. This is connected to the pulse
generator in the previous level, so the integrator is reset each step. This integrator integrates one divided by
the pulse width. If you open the integrator block, you will see that the gain is set 1000, the saturation limit is set
to 1, and we have enabled the saturation port:

Note that the integration output of the block is terminated and it is the saturation port that goes to the switch.
The way the saturation port works is that when the integrator is not saturated, the saturation port output is zero.
When the integrator is saturated, the saturation port output is one. The switch is used to invert the saturation
port output.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

280

Instrumentation and Microcontrollers Using Automatic Code Generation

The integrator integrates 1000 divided by the pulse width. Note that the pulse width is provided
by a constant in the top level of the model. While integrating, the output of the switch (and thus the output of
the subsystem) is one. When integrator reaches one, the integrator will saturate and the switch output goes to
zero. The integrator starts at zero and integrates the value of 1000/PW until it reaches a value of 1. The
1000

amount of time it takes to reach 1 is 0

= 1, or

1000

= 1, or =

.
1000

Thus the width of the pulse emitted

by this block is the value of signal PW in milliseconds. (If PW = 10, the pulse width will be 10 ms.) A simulation
with the pulse width set to 10 ms and the pulse generator period set to 100 ms is shown below:

Note that if we change the pulse generator frequency, the pulse width will remain the same. Thus, we can run
the motor fast or slow, and the pulse width to the motor will be constant at the specified pulse width.
Demo X.2: Show the working stepper motor. Use external mode so that you can vary the pulse frequency by
changing the pulse generator frequency. Show that you can vary the pulse generator period from 4 ms to 1 s,
and the motor responds appropriately. You will need a fixed time step of 1 ms or smaller.
Now that we have created a model that implements basic stepper motor operation, we can add
logic to control the motor in interesting ways. Well At least more complicated ways than in the previous
example. First, we will create a subsystem out of the previous model that drives the stepper motor. The
subsystem input will be an edge trigger that moves the motor one step counter-clockwise. The outputs of the
subsystem are the digital outputs that drive the L293 stepper motor driver integrated circuit:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

281

Now that we have this subsystem, we will create a model that drives the motor anywhere from 0 to 250 pulses
per second (pps) based on a potentiometer connected to an analog input 28. Note that since it takes the motor
20 pulses to make one revolution, the motor speed will vary between 0 and 12.5 revolutions per second. The
top level model is shown below:

The additional portions of the model are taken from earlier labs and will not be discussed here 29. You are
encouraged to reuse earlier models and adapt it to this example. Note that the output of the Stateflow chart is a
variable frequency square wave proportional to the analog input.
Demo X.3: Show the working stepper motor with a variable frequency between 0 and 12.5 revolutions per
second. The speed should depend linearly on a potentiometer read with an analog input.
Now that we have a variable speed stepper motor controller, we would like to be able to change
the direction of rotation. From the stepper motor data sheet and the stepper motor truth table shown on page
28
29

250 pps is based on the minimum pulse width of 4 ms discussed in Demo X.2.
Check out the variable speed ring counter on page 145.
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

282

Instrumentation and Microcontrollers Using Automatic Code Generation

273, to change the direction of the stepper motor rotation all we need to do is reverse the order of the pulses.
This is easily accomplished by modifying the Stateflow chart that controls the order of the pulses. We will add a
new input to the Stateflow chart called Direction. This variable determines if the motor rotates clockwise or
counter clockwise. The modified chart is shown below:

We see that if Direction equals one, the chart changes states in the counter clockwise direction. If Direction
equals 0, the chart changes states in the clockwise direction. The way we set up the chart initially makes this
change easy to manage and visualize.
The top level model is shown below:

We have added logic to read a pushbutton with a digital input, debounce that input, and then add some
memory to remember if the pushbutton has been pushed. The logic is designed so that when we push the
button, the output changes from a zero to a one. When we release the pushbutton, the output remains a one.
When we push the button again, the output changes from a one to a zero. When we release the pushbutton,
the output remains a zero. This operation forces the user to push and release the pushbutton to make a
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

283

change. Thus, Stateflow chart PB Memory 4 outputs a zero or a one. The user must push and release the
pushbutton before it can be pushed again. The output changes state when the pushbutton is pressed.
Demo X.4: Demo the stepper motor with variable speed and direction change. A pushbutton should change the
motor direction. The variable speed control should work in any direction. The motor should change direction
when the pushbutton is pressed. The direction should remain unchanged when the pushbutton is released.
We notice that the direction change pushbutton does not always seem to work right and also
gives the motor a jolt. As a fix, whenever the direction pushbutton is pressed, we will set the speed to zero and
then slowly allow the speed to return to the setting specified by the analog input. We will do this with an
integrator. The integrator will be reset to zero every time the pushbutton is pressed. The pushbutton will
integrate from zero to one in one second, and then saturate at 1. The model is shown below:

Demo X.5: Demo the stepper motor with variable speed, direction change, and speed ramping when the
direction pushbutton is pressed. A pushbutton should change the motor direction. When the direction is
changed, the speed should be set to zero and then ramp up linearly to the speed set by the analog input in one
second. The variable speed control should work in any direction.
Exercise X.3: Add an LCD display to the stepper motor model. The LCD will display the direction (CW or CCW)
and the speed in rpm. Example text would be Direction: CCW
Speed: 193 rpm

C.

Servo Motor

Servo motors are position control motors. The input signal commands the motor to turn to a specified angle,
and the motor holds that position. If an external force is applied to the motor arm, the servo motor will apply an
opposing torque to hold the arm at the same position. Servo motors are typically commanded by sending it a
repeating pulse with a specified pulse width. For analog servo motors, such as we will use in this lab, the servo
motor must receive a control pulse every 20 ms. For these motors, a control pulse width of 0.5 ms will position
the motor arm at 0 degrees, a pulse width of 1.5 ms will position the arm at 90 degrees, and a pulse width of
2.5 ms will position the arm at 180 degrees. Different motors may have slightly different requirements on the
pulse waveform. A typical waveform for a control pulse is shown below:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

284

Instrumentation and Microcontrollers Using Automatic Code Generation

This waveform is not a pulse-width modulated (PWM) waveform as the period changes with the pulse width. In
the waveform above, the period is 21.5 ms and the pulse width is 1.5 ms. If we change the control pulse width,
the time the waveform spends low will remain at 20 ms while the time high will change. As illustrated above,
the period of the waveform will change as we change the control pulse width. Instead of using this waveform,
we will use a PWM waveform and keep the period constant at 20 ms (50 Hz). We will still change the pulse
width from 0.5 ms to 2.5 ms which corresponds to changing the duty cycle of the PWM waveform from 2.5% to
12.5%.
For a first example, we will create the model below where the motor position is determined by a
potentiometer read with an analog input. The top lookup table is used to convert the values returned by the
analog input block to a number between 500 and 2500. This value goes to the pulse width input of the PWM
block which generates a pulse between 0.5 and 2.5 ms. The bottom lookup table is used to convert the values
returned by the analog input block to a number between 0 and 180. This value goes to the LCD display block
to display the angle of the servo motor:

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Lab X: Motors

285

Wiring of a servo motor depends on your motor. For a typical servo motor, the brown or black wire is ground,
the red wire is the positive power supply, and the third wire is the pulse width control signal. An example of
wiring a servo motor is shown below:

5 V power connection.

PWM signal connection.

Ground connection.

Also note that the pulse width input of your motor may require a 0 to 5 V amplitude pulse. The PWM output of
the KL25Z is a 3.3 V pulse. To correctly control the servo motor, you may need to use a level shifter as we did
for the stepper motor. (The level shifter wiring diagram for the stepper motor is shown on page 275. Note that
the stepper motor required 4 channels to be level shifted. For the servo motor, we only need to level shift the
control pulse width.)
Demo X.6: Show that you can control the motor position using the analog input to position the motor between 0
and 180 degrees. Display the value of the angle on the LCD display.
Now that we can control the position of the servo motor, we can make a bunch of interesting and fun
controllers to make the motor do what we want it to do.
Exercise X.4: Create a model that slowly rotates the motor from 0 to 180 degrees (or whatever a safe
maximum is for your hardware), and then slowly rotates it back to zero. The motor will continually rotate back
and forth. The speed of rotation should be constant.
Exercise X.5: Create a model that rotates the motor from 0 to 180 degrees (or whatever a safe maximum is for
your hardware), and then rotates it back to zero. The motor will continually rotate back and forth. The speed of
rotation should be determined by an analog input. The speed to rotate between 0 and 180 degree should vary
between 1 and 10 seconds as determined by an analog input. The speed to rotate back from 180 to 0 degrees
should be the same as the speed to rotate from 0 to 180 degrees. If the analog input is constant, the speed
should be constant.
Exercise X.6: Create a model that rotates the motor from 0 to 180 degrees (or whatever a safe maximum is for
your hardware), and then rotates it back to zero. The motor will continually rotate back and forth. The speed of
rotation should be determined by an analog input. The speed to rotate between 0 and 180 degree should vary
between 1 and 10 seconds as determined by an analog input. The speed to rotate back from 180 to 0 degrees
should be the same as the speed to rotate from 0 to 180 degrees. Make the speed follow a sine wave profile
Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

286

Instrumentation and Microcontrollers Using Automatic Code Generation

so that the speed increases in the middle of the rotation and slows near the ends of the rotation. (You can use
a look up table for this, a MATLAB embedded function, or a mathematical function block.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

XI.

A.

Appendices

Appendix

SparkFun Serial LCD Module Datasheet

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

288

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

289

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

290

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

B.

291

SUNON DC Cooling Fan

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

292

Instrumentation and Microcontrollers Using Automatic Code Generation

C.

PN2222A datasheet

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

293

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

294

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

295

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

296

Instrumentation and Microcontrollers Using Automatic Code Generation

D.

Datasheet 3

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

297

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

298

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

299

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

300

Instrumentation and Microcontrollers Using Automatic Code Generation

E.

Texas Instruments L293 H-Bridge

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Appendix

301

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

302

Instrumentation and Microcontrollers Using Automatic Code Generation

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

XII.

Bibliography

Bibliography
[1] Wikipedia, "ASCII," 9 March 2013. [Online]. Available: http://en.wikipedia.org/wiki/ASCII. [Accessed 4 4
2013].
[2] Sparkfun Electronics, "Barometric Pressure Sensor - BMP085 Breakout," Sparkfun Electronics, [Online].
Available: https://www.sparkfun.com/products/11282. [Accessed 13 April 2013].
[3] A. Industries, "MicroSD card breakout board+ -," [Online]. Available: http://www.adafruit.com/products/254.
[Accessed 16 August 2013].
[4] Wikipedia, "Serial Peripheral Interface Bus," [Online]. Available:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus. [Accessed 16 August 2013].
[5] [. t. H. Ref]. [Online].
[6] A. Mega, "Arduino Mega 2560," [Online]. Available: Arduino Mega 2560. [Accessed 16 August 2013].
[7] Wikipedia, Wikipedia, [Online]. Available: http://en.wikipedia.org/wiki/Piano_key_frequencies. [Accessed 2
5 2014].
[8] S. Pictures, "This is Jeopardy," [Online]. Available: http://www.jeopardy.com/. [Accessed 2 5 2014].
[9] Lumex, LDS-SMHTA302RISUGT Data Sheet, 290 E. Helen Rooad, Palatine, IL 60067-6976: Lumex,
2012.
[10] Lumex, LDS-C324RI Datasheet, Lumex, 1993.
[11] I. Milone Technologies, eTape Continuous Fluid Level Sensor PN-12110215TC, Sewell, New Jersey:
MILONE.

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

XIII. Index

Index

\n 234, 246

sample time 106


analog output 148
analog to digital converter 92
analog voltmeter 104
animation 83
Apps tab 22
Arduino UNO 20, 92
compatible pins 41
ARM mbed webpage 44
ASCII 168
at - Stafeflow command 183
atomic subsystem 176, 191, 206, 241
attenuation 158
auto 32
average 161
average voltage 153

+3.3 V supply 45

base current 164, 266


baseline 113
BAUD 169, 236
before - Stafeflow command 183
Binary ELF with DWARF1 or DRARF2 dbg
format 74
BJT 161
Block Parameters (Subsystem) 178
BMP085 204, 205
BMP180 204
Boolean data type 55
bootloader 18
bounce 181
bps 169
Break Link 196
breakout board 204
BSS 29
Build action 33
Build Button 42

%
%c 239
%d 192
%s 239

.
.elf file 74

1
1-D lookup table 145

3
3. installing RHIT KL25Z Library 8
3.3 V supply 45
3-wire bus 250

A
abs 168
accelerometer 210
address I2C sensor 200
after - Stafeflow command 183
American Standard Code for Information
Interchange 168
Analog Input block 92

Build Model button


Build, load and run 33
bypass capacitor 164

38

C
Callbacks 131
capacitor 164
card detect 251, 263
CD - MicroSD card 251
chart 59
animation 83
default transition 65
du: 62
en: 62
ex: 62
history junction 260
output 61
output variable 61
superstate 225, 260
transition action 67
transitions 62
chart output 61
chip select 250
clear LCD screen 236
Clock 122
closed switch 50
CMSIS Specification 7
Code Generation pane 32
collect data 252
collecting data 230
column vector 187
COM port 230
Commonly Used Blocks 54, 58
Compare to Constant 55
compare to zero 55
concatenate 171, 247
Connect to Target button
Constant block 57
continuous time block 113
counter 59
rolling 216
up-down 67
create chart output 61
Create New Model 23

82

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Index

305

Create New Watched Var 75


create state transition 62
create subsystem from selection 119
Create Subsystem from Selection 175
CS 250
current driver 161, 264
current gain 161, 265
cutoff frequency 152, 157

drive currents 161


drive large load 161
drive LED 44
driver 164, 271
du: 62
duty cycle 268
dynamic matrix 247

BDM Communication Plug-in


(HCS08/12, ColdFire, Kinetis,
PowerPC) 73
Binary ELF with DWARF1 or DRARF2
dbg format 74
Create New Watched Var 75
floating point IEEE 76
MAP File 74
modifying variables 132
OpenSDA 73
P&E Kinetis File 73
scope plot 110, 114
Start/Stop Communication button

D
DAC 148
data collection 252
data collection enable 255
data size limits 29
Data Type Conversion block 103
data type display on signal lines 103
DC 158
DC component 158
DC current gain 161
DC motor 264
debounce 181
debugging tools 68
Decibels 158
default decision 105
default transition 65
default transition button
65
define parameters 127
delimiter 246
demux 183, 190, 202
Device Manager 11, 79
DI - MicroSD card 251
diagnostic window 28, 39
digital input block 50
digital inverter 184
Digital Output block 26, 37, 42
digital to analog converter 148
diode 165
freewheeling 264
direction of rotation stepper motor 281
Disable Link 195
discrete integrator 123
discrete solver 32
Disonnect from Target
83
display sample times 179
display signal data types 102
DO - MicroSD card 251
double-precision floating point data type
95
drive a load 43

Edge Trigger to Function Call Trigger 203


elf file 74
en: 62
enter state 62
event input 122
Event Input From Simulink 121
event trigger 121
every - Stafeflow command 183
ex: 62
ExportedGlobal 70
External 79, 138
External Mode 77, 83
Setup block 83, 136
tuning parameters 134
Extrapolation method in lookup table
146

F
FC 152, 157
fclose 238
finish late 68
firmware 16
fixed- step time 106
fixed time step 68
fixed-step discrete solver 31
fixed-step size 32, 53, 106, 113
Fixed-step size 138, 149
flash memory 250
float2strparts 194
floating point IEEE 76
flyback diode 165
fopen(s1) 238
for iterated subsystem 244
formatted numerical output 192
formatting strings 192
FRDM-KL25Z target 31
FreeMaster
watched variables 132
FreeMASTER 11, 16, 68, 69, 92
.elf file 74

75
tuning parameters 127
Freescale Cup Companion 23
freewheeling diode 264
fscanf 238
function block 192
function-call
Generator 184
Subsystem 187
trigger 183, 235

G
ground 45

H
Half-H driver 271
hFE 161, 265
high frequency noise 150, 151
history junction 260

I
I2C 199
index vector block 245
inductive load 165
inherited sample time 113
InitFcn 131
initialize the SD Card driver 258
install CMSIS Specification 7
install the FRDM-KL25Z 6
installing FreeMASTER 11
integrator 123, 280
saturation port 280
intelligent sensors 199

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

306

Instrumentation and Microcontrollers Using Automatic Code Generation

inverter 184

measure some physical quantity 199


memory 211
array 211
flash 250
linear 242
min and max 219
ring 214
SD card 250
static 250
with Stateflow 223

K
Kinetis KL25 51
KL25Z accelerometer 210
KL25Z pin names 20
KL25Z Schematic 20
KL25Z touch sensor 210

L
L293 271
label signals 69
LCD
splash screen 198
LCD display 166
datasheet 288
LCD-09066 166
LED 48
LED current 45
level translator 273
Library Browser icon
23
Library Link 195
linear approximation in lookup table 146
linear interpolation in lookup table 144
linear memory 242
load 161
log data 252
Logic and Bit Operations library 55
logic functions 84
logical inverter 184
lookup table 121, 144
1-D 145
linear interpolation 144
low-pass filter 151, 157

M
MAP Files 74
master device (SPI) 250
master input, slave output 250
master output, slave input 250
MATLAB
ABS 169
MATLAB compiler 8
MATLAB function block 192, 211
mbed webpage 44
measure physical quantity 199

Memory block
57
mex setup 8
MicroSD
Breakout board 250
card detect 263
CLK, DO, DI, CS 250
MISO 250
Mode Select 226
Model Configuration Parameters 53
Model Explorer 127
Model Properties 130
model size limits 29
modifying variables in FreeMASTER 132
MOSI 250
motor winding 277
multirate 174, 177
MultiTasking 179, 206, 208

N
negative temperature coefficient 109
new line character (\n) 234
noise 150, 151
non-volatile flash memory 250
npn bipolar junction transistor 161

O
ON Board LED block 45
on-board LED 22
one shot 277
ones-based indexing 245
open COM port 238
Open SDA 13
open SDA port 11
open switch 50
OpenSDA 73
output variable (chart) 61
overrun 241
detection 68
flag block 68

P
P&E Kinetis 73
P&E Micro device driver 14
P5V_USB 164
parameter 127
parameter tuning
External Mode 134
FreeMASTER 127
parameters
defining 127
Period 36
Pulse Generator 25, 36
persistent 215, 221
PN2222 Data Sheet 162
PN2222A 265
PN2222A Data Sheet 162
port data types 102
position control motor 283
positive edge triggered 175
positive rail 43
positive supply rail 43
positive temperature coefficient 109
positive-edge triggered 122
pot 94
potentiometer 94
pressure sensor 204
printed circuit board (PCB) 204
protoboards 204
PTA1 80
PTA2 80
PTE30 150
pull-up resistor 50, 199
Pulse Generator 24, 35, 176
Pulse Width 36
Pulse Generator 25, 36
pulse-width modulation 148, 153, 264,
284
pulsing sequence of stepper motor 270
pushbutton switch 52
putc 172
PWM 148, 153, 264, 284
output block 155
waveform 154

Q
quad Half-H driver 271

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

Index

307

R
RAM 211
ramp generator 123
read digital input 52
real time 32, 68
real-time clock 209
Repeating Sequence Stair 54, 156
reset button 18
resistor
pull-up 50
RGB LED 21
RHIT_KL25Z_Library 8
ring counter 54
variable speed 146
Ring Memory block 214
rising edge 122
rolling counter 216
row vector 187
RS-232 231
RS-232 serial ports 166
RX 166

S
sample and hold 114
sample time
colors 206
inherited 113
sample times - display 179
saturation port 279
SCL 199
SCLK 250
Scope block 81, 134
History 135
Limit data points to last 5000 135
Number of axes 135
scope plot in FreeMASTER 110
SD Card 250
card detect 263
CLK, DO, DI, CS 250
SDA 199
SDA port 11, 20
sensor 199
address 200
BMP085/BMP180 204
KL25Z accelerometer 210
KL25Z touch sensor 210
KL25Z TSI 210
pressure 204
real-time clock 209
resolution 203

TC74 200
temperature 200, 204
TMP102 200
Sensor Read Functions 202
sequence events 183, 190, 235, 257
sequential logic 254
serial clock 250
serial clock line 199
serial communication 230
serial communication ports 166
serial communication with MATLAB 237
serial data line 199
Serial LCD 167
serial link 230
Serial Peripheral Interface 250
Serial Transmit block 166
servo motor 264, 283
Set Path
9
set real-time clock 209
signal display 71
signal dtat type 103
Signal Routing 187
simulate with Simulink 124
Simulink 30
Simulink Library Browser 23, 33
Simulink Parameter 128
Sine Wave block 159
single-pole-single-throw 50
single-precision floating point data type
95
sink current 43
size limits 29
slave device (SPI) 250
slave select 250
small signal current gain 161
source current 43
Sources library 24, 34, 54
SPI bus 250
splash screen 198
sprintf 192, 193, 207, 221, 227, 234, 256
SPST 50
square wave generator 123
SS 250
Start/Stop Communication button
75
state button
60
state diagram 59
state transition
guard 64
unguarded 63
state transitions 62

Stateflow 59
event input 122
Event Input From Simulink 121
event trigger 121
history junction 260
superstate 225, 260
temporal operators 123, 183
static memory 250
Step 113
stepper motor 264, 269
direction of rotation 281
pulsing sequence 270
strings
concatenate 171
subsystem 119
atomic 176, 206
create subsystem from selection 119
for iterator 244
triggered 107, 113
Sum block 57, 114
superstate 260
supply busses 46
switch
block 58
pushbutton 52
wire 52
switch block 58
switch debounce 181
switch-case statement 227

T
table data in lookup table 146
Target Hardware 32
targetinstaller 1
Tasking mode 179, 206
temperature sensor 110
temporal commands in Stateflow 123
temporal operators 183
temporalCount - Stafeflow command 183
terminator 93
text 29
text strings 168, 169
textscan 247
thermistor 109
timeout 239
TMP101 201, 204
touch sensor 210
transition
action 67
animation 83
default 65

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

308

Instrumentation and Microcontrollers Using Automatic Code Generation

guard 64
unguarded 63
transition action 67
transitions in chart 62
transmit collected 243
trigger block 175
triggered subsystem 107, 110, 113, 174,
175
truth table 84, 104
add input variable 84
add output variable 85
conditions 87
decisions 87
default decision 89
Ports and Data Manager 86
TSI 210
tuning parameters
External Mode 134
FreeMASTER 127
TX 166

TXB0104 273

U
UART0 167
UART1 167, 172
UART2 231
undebounced switch signal 182
update firmware 16
update KL25Z firmware 16
up-down counter 67
USB port 19
USBRX 167
USBTX 167

variable speed ring counter 146


Vector Concatenate 195
View diagnostics 28, 39
volatile memory 211
voltage divider 94

W
watched variables 132
while loop 247
winding resistance 270
Windows device drivers 11
Windows Device Manager 11, 79, 137,
231
wire as a switch 52
write data to SD Card 256

variable frequency signal generator 125

Instrumentation and Microcontrollers using Automatic Code Generation (Freescale KL25Z Version) by Marc E. Herniter is licensed under a Creative
Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://wiki.ece.rosehulman.edu/herniter/index.php/Instrumentation_and_Microcontrollers_using_Automatic_Code_Generation_%28Freescale_KL25Z_Version%29

You might also like