Building Systems with Simulink & Micro:bit

36
© Venus Shum & Clifford French Ver 1.6, Jan 17 P1 Building Systems with Simulink & Micro:bit The Micro::bit Elements Authors: Dr Venus Shum and Clifford French February 2017, version 1.6 I: INTRODUCTION 1 What is a BBC micro:bit? Micro:bit is a pocket-sized, programmable mini- computer (a microcontroller) that allows children to get creative with technology. This little device has packed in a lot of features, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The BBC micro:bit can detect motion and tell you which direction you’re heading in, and it can use a low energy Bluetooth connection to interact with other devices and the Internet. This little computer has the latest technology found in modern devices – mobile phones, fridges, smart watches, burglar alarms, robots, etc. It has intelligent sensors that can connect wirelessly to the cloud, a portable power source and a “brain” from something called the Internet of Things, shortened as IoT. Through connection to the IoT we can interact with a wide range of sensors across the whole world in real time and we can now make smart decisions using our devices. A micro:bit is both self-contained and expandable. In addition to using its built in LEDs, buttons and sensors, we can expand its range of functions by inserting it into an edge connector. The Edge Connector breakout board as part of the Prototyping System from kitronik The exhi:bit prototyping system from Proto-pic

Transcript of Building Systems with Simulink & Micro:bit

© Venus Shum & Clifford French Ver 1.6, Jan 17 P 1
Building Systems with Simulink & Micro:bit The Micro::bit Elements
Authors: Dr Venus Shum and Clifford French
February 2017, version 1.6
1 What is a BBC micro:bit?
Micro:bit is a pocket-sized, programmable mini- computer (a microcontroller) that allows children to get creative with technology. This little device has packed in a lot of features, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The BBC micro:bit can detect motion and tell you which direction you’re heading in, and it can use a low energy Bluetooth connection to interact with other devices and the Internet.
This little computer has the latest technology found in modern devices – mobile phones, fridges, smart watches, burglar alarms, robots, etc. It has intelligent sensors that can connect wirelessly to the cloud, a portable power source and a “brain” from something called the Internet of Things, shortened as IoT. Through connection to the IoT we can interact with a wide range of sensors across the whole world in real time and we can now make smart decisions using our devices.
A micro:bit is both self-contained and expandable. In addition to using its built in LEDs, buttons and sensors, we can expand its range of functions by inserting it into an edge connector.
The Edge Connector breakout board as part of the Prototyping System from kitronik
The exhi:bit prototyping system from Proto-pic
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 2
So ultimately micro:bit is everything that you can imagine. You can turn it into your messaging device, game console, smart wearable, burglar alarm, smart home controller or pretty much whatever your imagination can create by using the additional sensors, making a case or strap for the micro:bit and by programming it. There are many programming languages to translate your ideas to computer code. Currently, the supported programming languages on the website of the Microbit Educational Foundation1 are (a variation of) JavaScript, Microsoft Blocks, Microsoft TouchDevelop and MicroPython.
2 What are Simulink & MATLAB, what are they for?
You have almost certainly used a procedural programming language. Whether you’ve been working with Scratch or any of the languages on the micro:bit website, you have created a number of steps. You’ve no doubt had to debug your program when the steps you created didn’t quite do what you expected. Maybe you have made the cat dance in Scratch or made the micro:bit display a happy face. When you want the cat to do a different dance or the micro:bit to change its face, you change the program and run it again.
Each of the blocks you have used in Scratch and perhaps in Microsoft Blocks is an instruction or line of code. Simulink takes a different approach. The blocks you will see in Simulink represent parts of a system. They are not instructions. Think about a driverless car with a system made of sensors, a “brain” and an engine, brakes and wheels that can change direction. Blocks in Simulink represent different parts of a system. Here’s the official description:
Simulink®, developed by The MathWorks®, is a block diagram environment for simulation and Model-Based and System-level Design. It has a graphical editor for building and managing block diagrams centred on the concept of building a system.
Why, you may ask, should I learn to use MATLAB and Simulink? If you are a teacher, you may ask why your students should learn to use this software. MATLAB® is the high-level language and interactive environment used by millions of engineers and scientists worldwide. From NASA to car manufacturers and aircraft design, MATLAB is used to design, test and build our world. But MATLAB and Simulink are not just for engineers and scientists: they are also used in medicine, finance, market research and many other fields. Students who think that their future careers may have nothing to do with computer science may well be surprised.
1 At launch the BBC micro:bit was supported on the BBC micro:bit website at http://www.microbit.co.uk . The micro:bit is now supported by the Micro:bit Educational Foundation at http://www.microbit.org
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 3
Using Simulink® students will experience a completely different type of thinking from more traditional languages. They will begin to think in terms of system elements and how each piece connects and influences each other, and how the signal flows from one block to the other. Through Simulink, students learn about computational thinking including sequencing, they can also experience concepts such as time and event driven systems, control loops, feedback, multiplexing, and periodic events that occur in industrial (physical or simulation) systems.
In our Simulink and MATLAB journey, we will learn the basic elements in a system via practical exercises. We will start with some very simple models, slowly progressing to building more complicated systems as we incorporate different logics, system concepts and controls in our models. We will gradually include more elements in our models. The visual nature of Simulink and the simple micro:bit API means that we can progress to build complicated applications quickly and focus on learning and developing more complicated concepts.
3 Basic concepts of Simulink®
Have you used a flowchart before to plot your logic flow? Flow chart and pseudocode are common techniques for programmers to plan or present their logic ideas.
Figure 1: A simple Simulink model compresses of a source, zero or more processing block and a sink
Using Simulink is not dissimilar to working with flowcharts. We work with signal flow in Simulink instead of logic flow. Signals can be a timer, events, or data. In the case of data, they are generated from a source; we manipulate (process) the data and determine the data’s destination.
Signals are generated from Simulink Source blocks. Based on the task zero or more processing and signal routing block(s) are used to manipulate the source(s). The signals will be terminated at Simulink Sinks. The source, processing or routing and sink form an end-to- end system level design.
3.1 Block Connections Most blocks have angle brackets on one or both sides. These angle brackets represent input and output ports:
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 4
Figure 2: A Simulink block called Integrator
The > symbol pointing into a block is an input port, which should connect to a Source or another processing block.
The > symbol pointing out of a block is an output port, which should connect to a Sink or another processing block.
A source generates signal(s), a sink terminates signal(s) and a processing block transforms the signal.
The following table shows some examples of Simulink blocks
Examples Type Explanations Source A constant block generates a
specific number or variable.
Source A timer element that will increase the counter from “0” or “1” to your specified upper limit repeatedly.
Source Generates signals containing x, y and z components of micro:bit’s accelerometer periodically.
Sink Display the numerical values of the signal (s) in real time.
Sink Plot the signal(s) against time at the end of the simulation/deployment
Sink Specify the output pot of a subsystem.
Sink Specify the destination of the signal, which is micro:bit’s LED display.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 5
Examples Type Explanations Processing Add or subtract two input signal to
one output.
Processing Compare the input signal to a constant. Output true or false based on the condition being met.
Signal Routing Choose a source/input to route to the output depending on the condition.
Blocks are connected by dragging from the arrow > at a source to the arrow < at a sink. If you align these arrows, a suggested connection will appear and you can realise this connection by clicking on the suggested line.
Figure 3: A Simulink example directly linking a source (5x5 matrix) to a sink (micro:bit LED display)
4 Simulink and Micro:bit
After you have created a model in Simulink, you then use “deploy to hardware” options to download the codes to micro:bit. During this process, Simulink will translate your blocks to micro:bit hardware language and the translated codes will be transferred via the USB cable from the computer/laptop to the micro:bit.
Deploying onto hardware is only one of the outcomes for a system model. You can also run models on the computer/laptop. In our later example, we will build a model to read in data from a serial communication port on our laptop to be run on a computer instead of the micro:bit.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 6
5 Microbit Support Package Installation from MATLAB 2016b
Before we start using Simulink with Micro:bit, we need to add Support Package for BBC micro:bit Board. The installation procedures are as follow:
1. Open MATLAB 2016b
2. From the Menu Toolbar, choose Add-On=>Get Hardware Support Packages
3. Search for microbit
4. Select and Install
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 7
Project 1: Flashing LED Display
Class: Year 7 +
Quick Start Computing Glossary
Program: A stored set of instructions encoded in a language understood by the computer that does some form of computation, processing input and/or stored data to generate output.
Matrix: A matrix is a rectangular array of numbers. It is similar to use of tables storing information.
LED: Light Emitting Diode – low power semiconductor lights
Objectives: learn how to open and use Simulink learn how to set the hardware target to invoke the correct translator (compiler) learn how to navigate Simulink library to retrieve blocks learn how to compile and download created program onto the micro:bit learn how to turn on and off LED lights on the LED screen learn how to change the brightness of the LED display
Computational/ System Concepts: Input and Output Abstraction Multiplexing Switch Logic combination Code Reuse
Lessons: 1. Setting up Simulink Model 2. Put a smile on micro:bit 3. Make micro:bit’s heart beat 4. Create a firework animation
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 8
Lesson 1: Setting up Simulink Model
PROCEDURES SCREEN SHOTS
Click on the Setting icon
1. Choose hardware Implementation from the navigation pane
2. Find “BBC micro:bit” from the dropdown list for Hardware board.
3. Click “Apply” and then “OK”
If “BBC micro:bit” is missing, you need to follow the “Add support package” guide to add the support for this device
Note: Simulink uses different tools to translate the blocks into machine language running on a device. That’s why it is important to configure the correct hardware.
The Simulink Window
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 9
Figure 4: The Simulink application
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 10
Lesson 2: Put a happy face on micro:bit
About the project In this lesson you will use three blocks to put a happy face on the micro:bit LED Matrix. LED stands for Light Emitting Diode, you can treat them as low power lights. You will be using a block with the happy face design, a block for the matrix and another block for the brightness.
Students in school are usually asked to draw a flow diagram or write pseudocode before writing a program. Let’s look at a flow diagram for displaying a happy face on the micro:bit. It might look something like this:
This diagram shows the steps clearly but it does not really help us write code. How do you go from a diagram like this to code in Python, TouchDevelop or your favourite language?
By contrast, it is fairly easy to see how to translate this into the blocks we need for a Simulink program, as we need a minimum of two blocks
A source block for the happy face and the brightness A sink block for the micro:bit’s matrix with its 25 LEDs.
Then we just link these blocks together to form a data flow. We’ll see this in detail next. Lesson 2 to 4 will prepare you to create a full micro:bit animation with Simulink.
Start
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 11
PROCEDURES
Description: Use brightness effect blocks to show animation on micro:bit.
Open Simulink Library on the menu toolbar The blocks you need are under the “Simulink Coder Support Package for BBC micro:bit” and “Simulink” categories
Simulink Elements: 1) Matrix 2) Micro:bit LED Display 3) Constant
Computational/ System Concepts: 1) Input 2) Multiport Input Building the Model 1. Double click Simulink Coder Support Package for BBC micro:bit to expand it and double
click LED. Double click LED Images. 2. Drag and drop the “Happy face” block on the empty space 3. From the LED Matrix output group, drag and drop “LED/ Matrix Display (Brightness)” 4. Click on an empty space on the model, start typing “Constant, choose “Constant” with
“Simulink/ Sources” as subheading. You can also drag and drop this block from “Simulink” category under “Commonly Used Blocks” sub category.
5. Connect the blocks by dragging the output on one block to the input of the connected block.
6. The finished model is shown 7. Double click on “Constant” and change the value to 10. Brightness level is from 1-10.
8. Save the model as “microbit_happy”. Don’t skip this step! 9. Download the model to micro:bit by clicking on the “Deploy to hardware” icon 10. You will see the software processing your system in the bar at the bottom of
the Simulink window. The LED on the back of the micro:bit will flash as the code is downloaded and a windows will appear on your computer’s screen with a Code Generation Report. Choose OK to close this.
Challenge: Double click on the Smiley face block and draw your own facial expression for your micro:bit. For example, could you add a nose to the face? How would you get your design to appear on the micro:bit’s matrix?
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 12
Lesson 3: Make micro:bit’s heart beat
PROCEDURES
Description: Use brightness effect blocks to show animation on micro:bit.
Your required blocks are under “Simulink Code Support Package for BBC micro:bit”
Simulink Elements: 1) Matrix 2) Micro:bit LED Display 3) Brightness effect
Computational/ System Concepts: 1) Input 2) Data flow
If you have closed your microbit_happy file, open it and choose File Save As .. to save a copy as “microbit_heartbeat”. If it is still open, just choose File Save As.. to save it as microbit_heartbeat. Alternatively you can build a new model from the beginning.
Building the Model 1. Delete the “Constant” block and the connection from the Task 1 model. 2. Drag “Pulse” block from the LED Brightness Effect sub-category. 3. Replace “the Happy face” block with a “Heart” block
4. Save your model. Don’t miss out this step! 5. Download the model to the micro:bit by clicking on the “Deploy to hardware”
icon.
Reflection: Does the image simply flash on and off? How would you describe the effect? Double click the “Pulse” block, change the “Fading step size” from 0.1 to 0.2 in your program and download it. How would you describe the change in the heart beat’s pace?
Challenge: Replace “Pulse” block with different brightness effects and change the parameters on the block. Please take time to try a number of different brightness effects. Think about how different effects could simulate heartbeats under different conditions, for example, resting in a chair, running up hill, feeling ill.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 13
Lesson 4: Create a firework animation
PROCEDURES
Descriptions: To create an animation, we need to create a set of matrix blocks. These are called “Frames”. We display them one by one.
Start with a new Simulink model and save it as “microbit_firework”
The blocks you need are under “Simulink Code Support Package for BBC micro:bit” and “Simulink” catagories
Simulink Elements: 1) Matrix 2) Micro:bit LED Display 3) Counter Limited
Computational/ System Concepts: 1) Input/ Output 2) Switch 3) Time driven system 4) Creating images 5) Animation
The Model
1. Add these blocks to the model, double click to change the parameters. Blocks Category Parameters Counter Limited Simulink/Sources Upper limit: 9 (number of frames)
Sample time: 0.2 (seconds between frames)
Multiport Switch Simulink/Signal Routing Data port order: One-based contiguous Number of data ports: 9
You will probably find it helpful to resize the multiport switch so that you can see all of the ports.
2. Adding the frames Drag 9 of the “empty matrix” blocks from the LED Images. The first empty matrix will have the title Empty Matrix and the second Empty Matrix 1. You may wish to rename them starting at “1” (renaming “Empty matrix 1” to “2” and so on. Double click each block in turn to get the effects shown below. You will be selecting each LED by ticking it rather than by setting a colour.
3. Selecting the LEDs to make a fireworks pattern
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 14
4. Now arrange the blocks in your model like this:
5. Save your model again. Now download the model to the micro:bit by clicking on the “Deploy to hardware” icon.
Challenges: 1. Make the animation faster by changing the sample time to 0.1 (s). 2. Create more frames to improve the quality of animation. 3. Design an animation of a moving creature.
Try to make sure that the connector lines do not cross each other. This will make your diagram easier to read.
Finally, add an LED Matrix block and link it to the Multiport switch
?? What should you put
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 15
Further explanation
The concept of a Simulink model focuses on Signal Flow – what signals are generated, the sources, how the signals are changed and routed throughout the system and the final destination of the signals, the sinks. It is similar to the input/processing/output model. In this example, we have the constant sources, which are the image frames, and a periodic signal source, “Counter Limited” and the sink, which is the LED Display. The multiport switch determines how the signals are routed.
This example is a time driven system. The “Counter Limited” block is time-dependent and is executed every periodic step. The duration of a step is determined with the “Sample Time” parameter in seconds. In this example, the animation frame is chosen depending on the output value of the “multiport switch”, which is driven by the output of the “Counter Limited” block.
The “Counter Limited” block has two parameters: upper limit and sample time (in seconds), data order. It starts the counter from zero every sample time and will roll back to zero once the upper limit is reached.
A system can have multiple concurrent timers and time driven elements that run at different speeds. The LED Matrix Display itself has multiple timers to drive the LEDs. The “LED effects” also have their own timers.
Another important element in this example is the “Multiport switch”. The term switch in a switching system comes from the control at interconnect telephone circuits to establish telephone calls. The “multiport switch” will select an input and pass it through to the output port based on the value at the switch (the top input with -| sign).
Extension: Create your image library (Appendix I)
You may wish to save your images, and - custom blocks for use in other programs. This is easy to achieve by creating your own Simulink library. A Simulink library is a place to store the blocks that are not connected to each other to be reused later.
A phone exchange before the days of digital phones.
Photo: Joseph A Carr, 1975
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 16
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 17
Project 2: Direction indicator for a bike
Class: Years 9 +
Quick Start Computing and System Glossary
Time driven: A flow of computer instructions that is driven by a clock at regular interval.
Event driven: A flow of instructions that is trigged by some events (e.g. a button press)
Switch: A switch is a one input, two-outputs element that outputs a value depending if the input value is true (1) or false (0).
Subsystem: A Simulink subsystem is a grouping of blocks that form a logical entity. A subsystem can have inputs and outputs and can be activated by conditions using trigger and enable blocks.
Objectives: learn how to abstract subsystem for code clarity and reuse – we will explain this in
lesson 6 learn how to develop an event driven system learn how to use external mode in Simulink
Computational/ System Concepts: Input and Output Abstraction (subsystem) Multiplexing Multiport Switch Event driven system Code reuse Input control
Lessons: 5. First experiment with buttons 6. Left and right Indicator Display 7. Micro:bit Indicator in external Mode 8. Button triggered Indicator
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 18
Lesson 5: First Experiment with Button
PROCEDURES
Descriptions: Use button blocks to see the effect of a button
Start with a new Simulink model and save it as “microbit_buttonFirstExperiment”
New Simulink Elements: 1) Micro:bit Button Pressed 2) Switches
Computational/ System Concepts: 1) States 2) subsystem
The Model
Build this model in Simulink.
When does the happy face come on? Is it what you expected?
The output of the “button pressed” registers the event and sends “1” signal the moment the button is pressed. It outputs “0” before we press the button and straight after the button is pressed.
When the button is pressed, it triggers a momentary signal source to kick start the system. The signal is fed into a switch to choose which image to display
Challenge: Try replacing “Button A Pressed” with “Button A released” and “Button A hold”, “Button A Digital Read”. Observe when the happy face comes on and how these blocks behave.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 19
Reflection:
Did you try Button A Hold? Did it do what you expected?
Look at the block parameters for the Switch: here are screenshots of the switch and the parameters:
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 20
Lesson 6: Left and Right Indicator Display
PROCEDURES
Descriptions: Switch display left and right arrow based on the value of a data store
Our goal in this module is to build a system using button presses as triggers to flash a left pointing arrow or a right pointing arrow.
Our first step is to use a data store with a value that can be set to turn the display on or off. We will use a data store memory block to hold a value (or variable in the terminology of some other languages).
Computational/ System Concepts: 1) Trigger 2) Subsystem 3) Actuation
Save your model as “microbit_indicator”.
The Model
In this model, We introduce the concept of Data Store Memory, a block defines and initializes a named shared data store. Let say if you want a certain value to be accessible by more than one block, you need to create a shared memory/ variable to store this value in a particular point of the program. This is called a Data Store Memory in Simulink. This memory (or variable) can be read by the block Data Store Read, and can be re-written by the block Data Store Write. Let’s look at the start of our model:
These are our new blocks. Remember the best way to search for a block is to start typing the block name in an empty space.
Blocks Category Parameters
Data Store Memory
Initial Value: 0
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 21
We would like the LED display to show left if the value of Data Store Memory “A” is 1 and show right if the value of “A” is 0. The “Data Store Memory” is the block that defines the name “A” and the initial value (which can be changed by double click on the block) of “A”. The block “Data Store Read” reads out the value of “A” at the time and output it to the input port of the Switch.
Save your model, you will develop it further in Lesson 7 and 8.
Download to the micro:bit, you should see a left arrow flash.
Reflection:
Set the initial value in the Data Store Memory to “1”. What do expect will happen?
Choose Deploy to Hardware. Did you model behave as you expected?
What happens if you set the value in the Data Store Memory to 2 or 5?
What happens if you set it to -3? Remember that you can always check what your model does by pressing the Reset button on the back of the micro:bit to run the model again.
What conclusion do you reach about possible values for the Data Store Memory in this model?
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 22
Lesson 7: Micro:bit Indicator in External Mode (continued from Lesson 6)
You can proceed to Lesson 7 directly if you not want to try external model in Simulink.
Preliminary Installation and Settings 1. Update Firmware on Microbit
Download and update the latest DAPlink firmware. It is a little piece of clever code permanently rest in Micro:bit that allows USB drag and drop and over the air programming.
2. Install Microbit serial driver on your computer/laptop This driver is responsible for converting the USB to serial communication on your computer/laptop, and allows it to talk to the microbit.
3. Find out the serial port (COM port) your Micro:bit is connected to In Device Manager You can open Control Panel=> Hardware and sound => Device
Manager, navigate to Ports (COM & LPT) as below:
It is “COM19” in this example. It will be different on your laptop/computer.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 23
Alternatively, you can type “mode” in Command Prompt (search google to see how to use this). This would list out all connected device.
3. Configure the Serial port:
The next step is to tell your Simulink model about this COM port. In Simulink, find Setting in the toolbar and choose Model Configuration Parameters.
In your Simulink model, you need to configure the communication port via setting for running external mode. This is usually known as “COM port”, the USB (serial) port viewed by your laptop/computer to “talk” to your micro:bit (or other device).
Open model configuration:
Input the name of COM port under “Hardware Implementation=>External mode=>Serial port” as below.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 24
PROCEDURES
Descriptions: Use External mode to change a data store value
Computational/ System Concepts: Variable (Memory Store), Serial communication
Continue from the model at the end of lesson 6, in this lesson, you will learn how to use Simulink external mode, and control micro:bit from the computer. Save your model as “microbit_indicator_external”
The Model
We will now add these elements in your model so that you can control the micro:bit from your computer.
These are the new blocks and the blocks need configuring:-
Blocks Category Note
Constant Simulink/Source Value: 1
1. Extend the model from Lesson 6 as below:-
Slider Switch
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 25
2. Double click on the Slider Switch and configure it as follow. Click on the list area under Connect, then select the Constant block in your model. The item “Constant:Value” will appear. Select the radio button to connect. Change the other parameters according to the figure below. Then click “Apply” then “OK”.
3. Now we can run the model. Instead of choose “Deploy to hardware”, you need to i) select “External” from the drop down menu (you may need to maximize the windows to see this), or choose it under “Simulation=>Mode=>External”. ii) Then click “Run”.
The above setting will allow Simulink to “talk” to your micro:bit for 30 seconds. You can increase or decrease the number to make the simulation last shorter or longer. Type “inf” in the box if you want to run the model for an infinite time until you stop the model.
If your Simulink model fails to run on Micro:bit, it usually is because of the configurations are not properly set up. Make sure that you have update the firmware on Micro:bit and check the COM port name and try again.
Challenge:
Connect a “Display” block from Simulink/Sink category to the “Constant” and “Data Store Write” Block, then run in external mode. What do you see when you flick the switch?
Is there a delay between the action and output?
To run for 30 Seconds
Start
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 26
Further Explanation:
1. External mode
In this example, we have used external mode to make a dashboard control (a switch slider) to change the direction of the arrow display on the microbit by changing the value of variable A.
When running in external mode, Simulink puts some additional communication codes to run on your microbit and instruct the microbit what to do next. This is separate from your own model/code.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 27
Lesson 8: Button triggered Indicator (continued from Lesson 6)
PROCEDURES
The Model
1. Re-open the model from Lesson 6, save model as “microbit_indicator_button”.
2. In a blank space, build the following:
4. Now select these blocks you have just built; right-click and select “create subsystem from selection” from the menu. This would group the blocks into a subsystem block represented by a simple rectangle.
5. Rename the new subsystem block as “set A to 1”, double click the block to reveal what’s inside. Now add a “Trigger” block from “Simulink/Ports and Subsystems”, or type “Trigger” in a black space within the subsystem.
6. On the menu bar, select the “up arrow” icon (Up to Parent) to go back to the main model.
4. Connect the subsystem “set A to 1” to “Button A Pressed” as shown below.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 28
5. Similarly, build a system called “Set A to 0”
The final model is like this:
1. Create subsystem 2. Add trigger
1. Create subsystem 2. Add trigger
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 29
Challenge
If you have learnt how to run in external mode, add a “Display” or a “Scope” block to observe the values of “A” changes when you press a button.
Further explanation
1. Subsystem
We have learned to group multiple blocks to form a subsystem in this task. Subsystem is a very powerful concept in Simulink. Not only that it helps to group related blocks into reusable submodules for clarity, you can also use “trigger”, “enable”, etc blocks to specify the conditions when the subsystem is run.
2. Button
The buttons on micro:bit are also called “tactile switches” or “momentary switches”. A switch has a state – either ON or OFF (or 0 or 1). A button changes its state only when it is actuated (“pressed”). When the button is pressed, the electric circuit is closed and a signal is sent to the micro:bit. The value of the digital pin connected between the button and micro:bit changes from “0” to “1”.
3. Event driven system
This example is an event driven (button) system. An “event” happens when button is pressed, which trigger our subsystem to run and change the behaviour of the model.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 30
Lesson 9: Viewing Accelerometer Data (External Mode)
PROCEDURES
Descriptions: Understanding the accelerometer sensor in micro:bit with External Mode
Computational/ System Concepts: 1) Serial communication. 2) Three dimensional accelerometer data
The Model: 1) Build the model with the following settings. Blocks Category Parameters
Accelerometer Simulink/Support Package for BBC micro:bit
Default
Mux Simulnk/Signal Routing Number of inputs: 3
Display Simulink/Sink Default (make the box bigger so it can show 3 displays at the same time)
Scope Simulink/Sink Default (double click to open)
2. Simulate/Run the model
To run the model, instead of using “download to hardware” button, use the dropdown menu to change the mode to “External”, then press the “run” button as in Lesson 7.
Double click to open the Scope so you can view the data in real time.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 31
Simulink will build the model and then enable external mode. You will see the data being updated in real time on the “Display” block. If you have doubled click the Scope before running the model, you will see the data plotted in real time.
The setting in the above figure will set the model to run for 120 seconds. Type “inf” in the box if you want to run the model for an infinite time until you stop the simulation.
2) Turn micro:bit around slowly and observe how the values of accelerometer change in all three axis.
Challenge 1. Use the accelerometer y-reading and build a model, such that when you turn the micro:bit vertical, it will display an image. 2. Use a multiport switch so that the micro:bit will display different images when it is positioned at different orientations.
Further explanation
1. External mode
External mode in Simulink is a very useful tool to allow you to view data coming from the micro:bit in near real time. This additional feature is unique in Simulink; you do not need to have an external serial monitoring program, or write another program to achieve this. Simulink enables this by constantly running a communication protocol between the hardware and the computer during external mode. A protocol is just a set of rules that control how something happens – in this case, how the micro:bit and the computer communicate with each other.
External mode is useful not only for displaying data in real time but also for debugging and testing your program. For example, if you need to display an interim value of a variable, you can output this to a display.
The next example will show you how to use external mode as an input to a model to change some values in real time.
1. Accelerometer
The accelerometer is a sensor that detects acceleration. It is generally used for motion detection or orientation. The accelerometer on the micro:bit is a 3-axis accelerometer, meaning that it can detect and distinguish acceleration in the 3 dimensions.
Even when the micro:bit is not moving, there is a constant acceleration enacts on it – the gravity. The amplitude of gravity is 1G, or 9.8m/s2. You can use this characteristic to determine the orientation of the micro:bit: for example, if you lay the micro:bit flat on a surface, the z-axis of the micro:bit will read around 1G.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 32
Lesson 10: Accelerometer X-Y-Z part II
PROCEDURES
Descriptions: Use “MATLAB Function” block to incorporate MATLAB code to turn accelerometer data into a bar chart display on Micro:bit
Computational/ System Concepts: 2D Matrix. Acceleration visualisation
2. The model
In this model, we add a MATLAB function to take in the accelerometer data, process them and output as a matrix that shows a bar graph of the values.
In an empty space, start typing “MATLAB” to get a “MATLAB Function” block, or drag one from “Simulink/User-Defined Functions”
Double click the block to reveal a Block editor where you can copy and paste, or type the following code in:-
function m = fcn(x, y, z)
m = zeros(5,5);
sensitivity = 0.3;
% convert x,y,z reading to bar chart readings x1 = round(abs(x)/sensitivity); y1 = round(abs(y)/sensitivity); z1 = round(abs(z)/sensitivity);
m(5:-1:6-x1, 1) = 1; %display x on column 1 m(5:-1:6-y1, 3) = 1; %display y on column 3 m(5:-1:6-z1, 5) = 1; %display z on column 5
The line begins with % is called comment. Comment is read by humans and ignored by the computer compiler.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 33
Save and close the MATLAB block editor windows and download the code to micro:bit.
Observe the value of the x, y and z (1st, 3rd and 5th column) in the bar graph. 3 lights = 1G acceleration. Tilt the microbit and see how the accelerometer values changed. Shake it to see how the accelerometer values changes.
>>
Further explanation When the micro:bit is stationary, there is a constant acceleration on earth, which is gravity, and it is approximately 1G. If we lay the micro:bit flat facing upwards, we will observe this 1G force on the z-axis (5th column) of 3 bars. You can tilt the micro:bit to the side, the gravity is now measured by the x component of the accelerometer. Tilt the micro:bit forward, you will see the gravity is now measured by the y-component.
Acceleration measures the change in velocity, therefore, we increase the acceleration by shaking the micro:bit. Try shaking it gently, rotating it, tilting it, make gestures and observe the change in the 3 values.
1.Matrix and MATLAB programming We have used of the term matrix (as in LED matrix) throughout the lessons. A matrix is a rectangular array of numbers, arranged in rows and columns. You can picture it as numbers in a spreadsheet in a rectangular shape.
A 2 by 3 (2x3) matrix looks like this
The numbers in the matrix are called elements or entries. The LEDs on micro:bit form an “LED matrix” because they are arranged in a 5x5 formation. The possible values for each element are “0” or “1”.
This is element (1,1) on microbit
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 34
In Matlab terminal (the windows that comes up when you first open MATLAB), let’s create the above matrix.
>> = [ , , , , ; , , , , ; , , , , ; , , , , ; , , , , ] A semi-colon at the end of an instruction is optional. You can leave it out and MATLAB will print the output of the instruction immediately. Each element in a row is separated by a comma “,”; and each column is separated by a semi-column“;”. A matrix is defined inside square brackets [ ].
Now, say, we want to address the element in circle. We type in the following:-
>> ( , ) “a” is the variable of the matrix/ array we just defined. The first argument inside the brackets is the row number, the second argument is the column number. The output of the command should be 1.
We can address multiple elements at a time. Say we want to address row 4, column 1 to 3 elements, we type in
>> ( , : ) The result is “1 0 0”, which is the three elements in row 4.
>> (: , ) will give you all the elements in column 1 and >> ( , : ) will give you all the elements in row 1.
In MATLAB, the index of the elements starts at 1 rather than 0.
Challenge Draw a concept diagram to explain how you would use the accelerometer to design a game based on motion or orientation.
Explain how you can use the accelerometer to detect different gestures to be used in the game control.
(e.g. “snake game” and you can move your snake by tilting the board)
0 1 00 0 0 01 0 10 1 0
An element
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 35
Appendix I: Create your own library
You can create your own library and, optionally, add it to the Simulink® Library Browser. You save a library as a .SLX file as you do a model. However, you cannot simulate in a library, and a library becomes locked for editing each time you close it. You must unlock a library before you make changes to it. See Lock and Unlock Libraries.
1. From the Simulink start page, select Blank Library and click Create Library. 2. Add blocks from models or libraries to the new library. Make the changes you want to
the blocks, such as changing block parameters, adding masks, or adding blocks to subsystems. Subsystem names in a library hierarchy must be unique. For example, do not create a hierarchy such as Subsystem_Name1/Subsystem_Name2/Subsystem_Name1.
3. Add annotations or images. Right-click the ones you want to appear in the library in the Library Browser and select Show in Library Browser.
4. If you plan to add the library to the Library Browser, you can order the blocks and annotations in your library model. By default, they appear alphabetically in the Library Browser, with subsystems first, then blocks, and then annotations. The user of your library can use the Library Browser context menu to choose between viewing them in alphabetical order or the order you specified. When the user selects this option, the order in which they appear in your library model determines the order they appear on the grid in the library in the Library Browser.
5. If you want the library to appear in the Library Browser, enable the model property EnableLBRepository before you save the library.
set_param(gcs,'EnableLBRepository','on');
6. Save the library.
Where you save the library depends on how you plan to use it. If you want to add it to the Library Browser, save it to a folder on the MATLAB® path or add the location to the MATLAB path. Otherwise, save it to a location where the models that use the blocks can access it.
If you want the library to appear in the Library Browser, you must also create a function slblocks on your MATLAB path that adds the library to the browser. For an example that shows complete steps for adding a library to the browser, see Add Libraries to the Library Browser.
© Venus Shum & Clifford French Ver 1.6, Jan 17 P 36
Appendix II: Useful Shortcut and Tips
Shortcut keys and tricks Description Hold “Ctrl” and click on a line Branching an input to a second output Start typing the block name on a blank space
To retrieve a list of all the blocks with the typed names
Scroll button To zoom in or out of the model Ctrl-R To rotate a block
It doesn’t work! Try these:
1. Is your micro:bit plugged in? 2. Unplug and plug in your micro:bit again. 3. Have you completed the hardware configuration step and changed the board to
micro:bit? 4. Has the connection to the micro:bit comes loose? 5. Restart MATLAB
Reference
[1] Steven T. Karris, “Introduction to Simulink with Engineering Applications, Orchard Publications,
[2] MicroBitDisplay class, Lancaster university, https://lancaster- university.github.io/microbit-docs/ubit/display/
[3] Simulink Stateflow Truth Table, http://uk.mathworks.com/help/stateflow/ug/programming-a-truth-table.html