Technology lessons for educational technology integration in the classroom. Content for teachers and students.

Coding, Micro:bit Alex Coding, Micro:bit Alex

Elapsed time, velocity and the Micro:bit

In this lesson, we are going to use the magnetic sensor to calculate the velocity of a car moving across a track.

This is the setup. I have a toy car, Hot Wheels, with a magnet attached to the roof. The car is on a Hot Wheels track. Next to the car and track is a sensor gate. The sensor gate has a Micro:bit. The micro:bit will use the magnetic sensor to detect the passage of the car and magnet through the gate. A small distance away is another sensor gate. This gate is also set to detect the passage of the car and magnet.

elapsed time and speed project with Micro:bit

In this lesson, we are going to use the magnetic sensor to calculate the velocity of a car moving across a track.

This is the setup. I have a toy car, Hot Wheels, with a magnet attached to the roof. The car is on a Hot Wheels track. Next to the car and track is a sensor gate. The sensor gate has a Micro:bit. The micro:bit will use the magnetic sensor to detect the passage of the car and magnet through the gate. A small distance away is another sensor gate. This gate is also set to detect the passage of the car and magnet.

The micro:bit will start a clock when the car passes through the first gate. The clock will stop when the car passes through the next gate.

Knowing the distance and time between the gates will help us calculate the velocity of the car. The micro:bit will provide the time it took the car to travel a specific distance. It will be up to us to calculate the velocity.

Disclaimer

I am not affiliated with Hot Wheels or the company that represents Hot Wheels. You don’t have to use Hot Wheels. I like to use them because they are small, inexpensive, and include tracks.

The gates

I designed the start and end gates with Tinkercad. The design is free to download and print. The links to the models and preview of each model are available in the resources section.

The first gate is designed to have enough clearance for a regular Hot Wheels car and a small magnet. The gate has a bed to hold the battery pack. The gate prints upside down so you don’t have to worry about removing supports.

start gate bridge 3d print
start gate bridge with Micro:bit and battery

The second gate is not designed to be a gate specifically. I use this to hold the micro:bit for a variety of activities. The holder is available in two formats. One format holds the regular AAA battery holder. The other format holds the lithium rechargeable battery.

Micro:bit holder with AAA battery support
Micro:bit holder with rechargeable battery holder

The cars and tracks are available online. I found the best prices on Amazon.

Hot Wheels car with small round magnet on roof

The magnets are also available on Amazon. You can get the cars, track, and magnets for less than fifty dollars. You don’t have to use the 3D printed gates. Use small cardboard boxes or structures build with popsicle sticks.

I’m not providing links to the resources on Amazon because links tend to change and suppliers tend to disappear.

Code Resources

Transmit Gate code (Make Code):

https://makecode.microbit.org/_DDhaW6diba5i

Transmit Gate code (Github):

https://github.com/digitalmaestro/startgate

Receive Gate code (Make Code):

https://makecode.microbit.org/_42eAezdFw0K0

Receive Gate code (Github):

https://github.com/digitalmaestro/finishgate

3D print resources

enclosed gate

Enclosed Gate preview

https://bit.ly/3xiWQfv

Enclosed Gate download (Thingverse)

https://www.thingiverse.com/thing:4837474

Enclosed Gate download donate at Cult 3D

https://bit.ly/32OiJFr

micro:bit holder

Micro:bit holder with lithium battery support preview:

https://bit.ly/2QSv0Gc

Micro:bit holder with lithium battery support (Thingverse)

https://www.thingiverse.com/thing:4837487

Micro:bit holder with lithium battery support donate at Cults 3D

https://bit.ly/3xiHuru

Micro:bit holder with AAA battery support preview:

https://bit.ly/2RPSD2G

Micro:bit holder with AAA battery support download at Thingverse

https://www.thingiverse.com/thing:4837494

Micro:bit holder with AAA battery support donate at Cult 3D

https://bit.ly/2Pf6Ll8

Magnetic direction and strength

The sensor on the micro:bit is located behind the buttons. The sensor is part of the chip dedicated to the compass. Version 1.3B has the chip near the extreme left edge.

micro:bit version 1.3B sensor closeup view

Version 1.5 has the chip on the left edge too. It is integrated into one chip that contains both the accelerometer and compass.

micro:bit version 1.5 sensor closeup view

Version 2.0 has the chip in the same general location. It is a little larger than the others.

micro:bit version 2.0 sensor closeup view

The sensor readings will be stronger when the magnet is closest to the sensor. In my lesson, the car will travel from right to left. The sensor is on the right side when the micro:bit is facing this direction. The sensor will detect the magnetic field almost as soon as the car is next to the micro:bit.

hot wheels car next to micro:bit and on hot wheels track

The strength of the magnetic field depends on the size and type of magnet.

This part of the lesson will gather information on magnetic field strength. We will use that information to set up the conditions for starting and stopping the timer.

We need to know the approximate strength of the magnetic field when the car is closest to the starting position. We want the starting position to be close to the right edge of the Micro:bit. This will start the timer as soon as the car enters the gate.

Use the link below to access the Make Code development page.

https://makecode.microbit.org

Click the New Project tile.

new project tile

Use ‘magneticStrength’ for the project name; click the Create button.

project name field

The start gate will send a signal to the finish gate when the car enters the magnetic field. We need to know what that information looks like before creating the code.

The micro:bit measures the strength of the magnetic force from three directions. The measurements are along the x, y, and z-axis.

The x-axis runs left to right along the long edge of the Micro:bit.

micro:bit image

The y-axis runs up and down along the short edge.

micro:bit image

The z-axis runs through the Micro:bit.

micro:bit image

We are going to collect information from one of these directions. This information will be stored in a variable.

Go to the Variables code category; click the ‘Make a Variable’ button.

make a variable button

Use ‘x-axis’ for the variable name; click the OK button.

variable name field

Three blocks are created for each variable. The first block is the variable itself. The Set block is used to assign values to the variable. The values can be numbers, letters, or operations. The Change code block is used to change variables with numbers with some regular amount.

variable code blocks

Get the [set x-axis] code; place it in the [forever] loop.

code block in forever loop

Select the Input category and then the more option. Look for the [magnetic force] code block.

magnetic force code block

Place the code block into the set variable parameter. The block is already set to get values from the x-axis.

magnetic force code block added

The value in the variable will continuously update. We won’t display the information on the micro:bit display. This would take too long to get the information we need.

We are going to send the information directly to the computer, which can display information faster. The information is sent along the cable. The cable is a Universal Serial Bus, USB. There is a code block that sends information along the Serial cable.

Click the Advanced code category button.

advanced code categories option

Select the Serial code category.

serial codes category

Find the [Serial write value] code block.

serial write value code selected

Place the code block in the [forever] loop; after the set variable code.

serial write code block added

Type x-axis into the value label field.

label added to value field

Go to the Variables category. Get the [x-axis] variable; place it into the value field.

x-axis variable code added

This is all the code we need to collect the magnetic field strength along the x-axis.

Connect your micro:bit to the computer. Click the Action menu and select ‘Download to micro:bit’.

download to micro:bit option

Leave the micro:bit connected to the computer.

A ‘Show console Device’ button appears in the simulator area. Click the button to open the console.

show console device button

The bottom of the console displays the stream of magnetic field values detected by the sensor.

magnetic strength values

A scrolling chart plots the values as they increase or decrease.

graph plot line

Get a small magnet and move it along the bottom of the Micro:bit. The numbers will go up and down.

x-axis magnetic microtesla values

Sometimes the values will change from positive to negative.

negative microtesla values

Magnetic field strength

We are not interested in the value from one axis. We want to get the overall magnetic field strength from the magnet. This will assure that we won’t miss the start and finish as the car passes through the magnetic field.

Click the ‘Go back’ button.

go back button

Click the force axis selector; choose strength.

vector selector

Change the value label to ‘strength’.

updated label value

Click the variable selector; select ‘Rename variable’.

rename variable option

Use ‘strength’ for the variable name.

rename variable field

Download the updated code to the Micro:bit; click the ‘Show console Device’ button.

Move the magnet around the micro:bit to find the point where the magnetic force is strongest. It should be strongest along the right bottom edge.

magnet near the right edge of the Micro:bit

The strength is over 1,000 when the magnet is near.

microtesla values in console

Move the magnet about an inch away.

magnet about an inch away from the Micro:bit

The strength value drops by over a thousand with my magnet.

microtesla values

We only need to look for a moderate increase in the magnetic strength.

There are times when the measurements appear as negative values. We will fix this in our code later.

Click the ‘Go back’ button. Click the Home button to return to the Make Code main page.

Make Code home button

Start gate

The start gate has the simplest task. It will sense the magnetic field strength from the magnet. When the detected magnetic field is at a specific strength it will trigger a message. The message is sent to the second gate. The second gate micro:bit takes care of starting and stopping the timer. It will also display the elapsed time.

Click the ‘New project’ tile.

new project tile

Use ‘startGate’ for the project name.

project name field

This micro:bit will send a signal to the finish gate. We need to activate the Radio function. The Radio function is used by one micro:bit to send information to another.

Select the Radio code category; find the [radio set group] code.

Radio code category selected

Place the code into the [on start] section.

radio set group code added to on start section

The radio group is a number. This number is like a channel. There are 256 possible channels, 0-255. We can use any channel. All the Micro:bits that need to communicate with one another must be using the same channel. Set the radio group to channel 7, just for practice.

radio channel set to 7

The micro:bit needs to decide when to send the message. Decisions are made using deductive logic. This logic is in the form of, ‘If something is True Then perform some action’.

There is more information on if-then statements on the CK-12 website. https://bit.ly/3nzyGJy

Go to the Logic category; look for the [If True Then] code block.

Logic category selected

Place the code into the [forever] loop.

condition code block added

The True parameter in the logic condition is another logic operation. This is where we look for a value or a comparison.

Go back to the Logic category; find the Equal comparison code.

comparison code blocks

Place the comparison code into the True parameter.

equality comparator added

Go to the Input codes and get the [magnetic force] code.

more input code blocks

Place the code on the left side of the comparison code.

code added to comparator

Change the force input from the x-axis to strength.

magnetic force selector

Use the comparison selector to select ‘greater than or equal to’.

comparator selector

We know that the magnetic strength can reach a strength of over 1,000. We also know that the strength can go down to less than 100. A value in the middle of this range would be a good way to determine the presence of the car and magnet. Enter 500 into the right side of the comparison.

value added to comparator

If the magnetic strength is equal to or greater than 500, we want to send a signal to the other Micro:bit.

Go to the Radio codes; find the [radio send string] code.

radio send string code selected

Place the code inside the condition.

radio send code added

Type ‘team1’ into the string assignment.

string added to parameter

I am using a keyword for the string. This keyword serves an important purpose. It provides a codeword that verifies the authentication of one micro:bit to the other.

This verification is important in the classroom. Students often forget to set the radio channel to anything other than channel 1. It is also possible that students or groups might select the same group number. Even if multiple Micro:bits are using the same radio channel, the keyword provides a verification before a message is accepted.

Go to the Basic code category. Find the [show icon] code block.

show icon code block selected

Place the icon code after the radio send code.

show icon code added

Click the icon selector and choose the Happy icon. This provides feedback so we know the magnetic strength was detected and exceeded the 500 microteslas we selected.

icon selector

Return to the Basic codes and find the [pause] code block.

pause code block

Place the code block after the icon code.

pause code block added

Click the time selector; choose 500 milliseconds.

pause time selector

Get the [clear screen] code block from the basic section; place it after the pause code.

clear screen code added

We need the pause and clear code to erase the icon after displaying the confirmation. It clears the display for future trials.

We should identify this micro:bit as the start gate. Get the [show string] code from the Basic code category. Place the code into the [on start] section.

code added to on start section

Replace the hello string with the letter ’S’.

the letter s in the string

Connect the micro:bit to the computer. Click the action menu and select Download to micro:bit.

download to micro:bit option

Eject the micro:bit and set it to one side. Let’s get to work on the code for the other Micro:bit.

Finish Gate

Click the Home button to return to the Make Code micro:bit home page.

Make code home page button

Click the New Project tile. Use ‘finishGate’ for the project name.

new project tile

Get the [radio set group] code from the Radio category. Place the code into the [on start] section. Change the radio channel from 1 to 7.

radio channel value set

This micro:bit listens for a message sent from the start gate micro:bit. Go to the Radio codes; look for the [on radio received ‘receivedString’] code block.

on radio received code

Place the code block on the canvas.

code on canvas

When the micro:bit receives a string, we need to verify the string. This is another example where we need a condition to check for something to be True.

Get the [if True then] code block; place it into the [on radio received] code.

condition code added

Go back to the Logic codes; find the string comparison code. This code has quotes inside each side of the comparison parameters.

comparator code selected

Place the code into the condition parameter.

comparator code added

Type ‘team1’ into the right side of the comparison.

label added to comparator

The ‘receivedString’ block on the [on radio received] code is a code block variable. It holds received signals from micro:bit devices.

Drag the code block from the [on radio received] parameter; place it into the left side of the comparison code.

string received code added

The code verifies that the string received matches the string we need to start the timer.

code blocks

When the string is received, we need to capture the current elapsed time on the micro:bit. The elapsed time is measured in milliseconds. There are one-thousand milliseconds in one second. The time will be saved to a variable.

Go to the Variables category; click the ‘Make a Variable’ button.

make a variable button

Use ‘startTimer’ for the variable name.

variable name

Get the [set ‘startTimer’ to] code; place it into the condition statement.

set variable code added

Go to the more code section of the Input codes; find the [running time (ms)] code block.

running time code selected

Place the code into the value assignment parameter of the [set ‘startTimer’ to] code.

code added to variable assignment

The current running time is stored in the [startTimer] variable. We need feedback to know this has been done. Go to the Basic codes; get the icon code block. Place the code after the set variable code. Leave the icon set to the heart.

show icon code added

This code gets the running time value from the micro:bit the moment it receives the message.

Review of what is happening

This is how it works. Let’s assume the start micro:bit sends the signal and it is received by the finish gate micro:bit. Let’s assume that the finish gate micro:bit has been running for 8000 milliseconds, 8-seconds. This value is stored in the variable ‘startTimer’. The car activates the sensor on the finish gate after 11000 milliseconds, 11-seconds.

We subtract the second reading, 11 seconds, from the first, 8 seconds. This gives the total elapsed time since the timer was triggered by the start gate.

Finish time

To get the finish time, we will create some code that is similar to the one from the first gate. The code will be in the [forever] loop so it is always looking for a change in the magnetic field strength.

Go to the Logic codes and get the [if True then] code block. Place the code into the [forever] loop.

condition code block added

Get the comparison code; place it into the True condition parameter.

comparator code added

Change the comparator to greater than or equal to.

comparator selector

Get the [magnetic force] code from the Input codes; place the code into the left side of the comparator.

magnetic force code added

Change the force vector to measure the strength of the magnetic field.

force coordinate selector

Enter the magnetic field strength you want to sense into the comparator. This can be the same value we used for the start gate.

value added

We want to record the current running time when the car is close to the gate. This information will be stored in another variable.

Go to the Variables category; click the ‘Make a Variable’ button. Set the name of the variable to ‘finishTime’. Place the [set ‘finishTime’ to] code into the condition statement.

variable set code added

Get the [running time (ms)] code from the Input category. The code is under the More codes option. Place the code into the value assignment for the ‘finishTime’ variable.

code added to variable

We have the first running time saved in one variable and the second time saved in another. We can now subtract these values to get the time it took to travel from the first gate to the second.

We need another variable to store the results. Go to the Variables category. Create a new variable; use ‘elapsedTime’ for the variable name. Place the [set ‘elapsedTime’ to] code after the other set variable code.

elapsed time variable set code added

Go to the Math code category; find the subtraction operation.

subtraction code block

Place the operation into the assignment parameter for the [set ‘elapsedTime’ to] code.

subtraction code block added

Get the ‘finishTime’ variable; place it into the left side of the subtraction operation. Get the ‘startTime’ variable; place it on the right side of the operation.

variables added

convert seconds

The difference is calculated and represented in milliseconds. We can keep the answer in milliseconds, but I think it is much better to get the result in seconds. To convert milliseconds to seconds we need to divide by 1000.

We need another variable to store the answer. Go to the Variables category. Create a new variable; use ‘seconds’ for the variable name. Place the [set ‘seconds’ to] code after the [set ‘elapsedTime’ to] code.

set variable code added

Go to the Math codes; get the division operation. Place the operation into the assignment parameter for [set ‘seconds’ to].

division code added

Get the [elapsedTime] variable; place it into the left side of the division operation. Enter 1000 into the right side of the operation.

variable added and value updated

A confirmation

We need a way of knowing that the magnet’s passage recorded and the micro:bit calculated the elapsed time. Get the [show icon] code; place the code after the last code in the condition statement. Change the icon to a checkmark.

show icon code added

The elapsed time

Go to the Input category; find the [on button A pressed] code.

button A pressed code

Place the code on the workspace.

code added to workspace

Get the [show number] code from the Basic code category; place it into the [on button A pressed] function. Get the [seconds] variable; place it into the show number parameter.

code added to button a pressed

Identify the micro:bit

We need to identify this micro:bit as the finish gate. Place the [show string] code, from the Basic section, into the [on start] section. Use the letter ‘F’ for the string value.

show string code added

Absolute field strength

We need to take care of one more item. During our magnetic field strength at the beginning of the lesson, we noted that the values sometimes flipped from positive to negative. We need to take care of that to avoid false readings.

This is what could and does happen, at least during my trials. A magnetic value of (-900), negative 900, will not trigger the code to start or stop the timer. This happens because negative 900 is not greater than or equal to positive 500.

Go to the Math code category; find the [absolute of] code.

absolute code

Place the code above and to the right of the [forever] loop, not in the loop.

code placed on workspace

Get the [magnetic force] code and place it into the [absolute of] parameter.

magnetic force added to absolute code

Get the code blocks and place them back into the left side of the comparator.

code replaced

Click the action button and download the code to the micro:bit. Eject the micro:bit. Click the Home button.

microbit-velocity-timer-109e.jpg

Open the ‘startGate’ project. Connect the start gate micro:bit.

startGate project tile

Get the [absolute of] code block; place the [magnetic force] code into the parameter. Place both blocks back into the comparator. Download the code into the micro:bit.

code updated with absolute operation

Off to the races!

The image below shows the car on the track. The car and track are against the gate to get the best signal strength possible.

car, track, and micro:bit

The happy icon appears when the magnetic force is greater than or equal to 500.

happy face on Micro:bit

The finish gate shows it is waiting for the timer signal.

Finish gate Micro:bit

The heart icon shows the timer message was received.

heart icon on Micro:bit

Once the car enters the gate, a checkmark icon appears to indicate the magnet was sensed and the elapsed time was calculated.

checkmark icon on Micro:bit

Press button A to display the elapsed time.

time scrolling across Micro:bit display

Calculating velocity

To calculate the velocity we need one more piece of information. We need to know the distance between the gates. It helps if we can get a good measure of the distance. We need to know the point where the start and finish gates record the running time.

Place the finish gate next to the track where it will record the finish. Move the car slowly up to the gate. Stop when the checkmark appears. Place a mark to show the point where the front of the car marks the finish line. Repeat the process with the start gate.

finish marker

Get a ruler and measure the distance between the two marks.

marker and ruler measuring distance

Final notes

Be careful not to bring a magnet close to the finish gate after it has recorded the elapsed time. This will cause it to update the elapsed time with new values.

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit timer and stopwatch

This lesson will use the internal timer to create a basic stopwatch program. The program in this lesson is based on the code provided by Micro:bit to learn the fundamentals. I’ve taken it and expanded on the explanations.

microbit timer and stopwatch

Timer and stopwatch

Every computer and microcontroller has a built-in clock. This clock is important because it is used to synchronize operations and data transmission. Computers have a built-in rechargeable battery that keeps a clock going when the computer is not powered. This clock is used to keep track of the date and regular time according you your timezone.

Each computer also has an internal timer that begins when the computer starts. The Micro:bit has an internal timer that begins when it is powered or restarted. The timer keeps track of events and coordinates the synchronization of operations and data transfer.

This lesson will use the internal timer to create a basic stopwatch program. The program in this lesson is based on the code provided by Micro:bit to learn the fundamentals. I’ve taken it and expanded on the explanations. The link to the Make Code micro:bit lesson is available below.

https://makecode.microbit.org/projects/stopwatch

Project previews

Use the links below to get a preview of the final project.

StopWatch Make Code:
https://makecode.microbit.org/_PuY8zVbzuXDd

StopWatch Github:
https://github.com/digitalmaestro/stopwatch

Stopwatch

Use the link below to access the Micro:bit development environment. You don’t need an account to begin creating projects for Micro:bit.

https://makecode.microbit.org

Click the Create new project button.

new project button

Use “stopWatch” for the project name; click the Create button.

project name

Every new project includes two code blocks on the coding workspace. These blocks include the [on start] section and [forever] loop.

default code blocks on start and forever

The [on start] section is used to run code as soon as the Micro:bit starts or is restarted. This is where we usually define variables. We will use plenty of variables in our project.

The [forever] loop runs code for as long as the Micro:bit is powered. Code inside this loop does not require any user interaction. We won’t be using the [forever] loop in this project.

Get the [forever] code block and drag it to the Codes Section. Release the code block when a Trash Can icon appears.

removing forever block

Go to the input section; find the [on button A pressed] code block.

Input code category selected

Place a copy of the code block on the workspace.

on button a pressed code added

The internal timer begins the moment the Micro:bit starts. There is no way to reset the timer once the Micro:bit has started. We need to capture a moment from the internal timer and save it for use later. That moment will be saved in a variable.

Go to the Variables section; click the ‘Make a Variable’ button.

make a variable button

Use ‘Start’ for the variable name; click the OK button.

variable name

Three blocks are created for each variable. The first block is the variable itself. The Set block is used to assign values to the variable. The values can be numbers, letters, or operations. The Change code block is used to change variables with numbers with some regular amount.

variable code blocks

Place the [set Start to] code block into the [on button A pressed] function.

set variable code block added

Select the Input code category and click the more option.

more option in input category selected

There are two runtime code options. One records time in milliseconds(ms), and the other in microseconds(micros). There are one-thousand milliseconds in one second. There are one million microseconds in one second.

We are going to use the millisecond option.

running time code options

Place the [running time (ms)] code into the set variable parameter.

running time code added to parameter

Let’s get an idea of what this timestamp in the [Start] variable looks like. Go to the Basic code category; find the [show number] code block.

show number code block in basic category

Place the code block into the [on button A pressed] function and below the set variable code.

show number code block added

Go to the Variables section; get the [Start] code. Place the code into the [show number] parameter.

start variable added to show number

Go over to the simulator and click on button A.

Micro:bit simulation

A number will scroll across the display. This is the elapsed time since the virtual Micro:bit started.

numbers scrolling across display

Click button A again; the number will be larger because more time has elapsed.

numbers scrolling across display

The variable has captured this moment in time from the Micro:bit. With this time saved, we will subtract a future time to give us the elapsed time.

We need another variable to save the elapsed time. Go to the Variables section; click the ‘Make a Variable’ button. Use ‘elapsed’ for the variable name.

variable added to variables section

The elapsed time will be calculated and saved when we press another button. Go to the Input section. Get the [on button A pressed] code block. Place it onto the workspace.

The second [on button A pressed] code block is green with hash marks. The code is inactive because we cannot have two code blocks that refer to the same button at once.

button block greyed out

Click the button selector; choose button B.

button selector and button B selected

Go to the Variables category; get the set elapsed code block. Place the code block into the [on button B pressed] function.

set variable code block added

We need to subtract the current run time from the one recorded and saved in the Start variable. Go to the Math code category; find the Subtraction operation.

math operations section

Place the code block into the Set Variable parameter for the button B function.

subtraction operation added

Go to the Input category and the more section. Get the [running time (ms)] code block. Place it into the left side of the subtraction operation.

running time code added

Go to the Variables section. Get the [Start] variable; place it into the right side of the subtraction operation.

variable added to operation

Go to the [on button A pressed] function. Right-click on the [show number] code block; select the duplicate option.

duplicate option selected

Get the duplicate code and place it into the [on button B pressed] code; place it after the set variable code.

show number code block

Click the variable selector; choose the [elapsed] variable.

variable selected

Elapsed time in milliseconds

Click button A in the simulator. A long string of numbers will scroll across the display. This is the time in milliseconds. Reading the time in milliseconds is not human-friendly. Let's get the Micro:bit to display the times in seconds.

Elapsed time in seconds

One-thousand milliseconds is one second. We need to divide the total milliseconds by 1000.

Go to the Math code category. Get a copy of the Division operation and place it on the workspace below the [on button A pressed] function. Don’t put it into the function yet.

division operation on workspace

Get the [Start] variable from the [show number] code; place it into the left side of the division operation.

variable added to division operation

Place the division operation into the [show number] code parameter.

operation added to show number code

Type 1000 into the right side of the division operation.

value added to operation

Repeat the process for the button B code.

code for button b pressed

Click button A in the simulator. Wait a second or two and click button B. The values scrolling across the display will begin with a whole number followed by a number rounded to two decimal places.

Press button A to get the latest running time. Press button B to get the updated running time and subtract it from the first. This is your basic stopwatch.

If you press button B again—without pressing button A first—you will see a longer elapsed time. This is like a stopwatch lapse function.

Click the Actions menu and select Download to Micro:bit.

download to Micro:bit option
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit conductivity tester

The conductivity tester in our lesson will help us identify items that are conductors, resistors, or insulators. Conductors and resistors are very similar. Both of them allow electrons to flow through a circuit. Resistors allow less of the electrons to flow. Some electronic components need more current and some require less. Too much current going to a component that requires less can damage the component. Resistors are used to reduce the amount of current going into those components.

Micro:bit conductivity tester

Conductivity tester

There are items everywhere that conduct electricity. They allow electrons to flow from one end of a circuit to another. Some items are better at conducting electricity than others. Items that resist the flow of electricity are called resistors. Some items prevent the flow of electronics completely. These are known as insulators.

Conductors and resistors are very similar. Both of them allow electrons to flow through a circuit. Resistors allow less of the electrons to flow. Some electronic components need more current and some require less. Too much current going to a component that requires less can damage the component. Resistors are used to reduce the amount of current going into those components.

The conductivity tester in our lesson will help us identify items that are conductors, resistors, or insulators.

I have created a table with items to test for conductivity and resistance. The table contains items that are solids and others that are liquids. I tried to keep the list to items that are inexpensive and easy to gather. Feel free to modify the table of items to suit the needs of your classroom.

I included items with liquids to demonstrate that not all conductors are solids. This is one reason we don’t touch circuits with wet hands. Liquids with impurities facilitate the flow of electrons.

Use this lesson for a basic introduction to conductors, resistors, and insulators. The tables include spaces for values. You might want to graph these values in your activities.

Supplies

  • 1 Micro:bit

  • 1 Micro:bit power supply (battery pack or computer)

  • 2 alligator clip connectors

  • 2 medium or large paper clips

  • materials to test

Resources

Use the links below to get a copy of the final project.

Basic conductivity worksheets

Extended conductivity activity

conductivity tester Make Code :
https://makecode.microbit.org/_9gDPbzK8p2Xg

conductivity tester Github :
https://github.com/digitalmaestro/conductivitytester

Conductivity tester

We are using the Make Code development environment from Microsoft. We don’t need an account to create projects with Make Code. Use the link below to access the Make Code development environment.

https://makecode.microbit.org

Click the New Project button.

new project button

Use ‘conductivityTester’ for the project name; click the Create button.

project name

Every new project includes two code blocks on the coding workspace. These blocks include the [on start] section and [forever] loop.

default code blocks on the workspace

The [on start] section is used to run code as soon as the Micro:bit starts or is restarted. This is where we usually define variables.

The [forever] loop runs code for as long as the Micro:bit is powered. Code inside this loop does not require any user interaction. This is where we will develop the code for our tester.

The Make Code development environment has a Micro:bit simulator. The simulator has contacts along the bottom, just like the real Micro:bit. Some of the contacts have labels. Contacts with labels 0, 1, and 2 are used for external components. The contact labeled 3V provides 3-volts to external components. The GND contact is called the Ground. All circuits need to be connected to a ground to complete the circuit. Think of the ground as the negative side of a battery terminal.

Important: Never connect the 3v and GND directly. This could severely damage your Micro:bit.

The contacts labeled 0, 1, and 2 are referred to as General Purpose Input and Output pins. They can function as either input or output. We will use one as an input.

We are going to use the simulator to provide a foundation for the readings from the actual Micro:bit. This will help us understand the information to be displayed later.

micro:bit simulator

Go to the Basic code section; find the [show number] code block.

show number code block

Place the code block into the [forever] loop.

code in forever loop

Select the Advanced section to display more code block options.

advanced code section

Select the Pins section.

Pins code category selected

Find the [analog read pin] code block.

analog read pin code block selected

Place the code block into the [show number] parameter.

analog read pin code added

This code displays the information read by one of the contacts. The contact in this example is contact zero.

The simulator has a small number—zero—to the right of contact. This number provides feedback on simulated input. This number does not appear on the real Micro:bit. It is here to simulate input for the contact. The Micro:bit displays the number zero too.

pin zero displayed

Click on the contact and drag it up. You're going to see a color bar rise as we move the mouse pointer up. The value next to the contact will increase too. This number represents electric current. The current is combing from the Micro:bit voltage supply.

orange color bar

Drag the meter to the top of the contact. Stick to the edges of the contact to go around the circle or whole in the Micro:bit. The maximum value for the input is 1023.

top value in the simulator contact

What does the number mean?

The value of 1023 comes from Micro:bit's use of the 10-digit binary system. Every bit of information in a computer is either 1 or 0. Bits are combined to create everything in the computer. Characters are often stored in 8 or 10-bit binary strings. A string of 8 bits can represent 256 values. That number is 2 raised to the power of 8. A string of 10 bits can represent 1024 values. Increasing the number of bits provides more values and greater precision.

The Math is Fun website provides a nice explanation of the binary system. Use the link below to access the binary page for more information.

https://www.mathsisfun.com/binary-number-system.html

Variables

We need a variable to store the information read by the input pin. Go to the Variables section; click the ‘Make a Variable’ button.

make a variable button

Use ‘current’ for the variable name; click the OK button.

variable name field

Three blocks are created for each variable. The first block is the variable itself. The Set block is used to assign values to the variable. The values can be numbers, letters, or operations. The Change code block is used to change variables with numbers using some regular amount.

variable code blocks

Get the [set current to] code block; Place it into the [forever] loop. Place it above the [show number] code block.

set variable code block added

Get the [analog read pin] from the [show number] parameter; place it into the [set current to] parameter. This code assigns the value read from Pin0 to the variable [current].

analog read pin moved to variable assignment

We don’t need the [show number] code. Right-click on the code block; select the Delete block option.

delete code block

If an object is conductive, it will permit a flow of current. Any amount of current will be good enough for us to determine if an item is a conductor. The lowest value recorded by the micro:bit is zero. When it displays zero, no current is flowing through the Micro:bit. When a value is greater than zero means that some current is flowing. We will see later that this is not so for the physical Micro:bit.

Go to the Logic section; find the [if…then…else] condition code block.

condition code block

Place the condition code block in the loop, after the variable.

condition code block added to forever loop

The condition statement needs to evaluate a condition. It needs to evaluate if something is True. Go back to the Logic section; find the less-than comparison code block.

less than comparison operator

Place the Comparison code block into the condition evaluation parameter.

less than code block added

Click the comparison selector; choose greater-than.

greater than comparator selected

Go to the Variables section. Get the [current] variable; place it on the left side of the comparison code.

variable added to comparator

If the value in the variable [current] is greater than zero then we want to display something.

Go to the Basic section; find the [show icon] code block.

show icon code block

Place the code block into the first section of the condition statement.

show icon code block added

Click the icon selector; choose the checkmark icon or any icon you prefer.

icon selected

Go back to the Basic code section. Get another [show icon] code block; place it in the Else section. Change the icon to an ‘X’ or any icon you prefer.

show icon code added to else section

The Micro:bit will display an X as long as the probes are not connected to an object that conducts electric current. A checkmark will appear once the probes come into contact with something that conducts electricity.

Simulation vs reality

The simulator shows that the Micro:bit returns a value of zero when it is not connected to a conductive object. This is not so for the physical Micro:bit. This is not what I expected when I downloaded the program to the Micro:bit.

When coding we often run up against things we didn’t expect. Dealing with those unexpected situations is a big part of coding. We need to calibrate the values in our code before using it to test for conductivity.

If you were watching NASA and Ingenuity, you know that unexpected things happen. The NASA programmers had to upload a fix to the program before Ingenuity could fly.

Go to the Basic code section.

Get the [show number] code block; place it after the set code.

Place the [current] variable into the [show number] parameter.

Place a Pause code block after the [show number] code.

Change the pause duration to 500(ms).

Add a [clear screen] code block after the pause code.

code added

Click the Actions menu and select Download to micro:bit.

download code option

Don’t touch any of the contacts on the Micro:bit. The Micro:bit will display the checkmark followed by a number value. This is the pin reading from the Micro:bit. The number displayed on my Micro:bit is 208. The number displayed on yours might be different.

I went through the same process on three other Micro:bit. Each one gave me a slightly different number. The number displayed is the value at which nothing is connected to any of the contacts.

Calculate voltage

This value represents the current or volts registered by the Micro:bit. We can determine the voltage with a simple math formula. The formula is in the image below.

The total value we can get from the reading is 1023. The voltage from the Micro:bit is 3-volts. Multiply the reading from the Micro:bit, 208 in my example, by 3-volts. Divide the product by 1023. The answer for my example is .60997 volts. This is less than one volt.

voltage calculation

We can come to an agreement that any reading that is less than 1-volt can be ignored. This eliminates the strange readings which are probably caused by static electricity and electronic devices surrounding the Micro:bit.

The binary number 1023 represents a total of 3-volts. Dividing 1023 by 3 will give us the binary equivalent of 1-volt. Return to the code; enter 341 into the comparison parameter.

updated comparison value

Download the updated program to the Micro:bit. The Micro:bit will display the binary value from the contact reading. Use this value to calculate the voltage going through the conductor.

Connections and examples

Connect the alligator clips to the 3-volt and Pin-0 connectors.

clips connected to Micro:bit

Connect the Micro:bit to a power supply.

battery pack connected to Micro:bit

Don't dip the alligator clip into liquids. Don't pierce the fruit and vegetables with the clip either. Use a probe; I like paper clips.

*Don’t drink the liquids after testing!*

*Don’t eat the fruit after testing!*

alligator clip gripping paper clip

Use the curled inside of the paperclip to grip the sides of containers. Glass and plastic are good insulators. Use glass or plastic to hold the liquids for testing.

paper clip gripping side of glass container
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Collect data from multiple micro-bits

This lesson focuses on using several Micro:bits to collect sensor information and relay that information to one Micro:bit. The one Micro:bit is connected to a computer to collect data and save it to a Comma Separated Value, CSV, file.

sensor data from multiple micro-bits

Sensor data from multiple micro-bits

Many classroom teachers might have one Micro:bit per student or one per group. This arrangement is nice for most applications. There are applications where we need more than one Micro:bit. For example, when we need to collect remote sensor information and send that information to a Micro:bit connected to a computer.

In another example, we need to collect remote information from several Micro:bit devices. Each device needs to pair with a separate Micro:bit to collect the data.

This lesson focuses on using several Micro:bits to collect sensor information and relay that information to one Micro:bit. The one Micro:bit is connected to a computer to collect data and save it to a Comma Separated Value, CSV, file.

Project previews

Use the links below to get a preview of the final project.

Sensor Data transmitter (Make Code): https://makecode.microbit.org/_3EzC8P6DoFch

Sensor Data transmitter (Github): https://github.com/digitalmaestro/datatransmitter

Sensor data collector (Make Code): https://makecode.microbit.org/_bLW8Kf91PcTe

Sensor data collector (Github):
https://github.com/digitalmaestro/datareceiver

The project

Use the link below to access the Micro:bit development environment. You don’t need an account to begin creating projects for Micro:bit.

https://makecode.microbit.org

Click the Create new project button.

new project button

Use “dataTransmitter” for the project name; click the Create button.

project file name field

Every new project includes two code blocks on the coding workspace. These blocks include the [on start] section and [forever] loop.

code blocks on workspace

The [on start] section is used to run code as soon as the Micro:bit starts or is restarted. This is where we usually define variables. We will use plenty of variables in our project.

The [forever] loop runs code for as long as the Micro:bit is powered. Code inside this loop does not require any user interaction. We won’t be using the [forever] loop in this project.

Get the [forever] code block and drag it to the Codes Section. Release the code block when a Trash Can icon appears.

removing forever code block

The data from this Micro:bit will be sent to another Micro:bit. That Micro:bit will collect and store the information sent to it by each data transmitting Micro:bit.

Radio activation

To send data from one Micro:bit to another, we need to activate the Radio. Go to the Radio codes section. Find the [radio set group] code block.

radio code blocks section

Place the [radio set group] code block into the [on start] section.

radio set group code block added

The Radio Group code block uses a number to represent the channel for transmitting and receiving information. This channel links two or more Micro:bit devices. Micro:bits that need to communicate with one another need to be using the same group number or channel. We can use any channel from 0 to 255. That’s a total of 256 channels.

The group is set to channel 1 automatically. This channel is fine to use unless you get interference from other classroom Micro:bits. Make sure to use the same group number for the sending and receiving Micro:bit.

Go to the Input codes section. Find the [on button A pressed] code block.

input code section selected

Place the code block on the workspace.

on button a code block added to workspace

When the button A is pressed the Micro:bit will send sensor information to a listening Micro:bit.

Go to the Variables section; click the Make a variable button.

make a variable button

Use “temperatureData” for the variable name; click the OK button.

variable name field

Three blocks are created for each variable. The first block is the variable itself. The Set block is used to assign values to the variable. The values can be numbers, letters, or operations. The Change code block is used to change variables with numbers with some regular amount.

variable code blocks

Get the [set temperatureData to] code block; place it into the button A pressed function.

set variable code block added

Go to the Input codes section; find the [temperature] code block.

temperature input code block

Place the code block into the set variable parameter.

temperature code block assigned to variable

The value from the temperature sensor is now stored in the [temperatureData] variable.

Go to the Radio code section; find the [radio send value] code block.

radio code blocks section

Place the code block into the button A pressed function. Place the code block after the value assignment.

radio send value code block added

The send value code block has two parameters. This is known as a Name-value pair. The first parameter is a label for the value in the second parameter. The label is usually something like the word temperature to identify the sent value as the temperature. When collecting data from multiple Micro:bits it is useful to know where the information came from.

Labels in the name-value pair are limited to 8 characters. I use the student or group name along with the data label. For example, 'Alextmp' or 'Grp01tmp'. I use this information to group and sort the data in a spreadsheet later.

Type ‘Grp01tmp’ into the label parameter.

send value name assigned

Go to the variables section; get the [temperatureData] variable and place it into the second parameter.

temperature variable added

This is the basic code needed to transmit sensor data from one Micro:bit to another. The code sends one piece of sensor information. Let’s add more sensor information to send. We’ll add the light sensor data to our set of data sent to the Micro:bit.

Go to the Variables section; click the Make a variable button. Use “lightData” for the variable name.

variable name field

Get the [set lightData to] code; place it in the button A pressed function. Place it before the radio \\[send] value code block.

set variable code block added

Go to the Input section; find the [light level] code block.

l

Place the [light level] code into the [set lightData to] parameter.

light level code block added

Get a [radio send value] code block from the Radio section. Place the code block at the end of the code blocks in the button A pressed function.

radio send value code block added

Set the label to ‘Grp01lgt’.

value field updated

Get the [lightData] variable; place it into the second parameter.

light data variable added

Repeat this process with other sensor values you want to send.

Download to the transmitter

Connect your Micro:bit to the computer. Click the action menu button. Download this program to the sending Micro:bit. Eject and disconnect the Micro:bit.

download to micro:bit option selected

You can download this code onto different Micro:bits using one computer. All you need to do is change the group name.

Receiving Micro:bit

Click the Home button to return to the main Make Code page for the Micro:bit.

make code home page button

Create a new project. Use ‘dataReceiver’ for the project name.

Get the [radio set group] code block; place it into the [on start] section. Make sure the group number is set to the same number used in the transmitting Micro:bit.

radio set group code block added

Go to the Radio code section; find the [on radio received] code block.

on radio received code block selected

Place the code block on the workspace.

on radio received code block added to workspace

Click the Advanced section button.

advanced code section selected

Select the Serial code section; find the [serial write value] code block.

serial write value code block selected

Place the [serial write value] code block into the [on radio received] code.

serial write value code block added

The [serial write value] code has two parameters. These parameters are like the ones we used in the radio send code. The left parameter is for the label and the right is for the value. The values for these parameters are stored in the radio received code.

Click the ‘name’ parameter and drag it down into the label parameter.

name variable added

Drag a copy of the ‘value’ variable into the right parameter of the serial write value code.

value variable added

This is all the code needed for the receiving Micro:bit. Download the code to the Micro:bit. Leave this Micro:bit connected to the computer. Don’t leave the Make Code development environment. It needs to be open to collect the data and prepare it in a CSV file.

Collecting data

Press the button on one of the data collection Micro:bits. This activates the data collection mode on the Micro:bit and the development environment. The Micro:bit and the Make Code IDE is accepting data when you see the Show Console Device button. Click the button to enter the data display and collection portal.

show console device button

Proceed to collect data from the Micro:bits once you are in the console. The values are displayed in the section at the bottom of the console. This Micro:bit has collected sensor data from three Micro:bit devices.

data received from three Micro:bit devices

The collected data can be downloaded using the download button.

download CSV file button
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit multiple sensor information

This lesson will create a program to collect data from at least three sensors on the Micro:bit. The lesson will cover a fourth sensor option for collecting moisture information. The Micro:bit has several sensors that are useful in scientific explorations. They are useful for students that want to create a science project that uses several sensors. The Micro:bit can collect data from all the sensors at the same time. This includes sensors on the Micro:bit and sensors connected to it.

Micro:bit multiple sensor information data collection

Multiple sensor information

The Micro:bit has several sensors that are useful in scientific explorations. They are useful for students that want to create a science project that uses several sensors. The Micro:bit can collect data from all the sensors at the same time. This includes sensors on the Micro:bit and sensors connected to it.

Collecting and storing sensor data is useful for analyzing information over time. The Micro:bit can save the information collected from the sensors to a Comma Separated Value, CSV, file. Open the CSV file with any spreadsheet program to analyze the data and create charts.

This lesson will create a program to collect data from at least three sensors on the Micro:bit. The lesson will cover a fourth sensor option for collecting moisture information.

Here is a science exploration scenario. We have at four plants. Each plant is located in one of the four cartesian coordinates of North, South, East, and West. The purpose of the exploration is to understand how the plant’s exposure to the sun affects its growth. Each plant is cared for by a group of students. They are charged with collecting sensor information three times during the day.

The students will collect information from the light, temperature, and compass. The data will be shared with other students in the class.

A fourth sensor reading is not from one that is part of the Micro:bit. This fourth sensor reading measures the moisture content of the plant. The Micro:bit measures the amount of resistance present in plant soil. Water interacts with the soil to create a medium that conducts electricity. The more water there is in the plant the easier it is for electric current to travel from one electrode to another. One electrode is connected to a pin on the Micro:bit. Another probe is connected to the 3-volt connector. The Micro:bit measures the current flowing from one probe to another. This is similar to an experiment you might have tried where the Micro:bit is used as a conductivity tester.

The Micro:bit is connected to a computer during the sensor information collection process. It needs to be connected so the program can collect and store the sensor information into a CSV file.

Project previews

Use the links below to get a copy of the project from Make Code or Github.

Micro:bit multi-sensor collector (Make Code): 
https://makecode.microbit.org/_UEMEd9Py248h

Micro:bit multi-sensor collector (Github): 
https://github.com/digitalmaestro/plantsensordata

The project

The programs will be developed using Microsoft Make Code. This is a free online IDE, Integrated Development Environment. Use the link below to access the online IDE. You don’t need an account to create projects.

https://makecode.microbit.org

Click the New Project button.

new project button

Use “plantSensorData” for the project name; click the Create button.

project name field

Every new project includes two code blocks on the coding workspace. These blocks include the [on start] section and [forever] loop.

The [on start] section is used to run code as soon as the Micro:bit starts or is restarted. This is where we usually define variables. We will use plenty of variables in our project.

The [forever] loop runs code for as long as the Micro:bit is powered. Code inside this loop does not require any user interaction. We won’t be using the [forever] loop in this project.

Get the [forever] code block and drag it to the Codes Section. Release the code block when a Trash Can icon appears.

forever block over trash icon

We are going to define three variables to hold the different sensor information. Go to the Variables section; click the Make a Variable button.

make a variable button

Use “lightSensorData” for the variable name; click the OK button.

variable name field

Three blocks are created for each variable. The first block is the variable itself. The Set block is used to assign values to the variable. The values can be numbers, letters, or operations. The Change code block is used to change variables with numbers with some regular amount.

variable code blocks

Click the Make a Variable button again. Use “tempSensorData” for next the variable name.

Another block for the variable is created. The other blocks are reused with the new variable name.

updated variable blocks

Click the Make a Variable once more; use “directionData” for the variable name.

three variable code blocks

The Micro:bit will collect the data from the sensors when we press one of the buttons. Go to the Input section; find the [on button A pressed] code block.

input code section

Place the code block on the workspace.

code block on workspace

Go to the Variables section. Get the Set variable code block.

set variable code block selected

Place the code block into the [on button A pressed] function.

set code block in place

Get another Set variable code block and place it into the button function.

second set variable code block

Click the variable selector for the set variable block we just added; select [tempSensorData].

variable selector

Place another Set variable code block into the button function. Change the variable to [lightSensorData].

third variable set code block

We are going to assign a sensor code block to each variable. This will assign the corresponding value from each sensor to the variable.

Go to the Input section; find the [compass heading] code block.

compass heading code block

Place the code block into the [directionData] assignment parameter.

compass heading code block added

Return to the Variable section; find the [temperature] code block.

temperature code block

Place the code block into the [tempSensorData] assignment parameter.

temperature code block added

Return to the Variable section; find the [light level] code block. Place the code block into the [lightSensorData] parameter.

light level code block added

The code is set to store the sensor information from each sensor. The information for each sensor is temporarily stored in the corresponding variable.

Collecting and recording the data

To record the data we need to send the data from the Micro:bit to the computer. The information is sent along the cable connecting the Micro:bit to the computer. This uses a standard called Serial communication.

Click the Advanced button to reveal more code sections.

advanced section button

Find the Serial code section.

serial codes section

Find the [serial write value] code block.

serial write value code block

Place the code block in the [on button A pressed]; place the code after all the other code blocks.

code added to button function

The serial write code block has two parameters. The parameter to the left of the equal sign is used to assign a label to the data placed in the parameter on the right.

Type “direction” into the label parameter.

value added to field

Get the [directionData] variable from the Variables section; place it into the right parameter.

variable added to value

This code block will send the compass heading sensor data to the computer. The data will be given the label “direction”. We will see this in the file later.

Right-click the serial write value code block; select the duplicate option.

duplicate option

Place the duplicate code block after the current serial write value code.

duplicate code inserted into button function

Click inside the label parameter; change the name to temperature.

label value updated

Click the variable name selector; choose [tempSensorData].

variable selector

Duplicate this serial write value code block; place it after the previous code block. Change the label to light. Choose [lightSensorData] from the variable selector.

third write value code with values

Compass setup

After pressing the button on the Micro:bit you might be prompted to orient the compass. A message will display across the Micro:bit to tilt the Micro:bit to fill the screen. A smiley face will appear when you have done this successfully.

Upload the code

Whenever we send information from one computer to another it is called uploading. Whenever we receive information from another computer, it is called downloading.

Connect the Micro:bit to your computer. Click the actions menu and select Download to Micro:bit.

download code option

There is a Micro:bit simulator on the left side of the workspace. We won’t be using the simulator. Press button A on the real Micro:bit. A button appears under the Micro:bit simulator. Click the “Show console device” button.

show console device button

Three scrolling graphs appear in the top part of the console section. The scrolling graphs are used to chart continuous data received from the sensor. Our program is collecting one set of data values at the moment we press the button. No data is plotted on the graphs because we only have one value. The one value collected appears in an orange pillbox.

direction value

The bottom of the console page displays all the values collected from each sensor. The values include the labels we assigned in the write value code block.

sensor values

Students will write these values in a table or open them in a spreadsheet.

The values are available in a CSV file. Click the download button to get a copy of the file.

download button

The CSV file

Opening the CSV file in a spreadsheet shows the data values under each of the corresponding labels. The file includes other columns of information. These labels refer to the time when the data was collected. Each time label is followed by the source label. The time label will always be zero for this program.

spreadsheet with sensor values

Water sensor data

This sensor configuration is optional.

Detecting the amount of water in a potted plant requires two alligator clips and two pieces of wire. The pieces of wire are the probes we stick into the soil. I like to use paperclips because they are found everywhere and a box of them is cheap. The probes don't have to be made from wires; they can be nails or screws.

One alligator clip connects to any available pin. These pins include pins 0, 1, and 2. The other alligator clip connects to the 3-volt connector. The other end of each alligator clip connects to one of the wire probes.

Create a variable; use “waterSensor” for the variable name. Place the Set variable code block into the button A pressed function.

set variable code block added

Find the Pins code section under the Advanced codes area.

pins code section

Find the [analogue read pin P0].

pin code block selected

Place the code into the variable assignment parameter for the water sensor.

analog read pin code added

Click the Pin selector; choose the connector where your alligator clip is connected. The options are P0, P1, or P2.

pin P1 selected

Make a copy of the serial write value code. Change the label to water and the variable to [waterSensor].

serial write value code with updated values

Download this code to the Micro:bit. Collect data from all the sensors.

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit remote sensor

This lesson requires two Micro:bit devices. One is used to collect sensor data from a source. The other is used to receive the data and store it onto a computer as a CSV, Comma Separated Value, file. This lesson demonstrates how we use code within a program to do a lot of tasks for us. Most of those tasks are math-related. This lesson will use math to calculate several variables.

micro:bit remote sensor transmit data from one micro:bit to another

Remote sensor and progress bar

The Micro:bit has a variety of sensors built into the device. It can interface with other sensors connected to contacts on the Micro:bit. This makes the Micro:bit a good tool for science investigations and data collection.

One Micro:bit connected to a computer and collecting data is a common way to gather sensor information. Another way is to pair it with another Micro:bit. In this way, one Micro:bit is used to gather data from a remote source and send the data to another Micro:bit connected to a computer. The data is sent through the Micro:bit Radio. The receiving Micro:bit is connected to a computer to collect data and store it for analysis.

The Micro:bit collecting data may usually be in a location that is not easily accessed or where it would be better not to disturb the data collection process. For example, the transmitting Micro:bit could be on the roof collecting temperature, light, or moisture data. The Micro:bit could be in a bucket of ice-water. It could be outside a window gathering temperature and moisture information. It could be in another classroom with one group of students using the Micro:bit to transmit data to another class.

The lesson objectives

This lesson requires two Micro:bit devices. One is used to collect sensor data from a source. The other is used to receive the data and store it onto a computer as a CSV, Comma Separated Value, file.

I want to take this lesson beyond the fundamentals and include other options. One of those options includes a progress bar. The progress bar is used to provide visual feedback on the device when it is working to collect and transmit data.

This lesson demonstrates how we use code within a program to do a lot of tasks for us. Most of those tasks are math-related. This lesson will use math to calculate several variables.

We are creating two programs. One is for the first Micro:bit to collect and transmit data. The other is for another Micro:bit to receive and save the data to a CSV file.

The project can be used to transmit data from any sensor on the Micro:bit. It can also be used to collect data from a sensor connected to the Micro:bit.

Project previews

Use the links below to see and get a copy of the finished projects. Use them as a resource to check your own finished project.

Micro:bit transmitter (Make Code):
https://makecode.microbit.org/_ViH5R3eX26X3
Micro:bit transmitter (Github):
https://github.com/digitalmaestro/microbitSensorTransmitter

Micro:bit receiver (Make Code):
https://makecode.microbit.org/_86P3iJidxf4w
Micro:bit receiver (Github):
https://github.com/digitalmaestro/microbitSensorReceiver

The project

The programs will be developed using Microsoft Make Code. This is a free online IDE, Integrated Development Environment. Use the link below to access the online IDE. You don’t need an account to create projects.

https://makecode.microbit.org

Click the New Project button.

new project button

Use “sensorTransmitter” for the project name; click the Create button.

project name field

Every new project includes two code blocks on the coding workspace. These blocks include the [on start] section and [forever] loop.

The [on start] section is used to run code as soon as the Micro:bit starts or is restarted. This is where we usually define variables. We will use plenty of variables in our project.

The [forever] loop runs code for as long as the Micro:bit is powered. Code inside this loop does not require any user interaction. We won’t be using the [forever] loop in this project.

Get the [forever] code block and drag it to the Codes Section. Release the code block when a Trash Can icon appears.

forever code block and trash icon

To transmit data we need to activate the Radio on the Micro:bit. Click on the Radio section; look for the [radio set group] code block.

Radio code section and code blocks

Place the code block into the [on start] section. The Radio set group is automatically set to group 1. We can use any group number from 0 to 255. Group one is a good place to start. The same radio group number must be used on both the transmitting and receiving Micro:bit.

radio set group code block

We need to gather data from one of the sensors. We’ll use the temperature sensor for this example. We will create a variable to store the value from the sensor reading.

Go to the variables section; click the “make a variable” button.

make a variable button

Use “celsiusTemperature” for the variable name; click the OK button.

variable name field

Three code blocks are created for each variable. The first is the variable itself. The second is used to set, or assign, a value to the variable. The third is used to change the value of the variable by some numerical increment.

variable code blocks

Go to the Input section; find the [on button A pressed] code block.

Input code section

Place the code block on the canvas.

code block on workspace

Get the [set celsiusTemperature] variable; place it into the [on button A pressed] code.

set code block for variable

Go to the Input code section; find the [temperature] code.

temperature code block

Place the [temperature] code into the [set celsiusTemperature] code parameter.

temperature code block added

When we press button A, the code will query the temperature sensor and store the value into the [celsiusTemperature] variable.

After getting the temperature from the sensor, we need to transmit that information to the receiving Micro:bit. Go to the Radio code section; find the [radio send value] code.

radio send value code block

Place the code block into the [on button A pressed] code and after the variable code. Code is processed in the order it is created. We need to get the temperature value before sending it to the receiving Micro:bit.

code block added

The send value code block has two parameters. The first parameter is used to provide a name to the numeric data in the second parameter. Type “Celsius” into the value name parameter.

value name added to field

Get the [celsiusTemperature] variable from the variables section; place it into the second parameter for the radio send code.

variable added to code block

The code will get the temperature data and transmit it to the other Micro:bit each time button A is pressed.

Multiple readings with loops

We want to automate the process so the Micro:bit collects multiple readings from the sensor and transmits each.

Go to the Loop section; find the Repeat loop.

Loops code section selected and repeat loop

Move the loop over the [on button A pressed] code. Look at the code shadow and make sure the other code blocks pop inside the loop.

adding repeat code block

The Repeat loop is set to repeat the code in the loop 4 times. Each loop represents a reading from the sensor and a value sent to the receiving Micro:bit.

code blocks in repeat loop

We are going to need to gather many more data values over some time. We need a variable to store the number of readings we want to collect. Go to the Variables section. Click the "make a variable" button.

make a variable button

Use “readings“ for the variable name; click the OK button.

variable name field

Get the [set readings to] code; place it into the [on start] section.

code block added to on start

Enter thirty into the assignment parameter for the variable. In this example, we are going to collect thirty readings from the temperature sensor.

variable value updated

Get the [readings] variable; place it into the loop parameter.

variable added to repeat loop parameter

The number of values we want is assigned to the readings variable when the Micro:bit starts. That value is passed into the loop and ready for when we press button A.

pointing to variables and value

The Micro:bit is fast and it processes instructions almost instantly. It will process all the sensor readings in less than a second. We need to slow the process to collect readings from the sensor over some time.

Go to the Basic code section; find the [pause] code.

pause code block

Place the [pause] code at the end of the code in the loop.

pause code block added

The time intervals are measured in milliseconds.

Click the time selector in the [pause] code. We can choose a time interval from 100 milliseconds to five seconds, which is 5000 milliseconds.

pause interval selector

We usually don’t think in terms of milliseconds or even seconds for the most part. We think in terms of minutes or hours. To convert minutes to milliseconds we multiply the number of minutes by 60,000. One minute is 60,000 milliseconds. Five minutes is 300,000 milliseconds. Simple enough, but when we have a computer we can have it do all the work.

Minutes to milliseconds

We will add code to convert the number of minutes we want into milliseconds.

Go to the Variables section. Create a variable and use “minutes” for the name. Create another variable and use “pauseTime” for the name.

created variable blocks

Get a set variable code block; place it into the [on start] section. The set code block uses the variable name of the most recently created variable. Mine is set to “pauseTime”.

set code block added

Click the variable name selector; choose “minutes”.

variable selector with minutes selected

Place another set variable code block into the [on start] section. Select “pauseTime” for the variable.

updated set code block

The pause time variable will calculate the milliseconds for us.

Go to the Math section; find the multiplication operation.

multiplication code block selected

Place the multiplication operation into the set “pauseTime” parameter.

multiplication code block added

Place the [minutes] variable into the left side of the multiplication operation.

variable code block added

Enter 60000 into the right side of the multiplication operation.

value added to field

Type the number 1 into the minute's assignment parameter.

value added to variable assignment

Place the [pauseTime] variable into the [pause] parameter.

variable added to pause code block

The loop will pause one minute between readings. With 30 values to gather, it will take half an hour to take all the sensor readings.

To take the same amount of readings in less time we need to calculate the interval between readings. What pause interval do we need to take 30 readings in 20 minutes? We can divide 20 by 30 to give the interval in fractions of a minute. In this example that would be 2/3 or .6667. A reading is taken every 2/3s of a minute.

We don't have to calculate this ourselves. The Micro:bit will work out the math and calculate the correct pause time. It will calculate this time based on the readings we want and the total period.

Go to the Variables section. Create a new variable; use “totalTime” for the variable name.

Place a [set totalTime to] code block in the [on start] section.

set variable code added

We need to reassign the value in the set code we added earlier. The set code that calculates the pause time contains the math to calculate the total time in milliseconds. Click the variable selector and choose totalTime.

variable selector

Select [pauseTime] in the set variable code block we just added.

variable selector

To calculate the pause time we need to divide the total time by the number of readings. We know to divide time by readings because we want to know the pause time per reading or between readings.

Go to the Math section; find the division operation.

division operation code block

Place the operation into the [set pauseTime to] parameter.

operation added to code

Get the [totalTime] variable; place it on the left side of the division operation. Get the [readings] variable; place it on the right side of the division operation.

variable code blocks added

With these instructions programmed, all we need to do is decide on the number of readings and the period for those readings. The program will calculate the regular time interval between each reading.

Sensor countdown

The sensor will start taking readings as soon as button A is pressed. I like to give myself some time to press the button and place the Micro:bit into the environment to begin taking readings. I like to add a countdown timer.

Go to the Loop section; get a Repeat code block. Place the code block in the [on button A pressed] code and before the current loop.

repeat loop being added

We need a container to hold the countdown numbers. Create a variable and use “countDown” for the name. Place the [set countDown to] code into the [on start] section. Assign the variable a value of 5.

set variable value updated

Type the number five into the Repeat loop parameter.

repeat value updated

Get the [show number] code block from the Basic section. Place the code block into the Repeat loop.

show number code block added

Get the [countDown] variable; place it into the [show number] parameter.

variable added to show number

Get the [change countDown by] code block; place it after the [show number] code. Change the parameter value from 1 to a negative one(-1).

change variable updated

Get a [pause] block; place it after the change variable code. Set the pause duration to one second.

one second selected

Get the [clear screen] code block from the Basic section; place it after the [pause] code.

clear screen code added

Identify the transmitter

The send code for the first Micro:bit is complete. All Micro:bits look about the same. We need a way to identify this Micro:bit from the receiving Micro:bit.

Place a [show string] code block in the [on start] section.

show string code block

Enter the letter “T” for the string assignment. This will display the letter “T” until we press the button to begin the data collection.

updated string value

Progress bar

It’s comforting to see something happening on the Micro:bit to know everything is working. I like to include a basic progress meter.

Go to the LED section; find the [plot bar graph of] code.

LED code section

Place the code after the [radio send value] code.

plot bar graph code added

We need a container to hold the value for the plot. Create a variable; use "sensorData" for the name. Place the [set sensorData to] code into the [on start] section.

set code block added

Place the [readings] variable into the [sensorData] assignment parameter. The number of sensor data readings is the same number of readings.

variable added to code

Place the [sensorData] variable into the first parameter for the plot data graph code. Place the [readings] variable into the second parameter.

variables added to plot graph code

Get a [change sensorData by] code block; place the code after the plot bar graph code. Change the value from one to a negative one(-1).

code block value updated

Test the code

Change the minute assignment value to 1-minute.

minutes value updated

Click the button. The Micro:bit simulator will begin with a five-second countdown. The display will fill with light LEDs.

button pressed and bar graph plotted

Rows of LEDs will turn off as the data is sent. The count down we created with the sensor data variable is reduced by one each time a value is sent. This is what the graph is plotting.

bar graph changing

A progress meter that gets smaller over time is different from your typical progress bar. We can reverse the operation and have the bar grow over time. We are going to use Math to do this!

Remove the [sensorData] variable and set it to one side for a moment.

removing variable code block

Go to the Math section; get the Subtraction operation code. Place the code into the plot bar graph parameter.

subtraction operation code added

Place the [sensorData] variable on the right side of the subtraction operation.

variable returned to code

Get a [readings] variable; place it on the left side of the subtraction operation.

variable added to code

Press button A to run the program. The bar graph will plot the values going up instead of down.

Change the time to a value that represents the time for the readings you want to collect. Set the number of readings you want to collect during that time.

Download the code to the first Micro:bit.

Receiving Micro:bit

This is the easiest part of the code. The receiving Micro:bit’s job is to receive the data and compile it into a CSV file.

Click the Home button to return to the Make Code for Micro:bit home page.

Home icon

Click the Create New Project button; set the name of the new project to “sensorReceiver”.

project name field

Get rid of the [forever] loop.

removing forever code block

Go to the Radio section; get the [radio set group] code and place it on the [on start] section. Make sure the radio group number is the same as that used by the transmitting Micro:bit.

radio set group code block added

Get the [on radio received name value] code from the Radio section. Place the code on the workspace.

code block added to workspace

Open the Advanced code section; find the Serial codes section.

serial code section selected

Look for the [serial write value] code block.

serial write code block selected

Place the code block into the [on radio received] code.

code block added

The radio received code block contains the information received from the transmitting Micro:bit. This information is stored inside two variables created by the code block. The variables are “name” and “value”

Click the “name” variable and drag it to the parameter on the left side of the equal sign.

variable name being added

Drag the “value” variable onto the parameter on the right side of the equal sign.

variable name being added

variable name being added

This code will collect the data values sent by the other Micro:bit and create a file with the values. The “name” variable represents the title we provided for the temperature, Celsius. The “value” variable contains the temperature values collected from the sensor.

code with variables added

The receiving Micro:bit needs to be connected to the computer while collecting data from the sending Micro:bit. You also need to be on the Make Code IDE site. The site facilitates the collection and compilation of the data into a CSV file.

Download the program to the receiving Micro:bit before pressing the button on the sending Micro:bit.

Plug the other Micro:bit to a power source and press the button. You might need to use a battery in some situations.

A “Show console Device” button appears once the receiving Micro:bit receives the first value. Click the button to watch the data as it is received.

show console button

The data received is displayed in the bottom section of the console.

Important: Don’t leave the console page or click on anything else while collecting data. This will interrupt the collection process. You will have to start over if this happens. Press the Restart button on the back of the Micro:bits to start over.

temperature reading displayed

Click the Download button to save the CSV file to your computer when the process is complete.

download file button

End notes

The Radio signal from the Micro:bit is not very strong. Lots of things can interfere with the signal. This limits the distance you can be from each Micro:bit to send and receive data. You will need to test for the maximum distance in your environment.

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit timer

In this lesson, we are going to work on a countdown timer. The timer will count down in seconds, but it can be used for minutes too. We will develop an interface to set the timer value with the A and B buttons. The shake option will be used to reset the timer. We will include a countdown tone.

Micro:bit countdown timer

Timer

In this lesson, we are going to work on a countdown timer. The timer will count down in seconds, but it can be used for minutes too. We will develop an interface to set the timer value with the A and B buttons. The shake option will be used to reset the timer. We will include a countdown tone.

The code for the finished project is available from Make Code and my Github repository; use the links below.

Make Code: https://makecode.microbit.org/_8zzFXgfdg2VM

Github: https://github.com/digitalmaestro/timer

Micro:bit simulator and Make Code

You don’t need a Micro:bit to follow along in the lesson. Make Code offers an Integrated Development Environment, IDE, for the Micro:bit. The IDE includes a Micro:bit simulator. Use the link below to access the Make Code website. You don’t need a login account.

https://makdecode.microbit.org

Click the New Project button.

new project button

Use “timer” for the project name; click the Create button.

project name field

Every new Make Block Micro:bit project includes two code blocks. The [on start] code is used to run code the moment the Micro:bit is connected to a power source or restarted. The [forever] code is part of a function. Code in [forever] is part of a loop that repeats as long as the Micro:bit is connected to a power source.

We don’t need the [forever] function for our project. Take the code block and drag it to the Codes section. Release the block when a Trash Can icon appears.

removing forever loop code block

Basic intervals

We are going to create the timer so that pressing the A and B buttons will allow us to set the timer value. Go to the Input section; find the [on button A pressed] function.

code block selected

Place the code block on the coding canvas.

code block placed on canvas

We need some variables to store the timer values. Select the Variables section; click the “Make a Variable” button.

make a variable button

Use “intervalOne” for the variable name; click the OK button.

variable name field

Three code blocks are available for every variable we create.

different variable blocks available

Get the [change intervalOne by 1] code block; place it in the [on button A pressed] function.

code block added to button code

Go to the Basic code section; find the [show number] code.

show number code block selected

Place the [show number] code into the [on button A pressed] function and below the variable block.

code added

Select the Variables section. Get the [intervalOne] variable; place it into the [show number] parameter.

variable added to show number parameter

This is the basic code for increasing the timer by one unit at a time.

Go to the Simulator section and press the A-button a few times. The value should increase by one each time the button is pressed.

number four shown on display

Let’s set up the other button to increase the timer value by 5 at a time. This will save us button presses when we need to set a timer for 10, 15, or more. We will combine this with the A-button to give us other timer values.

Intervals by five

Go to the Input section; get another [on button A pressed] code. Place the code on the coding canvas. The function is faint and a different color. This happens when two button functions are on the canvas for the same button.

code block on canvas

Click the button selector; choose button B.

button B selected

Go to the Variables section; click the “Make a Variable” button. Use “intervalTwo” for the variable name.

make a variable button

Get the [change interval… to ] code block and place it into the [on button B pressed].

code added to B button block

Click the variable sector. Choose the [intervalTwo] variable if it is not already selected.

intervalTwo variable selected

Change the variable interval from one to five.

value updated

Get the [show number] code block from the Basic section; place it after the change variable code.

show number code added

Place the [intervalTwo] variable into the [show number] parameter.

variable added to code

Go to the simulator and press the B-button a few times. The numbers on the display should increase five at a time.

value on display

Combining values

The values generated by the A and B buttons are working independently. We need to store the values generated from each button and add them together. We need another variable.

Go to the Variables section; create a new variable. Use “totalTime” for the variable name. Get the [set totalTime to] code block; place it after the [change intervalOne by] code block in the [on button A pressed] code.

set code added

The [totalTime] variable will store the sum of the intervals selected using both the A and B buttons.

Go to the Math code section; find the Addition operation.

addition code block

Place the Addition operation into the [set totalTime to] parameter.

code added

Go to the Variables section. Get the [intervalOne] code; place it on the left side of the Addition operation.

variable added

Get the [intervalTwo] code; place it on the right side of the Addition operation.

variable added to code

Use the variable selector in the [show number] code; choose the [totalTime] variable.

variable selected

Go to the simulator; press button B once. Press button A two or three times. The values from buttons B and A are added and displayed.

value displayed on Micro:bit

Functions

We need the same cone for button B. Whenever we have code that repeats it is standard to create a Function for that code. The function of our code is to add the value of the buttons pressed for a total timer value.

Select the Advanced code option; select the Functions code section.

Functions code section selected

Click the “Make a Function” button.

make a function button

Click inside the function name.

function name selected

Use “timerTotal” for the function name; click the Done button.

function name

The function is placed on the canvas with the rest of our code.

function on coding canvas

Select the [set totalTime to] code and pull it away from the button function. The [show number] code will be moved too.

code being moved

Place the code blocks into the [timerTotal] function.

code placed in function

We call the function from the button-pressed code. Select the Function code section; look for the [call timerTotal] code block.

call functions in function section

Place the code into the [on button A pressed] and after the [change intervalOne by 1] code.

call function added

Get rid of the [show number] code from the [on button B pressed] function.

code being removed

Insert the [call timerTotal] function into the [on button B pressed] code.

call code added

Checking the function

Go to the simulator and press both the A and B buttons. The value on the display will update with the total.

Start the countdown

Once we have the total time for the countdown, we need to begin the countdown. The countdown will be started by pressing both buttons.

Go to the Input section; get an [on button A pressed] code block and place it on the canvas. Use the buttons selector and choose A+B.

button code on canvas

Pressing the A and B buttons will begin the countdown process. The countdown uses a loop. There are several ways to use loops. In this program, we want the loop to continue the countdown as long as the countdown value is greater than zero.

Go to the Loops section; find the [while True do] loop.

loop section

Place the loop inside the A+B button code.

while loop in button code

The While loop repeats everything inside the loop while some condition is True or False. In this project, we want the loop to continue as long as the countdown timer is greater than zero. This is a True condition.

To evaluate if something is True, we need a comparison code block. Go to the Logic section; find the Less-then code block.

less than code selected

Place the code block into the While loop parameter.

comparison code in loop parameter

Click the comparator selector; choose the Greater-than option.

greater than comparison selected

Place the [totalTime] variable into the left side of the comparator.

variable added to comparison code

Place the [show number] code block inside the While loop. Get the [totalTime] variable and place it into the [show number] parameter.

show number code added

Get the [pause] code from the Basic section; connect it to the [show number] code in the loop. Change the pause duration to 1-second.

pause code and time interval selector

Get the [change totalTime by] variable block; connect it to the [pause] code. Change the value from a positive one to a negative one.

change value updated

Test the timer

Go to the simulator; press button B once and button A twice. This creates a seven-second timer.

value displayed on Micro:bit

Click the A+B button. The timer counts down and stops at number one.

value on Micro:bit display

This happens because the loop is instructed to repeat the process as long as the [timerTotal] is greater than zero. Change the comparison operation; select Greater-than or Equal-to.

comparison selected

Set a timer value of your choosing: click the A+B buttons. The timer will countdown and stop at zero.

zero displayed

Set the startup variable values

It’s a good idea to include a way to reset the value without pressing the reset button on the back of the Micro:bit.

Before creating the reset code, we need to set the start-up values for all the variables. Setting the initial values for variables at the beginning is always a good idea.

Go to the Variables section. Place a [set variable to] code block into the [on start] section for each variable. Leave the value assigned for each at zero.

set variables added

Place a [show number] code block after the set variables code blocks. Place the [totalTime] variable into the [show number] parameter. Place a [pause] code block after the [show number] code; set the pause duration to 500ms. Place a [clear] screen code block after the [pause] code.

other code blocks added

This is the same code we are going to use when resetting the timer. We are going to reuse code; this is an indicator that we need a function.

Reset function

Go to the Functions section; click the Make a Function button.

make a function button

User “clearTimer” for the function name; click the done button.

function name

Get all the code blocks from the [on start] section; place them into the [clearTimer] function.

code being moved to function

Click the chevron next to the function name. This collapses the function. The function works in the same way, but all the code is neatly tucked away inside.

function code collapsed

Get the [call clearTimer] code; place it into the [on start] section.

call code added

Reset on shake

Go to the Input section; find the [on Shake] code block.

on shake code

Place the [on shake] code block on the coding canvas. Get a [call clearTimer] block and place it into the [on shake] code.

call code added to on shake

Test the shake function

Press the B-button three or four times; click the Shake button.

shake button option on simulator

Recall timer value

When using the timer we may want to check the value one more time. The timer value has disappeared from the screen. We need a way to recall the information. The problem is that we have run out of buttons on the Micro:bit. Micro:bit version 2 uses the logo as a contact button. The contact button in version 2 is like the contacts at the bottom of the other Micro:bits. We will use contact number 2 as a contact button.

pin two on Micro:bit

Go to the Input section; find the [on pin 0 pressed] function. Place the function on the coding canvas.

on pin code

Click the pin selector; choose pin P2.

pin 2 selected

We don’t need to create any code to display the timer value. We already created that code and put it in the [timerTotal] function.

code in timerTotal function

Place the [call timerTotal] code into the [on pin P2 pressed] function.

call code added

Set a value in the Micro:bit simulator.

value displayed

Click the P2 contact. It works as a button now.

pin two clicked

The contact will change color to show it has been clicked. The value will scroll across the display.

value displayed on Micro:bit

Sound

Version 1.3B and 1.5 of the Micro:bit don't include a speaker. To use sound with these Micro:bit versions, you will need to connect a small speaker.

You can use a larger speaker if you don’t have small speakers. The Micro:bit does not put out enough current to power large speakers. The speakers need to be powered by an external source. There are plenty of portable speakers available on the market. The speakers need an input jack for connecting a 3.5mm stereo cable. These cables have three sections. The sections are separated by a plastic ring. You will need to connect the alligator clips to the first and third sections of the plug. The Micro:bit simulator shows how to connect the clips.

Go to the Music section; find the [play tone Middle C for 1 beat] code block.

tones code section

Place the code block into the [on button A+B pressed] function. Place the code block after the [show number totalTime] code.

play tone code added

Change the beat from a Whole note to a Quarter note.

quarter note selected

Click in the Tone parameter; select Middle-A using the virtual keyboard.

middle A note selected

The Micro:bit simulator shows how to connect the audio cable with alligator clips.

audio plug connection in simulator

Use the simulator to set a timer and test the code using sound.

Download the code to the Micro:bit and start using the timer.

Seconds to minutes

The timer counts down the value we choose in seconds. We may want to use minutes instead of seconds. The Pause code uses milliseconds. One thousand milliseconds is one-second. Sixty-thousand milliseconds is one minute. Enter this value into the [pause] code.

updated pause value
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit temperature sensor data collection

In this lesson, we are going to transfer data from the Micro:bit temperature sensor directly to our computer. This is a good introduction for the collection of data from Micro:bit sensors. The Micro:bit will collect sensor data. The data will be saved to a CSV, Comma Separated Value, file. The CSV file can be imported into any spreadsheet program. We will import the file into a Google Sheet and create a line chart.

Micro:bit sensor data collection

Sensor data

The Micro:bit has a variety of sensors. They are an excellent way to collect data for science investigations. I like the temperature sensor. It provides immediate feedback for something that students can readily relate to. The temperature sensor is a good way to investigate a variety of science concepts.

In this lesson, we are going to transfer data from the Micro:bit temperature sensor directly to our computer. This is a good introduction for the collection of data from Micro:bit sensors. The Micro:bit will collect sensor data. The data will be saved to a CSV, Comma Separated Value, file. The CSV file can be imported into any spreadsheet program. We will import the file into a Google Sheet and create a line chart.

Use the links below to get a copy of the project.

Make Code: https://makecode.microbit.org/_fkxHWh6LWbYg
Github: https://github.com/digitalmaestro/temperature-sensor-data

Micro:bit simulator and Make Code

Make Code offers an Integrated Development Environment, IDE, for the Micro:bit. The IDE includes a Micro:bit simulator. Use the link below to access the Make Code website. You don’t need a login account.

https://makdecode.microbit.org

Click the New Project button.

make block new project button

Use “temperature sensor data” for the project name; click the Create button.

project name field

Go to the Input code section; get the [on button A pressed] code and place it on the coding canvas.

code block selected

Go to the Variables section; click the "Make a variable" button.

make a variable button

Use “celsius” for the variable name; click the OK button.

variable name box

Three code blocks are available for every variable. The first is the variable itself. The others include the set variable code block. This assigns a value to the variable. The other is the change variable code block. This code increments the value of a variable by a value of our choosing. This block is often used in counting and loops.

variable code blocks

Get the [set celsius to] code block; place it in the [on button A pressed] function.

set variable code block in button function

Go to the Input code section; find the [temperature] code block.

temperature input code block selected

Place the code block into the [celsius] assignment parameter.

temperature code block in variable assignment

Go to the Basic code section; find the [pause] code block.

pause code block

Place the [pause] code block below the [set celsius to] code.

pause code block connected

Use the time selector; select 1-second.

pause time selector menu

Click the Advanced menu to display the advanced code blocks.

advanced menu option

Select the Serial code section.

serial code section

Find the [serial write value] code block.

serial write value code selected

Place the code block before the [pause] code.

code block connected

Type "celsius" in the value description field.

value in name field

Go to the Variables section. Get the [celsius] variable; place it into the [serial write value] field.

variable in serial write parameter

This code will set the temperature sensor information and save it to the [celsius] variable. The value in the variable will be passed into the [serial write value] code. The serial write value code writes the values into a CSV file, which we will save later.

The code includes a one-second delay. We will use this delay later to collect sensor readings.

Go to the simulator area; press the A-button.

Micro:bit simulator

A simulated temperature meter appears on the Micro:bit. This represents fake temperature data.

button and temperature simulation

A “Show console Simulator” button appears below the Micro:bit simulator; click the button.

show console simulator button

The simulator includes a scrolling graph of the data collected by the sensor. The simulated sensor has collected one reading so there is no chart to create.

scrolling graph area

The values recorded by the program are shown in the section below.

sensor data in data field

Click the “Go back” button to return to the coding environment.

back button

Device sensor information

We want to collect information from the real Micro:bit sensor. Connect your Micro:bit to the computer.

For the next step, I'm going to assume you have not paired your Micro:bit to the computer.

Click the more menu option; the three dots. Select the Pair device option.

actions menu options

Click “Pair device” when the instruction box opens.

pair device button

Your browser might ask you to select the device to pair. Select the Micro:bit device and click the Connect button.

Micro:bit connected information

Click the More Actions button; select “Download to micro:bit”.

download to Micro:bit option

Don’t disconnect your Micro:bit from the computer. Click the A-button on the real Micro:bit.

A “Show console Device” button appears below the Micro:bit simulator; Click the button.

show console device button

We have collected only one value, so the graph doesn’t show anything of interest.

scrolling graph area

The data area shows the first value collected by the Micro:bit. The temperature collected by my Micro:bit sensor is 27-degrees celsius.

data area

Press the button on the Micro:bit a few times. Place the Micro:bit in your hand or on objects with different temperatures. Press the button each time to get a new temperature reading.

My Micro:bit recorded eight sensor readings. Five readings measured 27-degrees, two readings measured 28-degrees, and one measured 29.

different temperature readings collected

The scrolling graph displays the changes in sensor readings over time.

scrolling graph area with line

Click the “Go back” button.

Collect multiple readings

Pressing the button to get a temperature reading is fine, but it is not the best way to get continuous readings from a single source. We are going to add some code so the sensor will get temperature readings at regular intervals.

Get the [repeat times] loop from the Loops section.

loops section selected

Move the loop into the [on button A pressed] function. Make sure the loop surrounds and incloses the existing code.

loop over code blocks

Change the repeat parameter from 4 to 60.

repeat value updated

The [pause] code we added earlier is set to one second. Readings will be taken from the temperature every second. The program will do this 60 times. That gives us one minute's worth of temperature data.

Click the actions menu and download the program to the Micro:bit.

download to Micro:bit option

Press the A-button on the Micro:bit. Click the Show console Device button.

show console device button

Temperature readings from the sensor will begin to be recorded. My Micro:bit is on my desk and reading the same temperature for every reading. It will stop taking readings when the number in the loop parameter is reached.

data section with sensor values

Ice water temperature

This is a simple way to test the program and collect data.

CAUTION!

PERFORM THIS PART OF THE LESSON ONLY IF YOU HAVE A WATER-TIGHT BAG FOR THE Micro:bit.

Get a bowl of water and add ice. Place the Micro:bit into a water-tight bag. I use a water-tight bag for cell phones. The bag is rated IPX8. This means the bag can be dropped into the water and the bag will not let water in for some time.

Micro:bit in water tight pouch

Press the A-button on the Micro:bit and submerge it into the ice water. I could not close the bag because of the cable so I held the top of the bag while the Micro:bit was in the ice water.

Micro:bit in water-tight pouch submerged in ice water

Click the Show console Device button. Watch as the sensor data is collected and displayed. The numbers in the grey represent the number of readings at that temperature. Each temperature has several identical readings. This is because we are taking one reading every second.

temperature data values

Watch the scrolling graph. The data collection is complete when the graph stops displaying the collection of data.

scrolling chart area

The data has been collected and temporarily stored in a text file. We need to download this file before anything else. Click the blue arrow to download the CSV file.

download CSV file button

More temperature data

Taking a temperature reading every one-second might have been too much. Return to the code; change the pause duration from one to two seconds.

time interval selector

Click the actions menu and download the updated code to the Micro:bit. We always need to download any changes to the Micro:bit.

download code button

Repeating the experiment

Take the Micro:bit out of the ice water and pouch between measurements. Leave the Micro:bit out for about 5 minutes. This will give the Micro:bit some time to warm up to room temperature. Place the Micro:bit into the pouch after five minutes, press the button, and insert the Micro:bit into the ice water.

The process will take about two-minutes this time. Watch the graph being plotted and the data being collected. Download the CSV file when the process is complete.

Repeat the process one more time. Return to the code and change the pause duration to five-seconds. Download the updated code to the Micro:bit. Insert the Micro:bit into the ice water and collect the data. The process takes five minutes this time.

Note that we are taking the same number of readings. The only thing that is changing is the duration between readings. How does the duration relate to the data retrieved from the Micro:bit?

Importing data to Google Sheets

By now you should have at least two CSV files with temperature data. Open a new tab in your browser and create a new Google Sheet. The link below will take you to Google Sheets and create a new sheet. You will still need to log in with your account.

https://sheets.google.com/create

Click the sheet name; rename it to Micro:bit temperature data.

updated sheet name

Click File and select Import.

import option

Select the Upload option.

upload file option

Click the “Select a file from your device” button.

select file button

Select the first CSV file; click the Open button.

CSV file selected

An import configuration box opens. Select the option to replace the Sheet.

replace current sheet option selected

Leave the other options set to detect the separator type automatically and convert the information automatically. Click the Import Data button.

delimiter and formatting options

The data includes some heading information. Erase the contents of the first cell, cell A1. Change the title for the time to "Time(seconds)". Update the title for celsius. Have it begin with a capital letter.

The first data value was taken at the moment we pressed the button. It was taken at zero seconds. We don’t need this data value. Select the cells and delete the information.

values selected

Select the cells with the data collected; include the headings.

data and headings selected

Click the insert a chart button.

insert chart button

You should get a basic line chart.

basic line chart

Import more data

We will use the same sheet to import other data values.

Deselect the cells; click File and select Import.

import option

Choose the Upload option and select the next CSV file. Choose the Insert new sheet(s) option from the import file configuration box. Click the Import data button.

insert new sheet option

Double click the sheet name; use “2 seconds” for the sheet name.

updated sheet name

Cleanup the heading information like we did with the other import. Create a chart with the new data.

Repeat the process if you collected data from the sensor using five-seconds for the pause duration.

Use the link below to get a copy of the data I collected and uploaded to Google sheets. The first link gives you a preview. The second link will allow you to save a copy of the sheet to your Google Drive.

Preview the Sheet

Get a copy of the Sheet

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit progress bar for data collection projects

This lesson creates codes for a progress bar. Progress bars are a good way to get feedback during an operation. The Micro:bit has a variety of sensors. Those sensors are an excellent way to collect data for science investigations. The collection of data can take some time. The duration can be a few minutes or more. During that time we don’t have visual clues to provide feedback on the data collection progress. This is where a progress bar is something useful to include in a project.

Micro:bit progress bar for projects

Micro:bit progress bar

The Micro:bit has a variety of sensors. Those sensors are an excellent way to collect data for science investigations. The collection of data can take some time. The duration can be a few minutes or more. During that time we don’t have visual clues to provide feedback on the data collection progress.

This is where I decided it would be a good idea to include a progress bar when a Micro:bit is tasked with collecting data. The data can be like a vessel that is filled with a specific amount of information. For example, we might want to collect several measurements as they are coming in from the accelerometer. In another example, we might want to collect the ambient temperature in a room over some time.

The code for this progress bar can be used in a variety of projects. I have a couple of projects in the works where the progress bar will be part of the project.

Programmers often keep libraries of code they can use in a variety of projects or applications. This code will be one of our library resources for use in future projects.

In the lesson, you will learn how to use variables to keep track of information. If you are an educator, you will have the opportunity to demonstrate how math proves to be a useful tool in coding. The project uses basic division, addition, and multiplication. The project refers to the coordinate plane. The coordinate plane is a little different from that used in traditional math, but it does use the same x and y-axis properties.

Use the links below to get a copy of the finished project and the basic progress bar project.

My progress bar(Make Code): https://makecode.microbit.org/_APVgej8KFfW5
My progress bar(Github): https://github.com/digitalmaestro/my-progress-bar

Basic progress bar(Make Code): https://makecode.microbit.org/_8AP8P5546E2i
Basic progress bar(Github): https://github.com/digitalmaestro/a-basic-progress-bar

Micro:bit simulator and Make Code

You don’t need a Micro:bit to follow along in this project. Make Code offers an Integrated Development Environment, IDE, for the Micro:bit. The IDE includes a Micro:bit simulator. Use the link below to access the Make Code website.

https://makdecode.microbit.org

Click the “New Project” button.

make block new project button

Use “My Progress Bar” for the project name; click the Create button.

project name

A progress bar is based on the measurable completion of a process. The measurement is taken as either a counter toward the completion or as a percentage of the complete process. We are going to use a simple counter to generate the progress bar.

In a project, we are likely to collect a specific number of values from a sensor over a given period. In this example, we are going to use the temperature sensor to collect data. We are going to query the sensor every two minutes. The period can be longer or shorter. The progress bar works the same regardless of the number of values collected.

The Micro:bit has five LEDs across and five down. The five LEDs across will be used to represent the progress bar. The progress bar will light up across the middle of the Micro:bit. The number of values we decide to collect needs to be divided into equal units represented by each of the five LEDs. We can take care of this with a simple division.

To understand how this progress bar works, let's take a look at some examples. We want to take 30 temperature measurements over some time. The time does not matter in this example. We need five markers in those thirty measurements to use for the progress bar. Thirty divided by five is six. An LED will light along the progress bar every time we reach a count that is divisible by six.

While counting we need to compare the count to a marker divisible by six. The table below shows six multiplied by one; then multiplied by two; then three; four; and finally five. The answers for each represent a value we will use to activate one of the LEDs. The first LED will light when the counter reaches six. The second LED will light when the counter reaches 12. The process continues until the counter reaches 30.

number table

The same holds if we choose a different number of sensor readings. In this next example, we are collecting 80 readings. The table shows the divisions and values for each division. Eighty divided by five is sixteen. This number is multiplied by five, then four to one in the table.

number table

The values are different for each number. The difference is not an issue. We are using an algorithm to activate each LED regardless of the value.

The difference between each stage increases as the number of values collected increases. This will trigger each LED to be light for a long time before the next lights. We will take care of this by instructing each LED to blink while data is being collected during each stage.

Go to the Variables section; click the “Make a variable” button.

make a variable button

Use “totalCount” for the variable name; click the OK button.

variable name

Make another variable; use “unit” for the variable name.

variable blocks

Three code blocks are created for each variable. The first is the variable block itself. The other variables set the value of a variable and change the variable by some value.

Place the [set variable to] code block into the [on start] section.

set variable block

Place another [set variable to] code into the [on start] section. Click the variable selector for the first code block and choose the [totalCount] variable. Make sure the second is set to the [unit] variable.

change variable name option

The [totalCount] variable represents the number of values we want to collect from the temperature sensor. Enter 30 in the variable assignment parameter.

variables in on start section

The [unit] variable will hold the value when we divide five into the total number of measurements we want to collect. In math, this is referred to as the Quotient. The quotient is part of the pattern of numbers used in the progress bar.

Go to the Math section; find the division operation.

division operation code

Place the division operation into the [unit] variable parameter.

division operator

Get the [totalCount] variable; place it into the left side of the division operator.

total count variable in division operation

Enter the number five into the right side of the operator.

value in operation

We need another variable. This variable will be used as the container to keep track of the count.

Go to the Variables section; create a new variable. Use “counter” for the variable name. Place the [set counter to] code into the [on start] section.

counter variable

Go to the Input section; get the [on button A pressed] code and place it on the coding canvas.

on button pressed input code

We are using a loop to keep track of the readings and values collected. The loop will generate a progress bar as long as the counter is less-than or equal-to the total number of values we want to collect. The number of values is 30 in our current example.

Go to the Loops section; get the [while True do] loop and place it into the [on button A pressed] function.

while do loop code

The [while True do] loop will process the contents of the loop while a condition is True. Our condition will be that the counter is less-than or equal-to the [totalCount] value.

Go to the Logic section; get the less-than comparison code block.

less-than operation

Place the comparison block into the loop parameter.

comparator in parameter

Click the comparator selector; choose less-than or equal-to.

less-than or equal-to option

Get the [totalCount] variable and place it on the right side of the comparison code.

variable in equality operator

Get the [counter] variable and place it on the left side of the comparison code.

counter variable

The loop will process the code inside the loop as long as the counter is less-than or equal-to the total count. The total number of readings we want to get from the temperature sensor.

Place the [change counter by 1] variable block into the loop. This adds one to the counter each time the loop cycles.

change counter variable

Go to the Logic section; find the [if True then] condition.

condition statement

Place the condition into the loop. Place it before the [change counter by 1] block.

condition parameter in place

The code inside a condition is executed if the requirements for the condition are met. The condition needs something to evaluate. One way to evaluate something for a condition is to make a comparison. For example, if something is equal to something else, then run the code in the condition.

Go to the Logic section; get the Equality comparison code block.

comparison operators

Place the comparison code block into the Condition parameter.

comparison block in place

Place the [counter] variable into the left side of the Equality comparator.

counter variable in place

The other side of the comparison code uses basic math. We need five points to check for comparison. Each is related to one of the LEDs to be light.

In the [on start] section we calculated the units of the division by the 5 segments we need for the LEDs. Multiplying the Unit or quotient(6) by 1, 2, 3, 4, and 5 will generate the markers we need.

Go to the Math section; find the multiplication operation.

operators in code section

Place the multiplication operation on the right side of the comparison code.

operation code added

Place the [unit] variable into the left side of the multiplication operation.

variable in operation

The unit value needs to be multiplied by each number from 1 to 5 for comparison to light each LED in turn. Type the number 1 into the right side of the multiplication operation.

value in operation

When the counter and the unit values are the same, the first LED will light. Go to the LED section; find the [plot x… y…] code block.

LED code blocks section

Place the code inside the condition.

plot code added

The LEDs are numbered using the computer Index. Computer indexes begin with zero. All the LEDs on the Micro:bit begin at index zero from left to right and top to bottom. The LED at index x=0 and y=0 is the top left LED. The progress bar will begin in the third row. This is index zero for the x-axis and two for the y-axis.

Enter the number 2 for the y-axis value.

x-axis value

The LEDs will be light from left to right. The next LED to be light is along the x-axis. The set of index values for the next LED are x=1 y=2. The y-axis index will always be the same.

This is the basis for lighting each of the LEDs in turn. When the counter reaches 12, 6 x 2, the next LED, x=1 y=2, will light.

The numbers for the multiplication and the x-axis index increase by one during each cycle. This is a clue for us to use a counter and a loop.

New programmers often want to repeat a process. For example, we could make a copy of the condition statement and change the values for the next LED(don’t do this part). In the image below, I duplicate the condition statement, changed the multiplication value from 1 to 2, and changed the x-axis index to 1. This involves unnecessary repetition of code. If we ever needed to update the code we would need to update each condition. For example, if the next version of the Micro:bit included a 7 by 7 matrix of LED lights. We would need to add two more conditions and change the numbers.

parameter values

This is what we will do instead.

Go to the Variables section. Create a new variable; use “ledCounter” for the variable name.

new variable created

Place the [ledCounter] variable on the right side of the multiplication operation.

variable inserted into code

Place the [set ledCounter to 0] block into the [on start] section.

set counter variable

The [ledCounter] will be used in a multiplication operation. Multiplying anything by zero will result in a zero. There are times when we might want that, but not in this situation. Change the assignment value to number one.

led counter variable set

Plotting the LED uses a similar process. We need to change the x-axis index after each LED is light. Go to the Variables section. Create another variable; use “x-ledplot” for the variable name. Place the variable into the x-axis parameter.

x-axis coordinate variable value

Place the [set x-ledplot to] code into the [on start] section.

set variable code connected

Place the [change x-ledplot by 1] code into the condition statement. Place the code after the code to plot the LED light. This changes the value after the previous LED is light.

variable values update

Place another [change variable by] code block into the condition statement. Change the variable to [ledCounter].

variable name selector

Reviewing the code

When the counter matches the markers, the condition statement will run the code inside. Let’s walk through a couple of steps.

The counter will increase by one each time through the loop until it reaches the first marker at six. The LED at the positions x=0 and y=2 will light. The [x-ledplot] variable will increase by one. The [ledCounter] variable will also increase by one.

During the next series of loops, the counter will need to match the product of the Unit variable times two. When the counter matches 12, the LED at positions x=1 and y=2 will light. Each of the variables will increase by one. The process will continue until the counter reaches the value of 30.

One more thing

Move the [change counter by 1] code block; place it after the condition statement and in the loop.

change variable counter

Running the program

The progress bar code is complete. Click the A-button.

The code generated the progress bar but it did so a little too fast. Get a [pause] code block from the Basic section. Place it below the condition statement and before the change counter code block.

pause code block

More data points

The progress bar works with any number of data points we want to collect. Change the [totalCount] variable with another value. For example, enter 80 and click the A-button.

total count value update

The progress bar takes a little longer to render. That’s because we are collecting more values between each marker.

Collecting temperature values

We can add any operation after the pause code. Create a variable; use “temperature” for the variable name.

Place the [set temperature to] code before the pause code.

temperature variable

Go to the Input section. Get the [temperature] code and place it into the [set temperature to] parameter.

temperature input code

Go to the Radio section; find the [radio set group] code.

radio set group code

Place the code into the [on start] section.

radio set group code in place

Find the [radio send value ] code block.

radio send value code block

Place the code block after the [set temperature to ] code.

radio send code block

Change the value name to Celsius.

value name updated

Get the [temperature] variable; place it into the [radio send value] assignment parameter.

temperature variable in place

Change the pause value to 1-second.

pause value selected

Change the [totalCount] variable assignment to 30.

total count value updated

This code will collect temperature information. It will get a new reading every second. The reading will be transmitted to another Micro:bit. It will do this for a total of 30 times, 30-seconds. The progress bar will keep track of the process.

Blinking progress

Collecting move information from the sensor requires more time. The progress bar, in turn, takes longer. It could seem like the progress might have stalled. We are going to include a toggle process in the code each time the loop cycles. A toggle will turn the LED Off if it is On or On if it is Off.

Go to the Logic section; get an [if True then] code block. Place the code after the [if True then] in the loop.

condition code block connected

We are using a similar comparison to the one used in the condition above. We can copy all the blocks in this comparison. Move your mouse over the code. Look for the comparison code block to be highlighted.

equality code block selected

Right-click when the comparison code is highlighted; select the duplicate option.

duplicate code option

Get the code and place it into the condition parameter.

duplicate code being connected

Change the Equality operator to less-than or equal-to.

less-than or equal-to option

Go to the LED section; get the [toggle x… y…] code block.

toggle LED code block selected

Place the code block into the condition statement.

toggle code connected

Get the [x-ledplot] variable; place it into the toggle x-axis parameter. Enter two for the y-axis parameter.

toggle code parameters updated

Run the program. Each LED in the progress bar will blink until the counter reaches the required value.

We can reuse this code for other projects. All we need to do is replace the information we want to gather.

temperature information highlighted
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit temperature transmitter

This project uses two Micro:bits. One will record the ambient temperature and the other will receive and display the temperature. This allows us to remotely monitor the temperature from one Micro:bit. This is useful if you don't want to constantly pick up the Micro:bit from its location to get a reading.

Micro:bit remote temperature sensor

Temperature transmitter

This lesson builds on a previous lesson for a temperature sensor. You don’t need to go through that lesson to follow along with this lesson.

In that lesson, we created a thermometer to read the ambient temperature. The thermometer reports the temperature in Celsius or Fahrenheit when the A or B button is pressed.

The thermometer provides continuous feedback on the ambient temperature. It displays a happy face when the temperature is comfortable, an angry face when it's too hot, and a sad face when it is too cold. Use the link below to access that lesson.

This project uses two Micro:bits. One will record the ambient temperature and the other will receive and display the temperature. This allows us to remotely monitor the temperature from one Micro:bit. This is useful if you don't want to constantly pick up the Micro:bit from its location to get a reading.

The purpose of the project is to be able to monitor the temperature of a location from another location. For example, we can place one the sensing Micro:bit outdoors. The other Micro:bit can be inside a classroom. We can monitor the outdoor temperature from inside the classroom.

Here are some other ways we can use this project. The sensing Micro:bit can be placed into a refrigerator, a freezer, in a sealed plastic bag, and hot water.

We can use it in a science experiment with ice water and salt. Get a container, 1 or 2 gallons; add water and ice in equal amounts. Place the Micro:bit thermometer into a water-tight container like a plastic bag. Measure the temperature until it can't get any colder, around 32-degrees Fahrenheit 0-degrees Celsius. Add salt to the ice water and gently stir. The temperature will begin to drop. This combination can bring the temperature down to minus 6-degrees Fahrenheit. Colder than the freezing temperature of the water.

I recommend a good water-tight container for electronics if you plan to place the Micro:bit into the water. I use a water-tight pouch designed for cell phones. It's large enough to accommodate the Micro:bit and battery. There are plenty of sources available through online retailers. Make sure the pouch has an IPX7 or IPX8 rating. IPX7 items can be submerged up to 1 meter for 30 minutes. IPX8 can be submerged deeper than a meter and can be in the water longer.

The thermometer

Use the link below to get a copy of the thermometer program created in the Thermometer / Thermostat lesson.

https://makecode.microbit.org/_CTiWy7U3qPMe

Github https://github.com/digitalmaestro/thermometer-thermostat.git

The thermometer reports the temperature in Celsius when the A button is pressed. It reports the temperature in Fahrenheit when the B button is pressed. In the Forever loop, it is providing constant information on the ambient temperature. It provides feedback in the form of icon expressions.

Transmitting and receiving

The same code works for transmitting and receiving information. To transmit and receive information between Micro:bits, we need to use code in the Radio section. Select the Radio section.

Radio code section selected

The Micro:bit needs to pair with another Micro:bit to send and receive information. This is done using the [radio set group] code block. Get the code block and add it to the [on start] function.

code in start function

The radio group is set to one automatically. The group number can be any number from 0 to 255. The important thing to know is that the communicating Micro:bits must be using the same group number. Leave the radio group set to one.

Go back to the Radio code section and find the [radio send number] code block.

code block selected

Place the code block after the [set Fahrenheit to…] code in the [forever] loop.

radio send number code added

I am using Fahrenheit for the example; we can just as easily send Celsius information.

Go to the Variables section; get the Fahrenheit variable and place it into the [radio send number] parameter.

variable in parameter

At this point you will notice a second Micro:bit appears in the simulator section. This is all the code we need to begin transmitting and receiving.

Micro:bit simulator

Now we need a way to receive the information. Find the [on radio received(receivedNumber)] code block in the Radio section.

on radio received code block selected

Place the code block on the canvas. The code we place in the function decides what we do with the information received. We will just display the information for now.

on radio received code on canvas

Go to the Basic section and get the [show number] code block.

show number code block selected

Pace the code block into the [on radio received(receivedNumber)] function.

show number code block added

To show the number from the transmitting Micro:bit, we need to pass the received value into the parameter. The function has a variable to place into the parameter. The variable is called [receivedNumber] and it is in the [on radio received] parameter.

receivedNumber variable

Select the variable from the parameter and place it into the [show number] parameter.

receivedNumber variable in show number parameter

These are all the modifications we need to send and receive data from the thermometer.

radio received code

Go to the simulator section. Adjust the temperature input slider. Make it hotter by sliding it up.

temperature slider in simulator

The first Micro:bit shows the proper icon, angry. The other Micro:bit still shows a happy face. The information is transmitted and received but there is a conflict. The second Micro:bit has a temperature sensor too. The code is getting the readings from that sensor and displaying a happy face.

Receiver only

We built both transmitter and receiver into the same code. I did this so you could see how it works in one example. We are going to modify the code a little to make one Micro:bit into a receiver only. The other will be a transmitter.

The receiver does not need to send information. We don’t need the [radio send number] code.

The code is between other code blocks. Hold the Option key on your keyboard while pulling the code out. The Option key isolates this one block from the others for movement.

radio send number being removed

Take the code block to the codes section to remove it from the program.

radio send number code over trash icon

Receiver variable

The receiver is set to record the ambient temperature from the receiver itself. This needs to be changed to display the information received from the transmitter. To do that we need a variable to hold the data from the transmitter. The variable will replace the sensor reading code, [temperature].

Go to the Variables section; click the Make a variable button.

make a variable button

Use “transmittedTemp” for the variable name; click the OK button.

variable block name

Get the [set transmittedTemp to] variable.

set variable code block selected

Place the code block into the [on radio received] function.

set variable code block added

Remove the [show number] code block.

removing show number code block

Place a copy of the [receivedNumber] variable into the [set transmittedTemp] assignment parameter.

variable added to parameter

The variable will contain the temperature reading sent from the transmitter. We need to replace all the [temperature] code blocks with the [transmittedTemp] variable.

Go to the A Button function. Remove the [temperature] code block from the [set variable to] parameter.

temperature code being removed

Get the [transmittedTemp] variable from the Variables section; place it in the parameter where we removed the [temperature] code.

temperature variable being added

Remove the [temperature] code from the [show number] parameter.

temperature code being removed

Place the [transmittedTemp] variable into the [show number] parameter. Repeat the process for all instances of the [temperature] code.

variable added to show number parameter

Don’t forget the one in the [forever] loop.

temperature variable

Receiver only

This Micro:bit is only a receiver now. It does not get information from the temperature sensor. The temperature slider is not on the Micro:bit anymore. If the slider is still there, make sure you replaced all the [temperature] code with the [transmittedTemp] variable.

Micro:bit display

Rename the project

Go to the project name field and update the name. Use “Thermometer Receiver” for the name.

updated project name

Transmitter code

We need a separate project for the transmitter. Use the link below to open the Make Code site in a new tab. Create a new project. Use Thermometer transmitter for the project name.

https://makecode.microbit.org

Go to the Radio section. Get the [radio set group] code; place it into the [on start] function.

radio set group code added

Get the [radio send number] code; place it into the [forever] loop.

radio send number code in loop

Go to the Input section; find the [temperature] code block.

temperature code block selected

Place the code into the [radio send number] parameter.

temperature code in parameter

This is all the coding the transmitting Micro:bit needs. The code on the receiver will take care of converting the values to Fahrenheit. The A and B buttons will do their thing.

Too much information

The receiver code includes the comfort zone display. This is not always needed. There is no need to get rid of it. We can make the comfort zone display optional. Using the A+B buttons we will toggle the display code on or off. It will be off when the Micro:bit starts and turned on when buttons A+B are pressed. This will give you the option to get continuous feedback or not.

The code in the forever loop is already lengthy. Whenever we have a block of code that serves a specific function, that is the time we need to place it into a Function.

Click the Advanced option in the code section; select the Functions section.

Functions section

Click the “Make a Function” button.

make a function button

A function configuration box opens. Click once inside the function name.

function name selected

Use “comfortDisplay” for the function name; click the done button.

updated function name

Move the Function container next to the [forever] loop.

function on coding canvas

Select the first block in the [forever] loop; move it to the function.

code blocks being moved

Click the Minimize button.

function minimize button

This collapses the function so the code is neatly tucked away.

collapsed function block

Go to the Variables section; click the “Make a variable” button.

make a variable button

Use “toggle” for the variable name; click the OK button.

variable name

Get the [set toggle to] code and place it on the canvas.

set variable code block

Go to the Logic section; get the [if True then] condition statement. Place it on the canvas.

condition code block selected

Place the [set toggle to] code into the condition code.

set variable being inserted into condition

Go to the Input section; get the [on button A pressed] code and place it on the canvas.

on button a pressed code selected

Place the condition statement into the button function.

code being put into place

Click the button selector; select the A+B option.

button option selected

The condition needs to check the toggle value. If the toggle is zero, then the Micro:bit will NOT display the comfort symbols. This will be the state when the Micro:bit starts.

To evaluate the condition, we need a comparator. Go to the Logic section. Find the Equallity comparator.

equal comparator selected

Place the comparator into the condition parameter.

comparator placed in parameter

Go to the variables section. Get the [toggle] variable; place it into the left side of the comparator.

variable in comparator parameter

Change the value of the [set toggle to] variable; use 1 for the value.

variable value set

Hang in there!

This is what is going on up to this point. When we press the A and B buttons the condition statement will check the value of the toggle. The value is set to zero when the Micro:bit starts. —We will set this in a moment.— If the value is zero then it will change the toggle value to 1. The 1 instructs the code to display the comfort zone information. The number zero is the Off switch and the number 1 is the On switch.

Back to our code

Pressing the A and B buttons will display the comfort icons. Pressing the buttons again will hide them. That’s what a toggle does.

Click the Plus button in the [if True then] condition.

add condition button

This adds an Else option to the condition.

else option shown

Go to the Variables section; get a [set toggle to] code block. Place it into the Else section.

set toggle variable

This is what the code does. If the toggle value is zero, the value is updated to 1; Else the toggle is set to zero. The Else portion looks to see if the value is anything else other than zero. If it is, then it sets the value to zero.

Let’s say that a different way. If the toggle is off change it to on. If it is not off then turn it off.

The next part of the code uses almost all the same code. We will save some time and duplicate the condition statement. Right-click on the condition statement and select Duplicate.

duplicate option selected

Place the duplicate code into the [forever] loop.

code in loop

Remove the [set toggle to] code blocks.

variable blocks removed

Change the zero in the comparator to one.

variable value updated

Go to the Functions section; look for the call function block.

call function block selected

Place the [call comfortDisplay] code into the If section of the condition.

code added to condition

The condition compares the value of the [toggle] variable to the number. If the value of the toggle is one, then the display code is called to run. If the value of the toggle variable is NOT 1 then the function is not called. The Else part of the condition needs to be here even if we don't provide any code.

Go to the Variables section; get the [set toggle to] code block. Place it into the [on start] function. This sets the start-up value of the toggle variable to zero. The toggle is off and the comfort information will not display.

variable assignment in start function

Run the program

The display on the Micro:bit is blank. None of the information received from the transmitting Micro:bit is displayed.

Micro:bit not information displayed

Click the A+B button.

The Micro:bit will display a sad face. The temperature will display a few seconds later.

The simulator is not receiving anything from the transmitter so it can only report a default value. That value is zero degrees Celsius or 32-degrees Fahrenheit.

Press the A+B button to turn off the comfort display.

sad icon

Press the A button to see the temperature in Celsius. Press the B button to display the temperature in Fahrenheit.

Ready to download

Download and transfer the Thermometer **Receiver** code to one Micro:bit.

Download and transfer the Thermometer **Transmitter** code to another Micro:bit.

Final notes

The transmitting Micro:bit does not display any content. There is no need to display anything since it is most likely to be out of sight. This extends the life of the battery if the sensor is going to be in a location for some time.

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit thermometer / thermostat

The Micro:bit has a sensor to measure the ambient temperature. It is not designed to be touching something like water. The sensor is inside the CPU.

The sensor is like a thermometer. A thermometer, like the one on the Micro:bit, can be used to trigger events. An event can include the update of information on a display or the activating of something like a cooler or heater.

Micro:bit thermometer and thermostat

Micro:bit thermometer / thermostat

The Micro:bit has a sensor to measure the ambient temperature. It is not designed to be touching something like water. The sensor is inside the CPU.

The sensor is like a thermometer. A thermometer, like the one on the Micro:bit, can be used to trigger events. An event can include the update of information on a display or the activating of something like a cooler or heater.

When a thermometer is used to trigger events it is called a thermostat. Thermostats are usually used to regulate temperature. A thermostat does not have to be used to regulate temperature. It can be used for any number of actions in response to a temperature reading. For example, it could sound an alarm if the temperature is too low or high.

In the lesson, we are going to

1. Create code to display the ambient temperature in Celsius.

2. Update the code to display either Celsius or Fahrenheit.

3. Display a friendly icon when the temperature is in a comfort zone.

4. Display a sad icon when the temperature is in an uncomfortable zone

Project preview

A link to the completed project is available below. Use it to get a preview of the final product. The code is also available through my Github repository. Use the link to import the project.

Thermometer / Thermostat project from Make Code

Thermometer / Thermostat project from Github

Celsius and Fahrenheit

Two measurements are commonly used in everyday temperature measurements. Both use the freezing and boiling of water. Celsius uses 0 for the temperature at which water freezes. The boiling point of water is 100-degrees celsius. Fahrenheit uses 32 degrees for the freezing point of water and 212-degrees for the boiling point of water.

Fahrenheit uses zero-degrees to mark the point where an equal mixture of ice, water, and salt freezes. Salt in ice water causes the ice to release energy and make the water colder. This is how ice cream makers get super cold turn cream into ice cream.

The measurement interval between Fahrenheit and Celsius is different. The interval between the scales is five-ninths(5/9). This number is important when we are looking to convert one unit of measure to another. We will revisit this later.

The Micro:bit uses Celsius as the unit of measure for temperature.

Micro:bit simulator

You don’t need to have a Micro:bit to learn about the Micro:bit. Microsoft provides a free online Micro:bit simulator. No login account is required. Use the link below to access the simulator.

The simulator is also the environment we use to create code for the Micro:bit.

https://makecode.microbit.org

Create the project

Click the New Project button.

new project button

Set the name of the project to “Thermometer Thermostat”; click the Create button.

project name field

Each new project includes two code blocks. The [on start] code runs instructions the moment the Micro:bit powers up or is restarted. The [forever] loop runs code in the loop for as long as the Micro:bit is powered.

on start and forever code blocks

Sensor reading

We are going to display the reading from the temperature sensor.

Select the Basic code section; look for the [show number] code block.

show number code block selected

Place the code block inside the [forever] loop.

code block inserted

Select the Input section.

input section

Find the [temperature] code block.

temperature code block

Place the code block inside the [show number] parameter.

code inserted into parameter

The simulator is not connected to a real sensor to take temperature measurements. The simulator provides a temperature slider to simulate the temperature received by the sensor. The temperature slider is set at the midpoint of 21-degrees Celsius.

temperature reading

Click and drag the slider to the top. The maximum temperature scale is 50-degrees Celsius.

maximum temperature reading

Move the slider down. The lowest temperature registered by the sensor is -5-degrees Celsius.

lowest temperature reading

Fahrenheit

You probably want to know what the temperature readings are in Fahrenheit. We need to convert Celsius to Fahrenheit.

We aren’t just going to convert the temperature and forget about Celsius. We are going to use the Micro:bit buttons to provide the temperature information in Celsius or Fahrenheit.

Select the Input code section; get the [on button A pressed] code block.

code block selected

Place the code block on the coding canvas.

code block on canvas

Get the [show number] code from the [forever] loop and place it in the [on button A pressed] function.

code inserted

Press the A-button on the simulator. The temperature is sensed and displayed when the button is pressed.

scrolling temperature reading

We are going to do the same thing for button B. Right-click the [on button A pressed] code and select the duplicate option.

duplicate option

A copy of the code blocks is created and placed on the canvas. The code is a light green with hash marks. This indicates that the code is not active. Make Code does not permit two functions to be on the canvas for the same button.

code on canvas

Click the button selector; choose B.

button selector

When button B is pressed, the Micro:bit will convert Celsius to Fahrenheit.

code blocks available

Remove the [celsius] input from the [show number] parameter. Set it to one side.

code block removed

The difference in units of measure between Fahrenheit and Celsius is 5/9. The difference for the freezing point of water is 32. To convert Fahrenheit to Celsius we subtract 32. We then multiply that answer by 5/9. The formula is shown below.

Celsius = (Fahrenheit - 32) x 5/9

To convert Celsius to Fahrenheit we multiply 9/5, the inverse of 5/9, and add 32. We can use the conversation formula with a fraction, 9/5, or with a decimal. The fraction 9/5 is 1.8. The formula is shown below.

Fahrenheit = (Celsius x 9/5) + 32

Go to the Math code section. Find the multiplication operation.

operation code blocks

Place the operation code block inside the [show number] parameter.

operator added

Place the [temperature] code block into the left side of the multiplication operation parameter.

code added to operator

Enter 1.8 into the right side.

value added to parameter

Return to the Math section and get the Addition operation. Place it on the canvas below the code we are working on. We are placing the code here for a moment so we can insert the multiplication operation into the left side of the addition operation.

operator added

Select the Multiplication operation and place it on the left side of the Addition operation. Make sure to select the operation block.

code added to operator

Select the math operation block and place it inside the [show number] parameter.

moving code block

Enter 32 into the right side of the Addition operation.

value added to operator parameter

Go to the simulator and press the B-button. The slider shows the temperature in Celsius. The number scrolling across the display is the same temperature in Fahrenheit.

temperature scrolling

Move the temperature slider up and down. The maximum temperature in Fahrenheit is 122-degrees. The lowest temperature is 23-degrees.

Comfort zone

We are building on the same project to display a room temperature comfort meter. The Micro:bit will monitor the ambient temperature and report the comfort level. It will report this with icons and occasional information.

The comfortable temperature for most people ranges between 18 and 24-degrees Celsius, 64 and 75-degrees Fahrenheit. Temperatures above and below this range are uncomfortable. The thermostat will display a smiling icon when the temperature is within the range. It will display a Sad icon when it’s too cold and an Angry icon when it’s too hot.

Variables

We have an equation that converts Celsius to Fahrenheit. We need to use this conversion in at least one more location. This is reason enough to use variables.

Variables allow us to store values or the result of complex operations into a container. This container is used where needed without the need to enter the value or recreate the operation. They reduce the chances that we will make mistakes and increase the efficiency of programming.

Go to the Variables section; click the Make a Variable button.

make a variable button

Use “Fahrenheit” for the variable name; click the OK button.

variable name

Every variable gets three code blocks. Get the [set Fahrenheit to] code block and place it on the canvas.

variable blocks

Get the conversation formula and place it into the [set variable] parameter.

code being attached

Place the Set code block into the [on button B pressed] function; place it before the [show number] code.

code set in place

Return to the Variables section and get the Fahrenheit variable block.

variables section

Place the variable into the [show number] parameter.

variable in parameter

Right-click on the Set Variable code block; select duplicate.

duplicate option

Place the code inside the [forever] loop.

code in loop

We need a variable for Celsius. We don’t need to convert to Celsius, but it is a good idea to keep things consistent and use variables when we might need to use a value more than once.

1. Return to the Variables section.

2. Create a new variable and use Celsius for the variable name.

3. Place the [set Celsius to] code block on the coding canvas.

4. Place the Celsius code into the variable parameter.

5. (You can either duplicate the code block or get one from the Input section)

6. Place the code into the [on button A pressed] function; above the [show number] code.

code blocks

Move the button code blocks down and out of the way. We won’t be working on them until later.

Fahrenheit or Celsius

The choice to use Celsius or Fahrenheit is yours. I will use Fahrenheit. The same code works regardless of your choice.

We want to display a smiling icon if the ambient temperature is within the comfortable range, 64 to 75. To do this, we need a condition statement. A condition statement evaluates if something is True or False. The condition statement then performs an action based on the evaluation.

Go to the Logic code section. Look for the [if True then] code block.

code block selected

Place the code block into the [forever] loop and below the Set Variable code.

code block in place

If the temperature is below 64-degrees Fahrenheit, 18-degrees Celsius, we want to display a sad face icon. We need to compare the sensor reading to this value. To do that we need a comparator operator.

Go to the Logic section; find the Less Than comparator.

code block selected

Place the comparator into the condition statement parameter.

comparator in parameter

Go to the Variables section. Get the variable for your measurement and place it on the left side of the comparator parameter.

variable in parameter

Enter 64 into the right side of the parameter; enter 18 if you are using Celsius.

value added to parameter

Go to the Basic section. Get the [show icon] code; place it inside the condition statement.

code block added

Change the icon to a sad face.

sad face icon selected

Right-click on the conditions statement; select duplicate.

duplicate option

Place the condition statement after the first.

code inserted

Click the comparator selector; choose the Greater Than option.

comparator selector

Replace 64 with 75; use 24 for Celsius.

updated value

Change the sad icon to an angry icon.

angry icon selected

These are the easy conditions. The one for the comfort zone is a little more involved. The condition statement needs to verify specific conditions are met. The lowest temperature must be greater than or equal to 64. The opposite of the first condition. The condition includes the requirement that the temperature is the SAME or greater. The other part of the condition is that the upper temperature is less than or equal to 75.

Boolean logic

Boolean logic is a form of algebra. It is built around three words known as Boolean Operators. The words are “Or”, “And”, and “Not”.

The “OR” operator requires one condition or the other to be Tue. The conditions in an “OR” can be of any number. It Does not matter which one is True.

The “AND” operator requires that all the conditions be True. It does not matter how many conditions there are; they all have to be True.

The “NOT” operator is used in conditions to exclude a condition. We can exclude one or more conditions.

Comfortable condition

The comfortable range is between 24 and 75-degrees. The temperature must be within this range. It cannot be just greater-than-or-equal-to 24. It must also be less-than-or-equal-to 75. This requires that both conditions be met, so we need to use the “AND” Boolean Operator.

Go to the Logic section and get a new [if True then] code block. Put the code on the canvas and to one side of the [forever] loop.

code block on canvas

Return to the Logic section. Look for the “AND” operator in the Boolean section.

boolean selected

Place the operator into the condition statement parameter.

boolean added

Go back to the Logic section. Get a less-than operator and place it on the left side of the Boolean Operator. Get another less-than operator and place it on the right side.

comparators added

Change the less-than operator on the left to greater-than-or-equal-to. Chang the operator on the right to less-than-or-equal-to.

comparators updated

Get the condition statement and insert it between the other two conditions. It can go anywhere. I think this brings home the visual that the comfort level is between the cold and hot extremes.

condition block being inserted

Get a [show icon] code block and place it inside the condition statement. Use a Happy face for the icon.

code block inserted

Get the temperature variable and place it into the left side of the greater-than-or-equal-to comparator.

variable added

Get another temperature variable. Place it on the left side of the other comparator.

variable added

Enter 64 for the left comparator and 75 for the right comparator.

values added to parameters

Test the code

Look at the simulator. The Happy icon is displaying. Move the temperature slider up and down to watch the icons update.

happy face displayed

Move the slider and press the A or B button to display the temperature in either Celsius or Fahrenheit.

Display temperature

It would be nice to periodically display the temperature without having to press one of the buttons.

Go to the Basic section; find the [pause] code. It is near the bottom.

code block selected

Place the code after the last condition.

code added

Click the interval selector; choose 5-seconds.

interval selected

Place the [show number] code block after the [pause]. Place the temperature variable into the parameter.

code block in place

Clear the display

Everything is working nicely. The icon is followed by the temperature after a 5-second delay. The temperature information displays right next to the icon. This can make it difficult to read.

Go to the Basic section; find the [clear screen] code block. Place the code after the [pause].

code block added

Conclusion

We have a thermometer that displays the temperature in Celsius or Fahrenheit with the press of a button. The thermometer causes an event to happen while constantly sensing the ambient temperature. We get different icons for different ranges of temperatures. We have a basic thermostat.

Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit light meter for projects

The goal of the project is to create a light meter to register light values from two different sources at a time. The meter allows us to quantify the brightness of a source. These sources can include a candle, flashlight, LED, incandescent bulb, and fluorescent lights.

microbit light meter for projects

Micro:bit light meter

In this lesson, we are using the Micro:bit light sensor to record the light values of different sources. This makes for a nice science project.

The project

The goal of the project is to create a light meter to register light values from two different sources at a time. The meter allows us to quantify the brightness of a source. These sources can include a candle, flashlight, LED, incandescent bulb, and fluorescent lights.

Sources are not limited to objects. Sources can include locations like a classroom, the outside, a library, or a cafeteria.

I have provided Google Documents with tables of several objects and location ideas. Use the link below to get a copy of the Google Docs. Each document includes instructions.

Light meter comparison table for objects
Light meter comparison table for locations
Light meter comparison table for compare and contrast

You don't need to collect data with tables. The project will allow you to collect two separate light value readings and compare the different values with the Micro:bit.

Get the completed project using one of the links below.

Light meter project (Made Code)

Light meter project (Github)

Code outline

In the code, we are going to…

1. Activate the simulator light sensor.

2. Create code to store the value for one light measurement.

3. Create code to store the value for separate light measurements.

4. Create code to compare the two values.

Micro:bit simulator

You don’t need to have a Micro:bit to learn about the Micro:bit. Microsoft provides a free online Micro:bit simulator. No login account is required. Use the link below to access the simulator.

The simulator is also the environment we use to create code for the Micro:bit.

https://makecode.microbit.org

Create the project

Click the New Project button.

new project button

Set the name of the project to “Light meter”; click the Create button.

project name

Each new project includes two code blocks. The [on start] code runs instructions the moment the Micro:bit powers up or is restarted. The [forever] loop runs code in the loop for as long as the Micro:bit is powered.

Simulated light

The simulator in Make Code cannot register the light through a sensor. It does; however, have a way to simulate the light received by the sensor. We will activate the simulated sensor to test the code during development. In the end, we will remove the code before downloading it to your Micro:bit.

Go to the Basic code blocks section and find the [show number] code block.

selected code block

Place the code into the [on start] code block.

code block in place

Go to the Input section. Find the [light level] code.

code block selected

Pace the code into the [show number] parameter.

code block in parameter

The simulator has a light meter tool in the top left corner.

light meter in simulator

We are going to store the value of one light reading into a variable. The value will be written to the variable when the A-button is pressed.

The first light value

Go to the Input section and find the [on button A pressed] code.

code block selected

Place the code block on the canvas.

code block placed on canvas

Go to the Variables section and click the “Make a Variable” button.

variable button

Use “1st light value” for the variable name; click the OK button.

variable name field

We need another variable for the second light value. Make another variable. Use “2nd light value” for the variable name.

variable code blocks

Get the [set variable value to] code block. Place it in the [on button A pressed] code function.

code block added

Click the variable selector and choose the “1st light value” variable.

variable selector

Place the [light level] code, from the Input section, into the variable parameter.

This instruction activates the light sensor and records the reading into the variable “1st light value”.

code in parameter

Right-click on the [show number] code block in the [on start] function; select duplicate.

duplicate option

Place the duplicate code into the [on button A pressed] code block and after the [set variable to light level] code. This provides feedback for the value recorded into the variable.

The Micro:bit does not have a light meter like the simulator. We need a way to display the value recorded by the light sensor.

code blocks

At this point, this is all we need to collect the light measurement from different objects or locations. You can download this code to the Micro:bit and use it as is. But, we are not done yet.

The second light value

The code to get the second light value is almost identical. We record the data into a separate variable and use a different button to start the process.

Right-click the [on button A pressed] code and select duplicate.

duplicate option

Place the code to one side. The code colors are dimmed in a hashed green. This is Make Code’s way of telling us that the code is not enabled to work. We cannot have two [On Button pressed] code blocks for the same button.

inactive code blocks

Click the button selector; choose the B-button.

button selector

Click the variable selector and choose the “2nd light value” variable.

variable selector

Comparing measurements

Button A will record and store one light value. Button B will record and store another light value.

In the next part, we are going to write code to compare the values and show the difference.

To display the information we need to assign the instructions to a separate button or input option. There isn’t a third button option but there is the option to press both buttons at the same time.

Get the [on button A pressed] code from the Input section and place it on the coding canvas.

code block on canvas inactive

Select the A+B option from the button input selector.

button selector

Get the [show number] code and place it in the [on button A+B pressed] function.

code in button code

Go to the Math section; find the Subtraction operation. Place the code into the [show number] parameter.

operation code block in parameter

Go to the Variable section. Place the [1st light value] variable into the left side of the operation. Place the [2nd light value] into the right side of the operation.

variables in operation parameters

This is all we need.

Test the code

Go to the simulator and move the light meter to a value. Press the A button to record the reading. Move the light meter to a different value; press the B button. Press both A and B buttons to display the difference between the values.

One more thing

To make the displayed answer a little more friendly, I think we should have it display the numbers being subtracted in addition to the answer.

Get the [show string] code block from the Basic section. Place the code before the [show number] code.

code block in place

Click the Advanced section option; find the Text code section.

text code section

Find the [join] code block.

join code block selected

Place the [join] code into the [show string] parameter.

join code block in string parameter

Get the [1st light value] variable; place it into the first join parameter.

variable in join parameter

Replace the word in the second parameter with the minus symbol.

operation in parameter

Click the Plus button in the [join] code to add another text parameter.

add parameter button

Place the [2nd light value] variable into the new text parameter.

join code with parameters

Add another text parameter and type the Equal symbol into the parameter.

equal symbol in parameter

Run the program again. Get a new value for each of the variables and press the A and B buttons. The Micro:bit displays an expression of the light values and difference.

Cleanup

You don’t need the [show number] code in the [on start] function for the real Micro:bit. If you are going to download this to the Micro:bit. Remove the code.

removing code block
Read More
Coding, Micro:bit Alex Coding, Micro:bit Alex

Micro:bit smart LED dimmer

Sensors on the Micro:bit and a little programming allow us to develop products that respond to input from the world in ways that produce desirable results.

Light sensors are used in a variety of real-world applications. Light sensors are used in outdoor lights to turn them on when it gets dark. The same sensors turn the lights off when the sun is out.

Micro:bit smart light sensor dimmer

Smart light sensor dimmer

Sensors on the Micro:bit and a little programming allow us to develop products that respond to input from the world in ways that produce desirable results.

Light sensors are used in a variety of real-world applications. Light sensors are used in outdoor lights to turn them on when it gets dark. The same sensors turn the lights off when the sun is out.

Sensors and programming help create sophisticated applications.

The light sensor on the Micro:bit can be used to gradually make adjustments based on the ambient light. I covered this in the light sensor basics with a simple application.

Use the link below to see the light sensor introduction lesson.

Turning lights on or off when the ambient light changes is a basic smart switch. In the introductory lesson, we adjusted the LED brightness using the ambient light to control the brightness. As the ambient light rose, the LED lights got brighter. This isn't very useful because we don't need the LEDs to get brighter as the ambient light gets brighter. We need the opposite to occur.

Light sensor basics

Project objective

This project integrates some basic math along with process skills. The project aims to create a responsive sensor like that used in modern cars.

The display in modern cars decreases the panel lighting to compensate for the brightness of the daylight hours. The display gradually increases as the sun goes down. The brightness is not increased too much. Just to a comfortable level. This setting is often adjustable by the driver or passenger.

The project uses the light sensor to gradually decrease the LED luminance as the ambient light gets brighter. The Micro:bit will also gradually increase the luminance as the ambient light gets dimmer.

Use the link below to get a copy of the final product.

Smart LED dimmer (Make Block Micro:bit)
Smart LED dimmer (Github)

Development

You don’t need to have a Micro:bit to learn about the Micro:bit. Microsoft provides a free online Micro:bit simulator. No login account is required. Use the link below to access the simulator.

The simulator is also the environment we use to create code for the Micro:bit.

https://makecode.microbit.org

Download the completed project using the link below.

Click the New Project button.

new project button

Set the name of the project to “Responsive LEDs”; click the Create button.

project name

Each new project includes two code blocks. The [on start] code runs instructions the moment the Micro:bit powers up or is restarted. The [forever] loop runs code in the loop for as long as the Micro:bit is powered.

We need something to look at when adjusting the display brightness. Go to the Basic code section; look for the [show icon] code block.

show icon code block

Place the code block inside the [forever] loop.

code block inserted

We want the responsive light meter to begin with standard light measurement. That standard measurement for this project will be the midpoint for the light sensor.

Go to the Basics code section; find the [show number] code block.

code block selected

Place the code block in the loop and below the icon code block.

code block added

Go to the Input code section and find the [light level] code block.

code block selected

Place the code block into the [show number] parameter.

code block added to parameter

This code block displays the sensor reading from the Micro:bit. Look at the Micro:bit simulator. There is a brightness simulator icon in the top left corner. The simulator is also a meter for the amount of light that is being received by the sensor. The simulator shows that that the sensor is sensing about half the light it can register. This reading is in the simulator. The physical Micro:bit uses an estimate of the ambient light.

The LEDs used to sense light are not as accurate as using a Light Dependent Resistor(LDR). This is an independent component dedicated to converting light into electrical signals. The Micro:bit uses some algorithms to get a fairly accurate representation of the ambient light strength.

The light sensor returns a range of values from 0 to 255 (0 is dark and 255 is bright). The reading of 128 is right in the middle.

This is a good value to use for comparison.

Micro:bit simulator

The Micro:bit needs to make decisions based on the base reading of 128 and the ambient light.

We are using conditional statements to make our decisions. Conditional statements include statements like “If something is True Then take this action”. The opposite of this statement is that “If something is False then take an action”. The action taken depends on what we want to do.

Go to the Logic section; look for the [If True Then] code block.

condition code block selected

Place the condition statement inside the loop and below the [show number] code block.

code block inserted

The condition statement is looking for something True. We need to provide something to return a True or False response.

Look for the “Less Than” comparison code block in the Logic section.

code selected

Place the comparison code block into the condition statement parameter.

code added to parameter

Go to the Input section and get the [light level] code block. Place the code on the left side of the comparator.

code inserted into parameter

We want to compare the ambient light level to our base, 128. Type 128 into the right side of the comparator parameter.

value updated

The condition will compare the ambient light level to 128. If the light level is less than 128, then it will perform the instructions. We will get to that in a moment.

Variables

We typed 128 as the parameter into the comparator. In the future, we might want to change the base comparison to something else. Hard coding this value into the code is not a good idea if we intend to change the value in the future. Using a variable makes it easy to update the value for all the parameters in our program.

Go to the variables section and click the Make a Variable button.

make variable button

Use “Base level” for the variable name: click the OK button.

variable name field

Get the [Base level] variable.

variable selected

Place the variable into the right side of the comparator; in place of the value.

code block added

Go back to the Variables section; get the [set variable to] code block.

variable blocks

Place the code block inside the [on start] code; set the value to 128.

code added

When the ambient light increase or decreases, we want the light to increase or decrease proportionally. To do this, we need to get the difference between the ambient light and our base. We need to compensate for the difference and add the difference.

We need another variable to help with the math operations.

Go to the variables section and create another variable. Use “light” for the variable name.

Get the [set light to] variable block.

code blocks displayed

Place the block inside the condition statement.

code block placed

We need to determine the difference between the base light and the ambient light. Go to the Math section. Get the subtraction code block and place it in the variable parameter.

code added

Place the [Base level] variable into the left side of the operation.

code added to operation

Get the [light level] input and place it on the right side of the operation.

code block added

This takes the base light level of 128 and subtracts the ambient light. For example, if the ambient light is 90, the difference is 128 - 90 or 38.

We want to increase the light level by this amount. The amount has to be increased beyond the 128 base value. We need to add the difference to the base to increase the light level.

Go to the LED section and the more subsection; find the [set brightness] code block.

code block displayed

Place the code block inside the condition statement and after the [set variable to] code block.

code block added

Place an addition operation code block from the math section into the [set brightness] parameter.

code block added

Get the [light] and [Base level] variables. Place the [light] code into the left side of the addition operation. Place the [Base level] code on the right side.

code blocks added

Let’s test the sensor. Adjust the lightness meter to any value less than 128.

It isn’t easy to tell if the LEDs are getting brighter in the simulator.

simulator

Sensor feedback

We need a way to verify that the program is working. The number scrolling across the display is that of the ambient light level. We need to display the LED brightness level instead.

Go to the LED section and the More subsection. Find the [brightness] code block.

code block selected

Place the [brightness] code block into the [show number] parameter.

code added

Return to the simulator and adjust the light meter. The meter in my simulator reads 112. The number scrolling across my display reads 144. The difference between 112 and 128 is 16. When we add 16 to 128 we get 144. The brightness of the LEDs has increased.

value scrolling across display

Dimming the LEDs

Reducing the brightness uses the same process. The math is slightly different.

Right-click on the condition statement; select duplicate.

duplicate option

Place the duplicate condition statement below the first.

duplicate code set in place

We need to see if the ambient light is greater than the base light. Change the less than symbol to greater than.

greater than operation selected

We need to subtract the base light from the light level. There are a couple of ways to do this next step.

Absolute values

The first option is to remove the [Base level] and [light level] code blocks from the [set variable to] code. Set them to one side.

code blocks removed and set aside

Put the code blocks back. Place the [light level] into the left parameter and the [Base level] into the right parameter.

code blocks in place

Here is another way to do the same thing. This is good when you get into studying absolute values. I put the code blocks back the way they were.

Get the [absolute of] code block from the Math section.

code block selected

Place the block on the canvas outside the code.

code block placed on canvas

Move the mouse arrow over the subtraction operation. Make sure the operation is surrounded by a highlight.

operation block selected

Place the operation block into the [absolute of] parameter.

connecting code block

Place the [absolute of ] code block into the [set light to] parameter.

code placed in variable parameter

Now we need to set the brightness. We need to subtract the ambient light from the base light level. Switch the [light] variable and the [Base light] variables. Change the addition to subtraction.

code blocks updated

Go to the simulator. Reduce the brightness level. Dim LEDs are easier to see in the simulator.

moving simulated light meter

One more thing

We don’t need the feedback to display across the Micro:bit. Grab the [show number] code block and move it out of the loop. The attached code below is moved along with this one block. Put the code block back in place.

moving code blocks

There is a better way to remove just one code block without having to juggle lots of code blocks around.

Hold the Option key on your keyboard while dragging the code block away. This isolates the one code block from the others.

show number code block being moved on its own

Take the code block to the codes section.

deleting code block

The program is complete. Send the code to the Micro:bit if you have one.

Read More
Micro:bit, Coding Alex Micro:bit, Coding Alex

Micro:bit light sensor basics

The Micro:bit has LEDs that emit light. The same LEDs are used to collect and measure light. The LEDs on the Micro:bit perform double duty.

In this lesson, we are going to:

1. Learn to measure the light received by the sensor.

2. Set the brightness of the Micro:bit LEDs based on the ambient light.

3. Turn the LEDs On or Off based on the ambient light.

Micro:bit light sensor basics

Micro:bit light sensor

The Micro:bit has LEDs that emit light. The same LEDs are used to collect and measure light. The LEDs on the Micro:bit perform double duty.

In this lesson, we are going to:

1. Learn to measure the light received by the sensor.

2. Set the brightness of the Micro:bit LEDs based on the ambient light.

3. Turn the LEDs On or Off based on the ambient light.

You don’t need to have a Micro:bit to learn about the Micro:bit. Microsoft provides a free online Micro:bit simulator. No login account is required. Use the link below to access the simulator.

The simulator is also the environment we use to create code for the Micro:bit.

https://makecode.microbit.org

Use the link to go to the Make Code website. Click the New Project button.

new project button

Use “light sensor project” for the name and click the Create button.

project name

Each new project includes two code blocks. The [on start] code runs instructions the moment the Micro:bit is turned on or restarted. The [forever] loop runs code in the loop for as long as the Micro:bit is powered.

on start and forever code blocks

A BIT of information

A bit is the smallest container of information. A bit holds a maximum of two values, either 1 or 0. These represent programmings states like yes, no, on, off, true or false. The states are translated into information. The combination of possible states is expressed as an exponent. Eight bits is 2 to the power of 8 or 256 bits of information. The number of bits here is exactly what the Micro:bit uses to represent the amount of light received by the sensors. The Micro:bit detects light with the LED sensors. The light is processed and the intensity of the light is converted to a number range. That range is 0 to 255.

Measuring light

Go to the Basic code blocks section. Find the [show information] code block.

basic codes section

Place the code block into the [forever] loop.

show number code block

Go to the Input section; find the [light level] code block.

light level code block

Place the code into the [show number] parameter.

code in parameter

Look over at the simulator. A simulated light meter is placed at the top left corner. The LEDs on the Micro:bit scroll to display the light reading. The light reading is also represented below the light meter. That reading is 128. This number represents the midpoint of the possible light received by the sensors.

Micro:bit simulator

Use the mouse arrow to change the light level. Click inside the meter and move the pointer up. This reduces the light intensity. I reduced the light intensity to 98 in my example. Drag the meter down to increase the light intensity.

light meter value at 98

Dimming

Let’s use the sensor as a dimmer. A dimmer reduces or increases the light based on sensor input.

Remove the [show number] block and set it to one side.

code removed

Go to the Basic section; get a [show icon] code block and place it in the loop.

show icon code in loop

Go to the LED section and into the More section. Find the [set brightness] code block.

set brightness code block

Place the code into the loop and below the [show icon] code block.

code in loop

Get a [light level] code block from the Input section and place it into the [set brightness] parameter.

code in parameter

Go over to the simulator. Move the light input meter up and down. Watch the icon increase and decrease in brightness.

full brightness level

The brightness of the LEDs is proportional to the light level received from the sensor. The sensor provides graduated information to the program. The program uses this information to brighten or dim the LEDs accordingly.

On/Off sensor

The sensor can be used as a simple switch. We need to use conditions to decide when to turn the LEDs On or Off. We want the LEDs to turn on when the light level on the meter is below a certain value. We can choose any value.

Remove the [set brightness] block from the loop and set it to one side.

code block removed

Go to the Logic section and find the [if True then] code block.

code block selected

Place the condition statement inside the loop and below the [show icon] code.

code block attached

The condition statement looks for a condition to be True.

We want the condition statement to look at the light level information. If the value from the meter is less than a certain value, we the LEDs to turn on. If the value is greater than a certain value we want to turn the LEDs Off. We can choose any value to trigger the switch.

We need a way to store this value and pass it into the condition and parameters later. The value will be stored in a Variable.

Go to the Variables section and click the "Make a Variable" button.

make variable button

Set the name of the variable to “light trigger” and click the OK button.

variable name

Variable code blocks are created. Get the [set variable to…] code block.

set variable code block

Place the code block into the [on start] section. You might need to move the code blocks around.

code in on start code block

Enter 100 into the variable parameter. This assigns 100 to the variable. The value is assigned when the Micro:bit turns on or is restarted.

This is our value to turn the LEDs On or Off.

variable parameter changed

Go to the Logic section and into the Comparison blocks. Look for the [less than] cod block.

less than code block selected

Place the code block into the condition parameter.

less than code block in place

Get the [light trigger] variable and place it into the right side of the [less than] parameter.

light trigger variable in place

Get the [light level] input and place it into the left side of the [less than] parameter.

light level in parameter

Get the [set brightness] code block we set aside earlier and place it into the condition statement.

adding code block

Remove the [light level] code from the [set brightness] parameter.

removing code

Take the code to the Codes section to remove it from the coding area.

removing code

If the light level is less than the light trigger, 100, we want the LEDs to turn On. The brightness value is already set at 255. This is the maximum brightness. This takes care of turning the LEDs On.

brightness parameter value

We need to follow the same process for turning the LEDs Off. The process is just reversed. The condition statement turns the LEDs Off when the light level is greater than the light trigger.

Right-click on the condition statement; select the duplicate option.

duplicate option

Place the duplicate below the first condition statement.

code in place

Click the comparator selector; choose the greater than comparator option.

selected operation

Change the brightness level to 0.

brightness level set

Move the light sensor meter to a value less than 100; the icon lights to full brightness.

adjusting brightness

Move the meter to a value greater than 100; the icon turns off.

brightness meter

The light trigger might be too high or low. Change the value in the light trigger variable to 50 or 150. Choose a value of your own.

light trigger variable set to 50
Read More
Micro:bit Alex Micro:bit Alex

Micro:bit accelerometer Introduction

The Micro:bit has a variety of sensors. One of these sensors includes an accelerometer. The accelerometer is behind the B-button. A label on the Micro:bit behind the buttons points to the motion sensor.

The word accelerometer might make you think that it measures acceleration. The accelerometer measures motion. The motion comes from lifting or rotating the Micro:bit.

The accelerometer measures motion in three different directions. It measures motion when the Micro:bit is moved side to side or up and down.

Micro:bit accelerometer basics

Microbit accelerometer

The Micro:bit has a variety of sensors. One of these sensors includes an accelerometer. The accelerometer is behind the B-button. A label on the Micro:bit behind the buttons points to the motion sensor.

The word accelerometer might make you think that it measures acceleration. The accelerometer measures motion. The motion comes from lifting or rotating the Micro:bit.

The accelerometer measures motion in three different directions. It measures motion when the Micro:bit is moved side to side or up and down.

We need a frame of reference when we talk about the motion. Look at the Micro:bit with the contacts facing down. Use the image below as a reference. Place the Micro:bit on a flat surface.

Moving the Micro:bit from left to right is moving along the x-axis.

Micro:bit image

Moving the Micro:bit up and down is moving it along the y-axis.

Micro:bit image

Lifting the Micro:bit from the surface is moving it along the z-axis.

The accelerometer measures motion. It measures motion in varying degrees from slight motion to extreme motion. The accelerometer also uses gravity to determine the direction of motion. Motion is not just from side to side or up and down. Rotating the Micro:bit is also considered motion. We are going to focus on rotating the Micro:bit in this lesson.

You don’t need to have a Micro:bit to learn about the Micro:bit. Microsoft provides a free online Micro:bit simulator. No login account is required. Use the link below to access the simulator.

The simulator is also the environment we use to create code for the Micro:bit.

https://makecode.microbit.org

Measuring motion

The best way to understand the motion sensor is to watch it in action.

Click the New Project button.

new project button

Use “accelerometer basics” for the project title; click the Create button.

project title

The simulator places two code blocks on the canvas for every new project. The Start code runs code when the Micro:bit starts or is reset. The Forever code is a loop that repeats instructions for as long as the Micro:bit is powered.

basic code blocks

We don’t need the [on start] code. Drag it to the code panel.

code being removed

Select the Basic codes section.

code section selected

Drag the [Show number] code block and insert it into the Forever loop.

code block inserted

Select the Input section.

section selected

Find the [acceleration] code block.

acceleration code block

Place the acceleration code block into the [show number] parameter.

code block inserted

The [acceleration] code has three measurement options. Click the Axis selector. The other axis options include the y and z-axis. Leave the selector set to the x-axis.

axis selector

The simulator shows a big fat zero. The Micro:bit is not moving in any direction. The simulator shows the value for the axis below the B-button.

This is not true in the actual physical Micro:bit.

x-axis value

Move your mouse pointer over the Micro:bit simulator; place it over the right edge. The LEDs on the Micro:bit begin to scroll to display the value of the acceleration. The value is also displayed below the B-button. The extreme value and the largest value we can get is 1023.

value in Micro:bit display

Move the mouse pointer to the left side of the Micro:bit. The measurement is -1023 at the extreme value.

negative value displayed

The value 1023 is the largest value we can get when measuring acceleration. This isn’t how fast the Micro:bit has moved. It measures the amount of movement from the center of the Micro:bit when it was laying flat.

Imagine the Micro:bit is laying flat. The image below is in a coordinate plane with x and y-axis lines.

illustration of Micro:bit

Tilting the Micro:bit to the right increases the motion to the sensor. The measurements go up to a maximum of 1023.

illustration tilted to the right

Tilting the Micro:bit to the left increases the motion sensor. This time, the readings are in the negative range from 0 to -1023.

illustration tilted to the left

The numbers are represented with negative values because of the coordinate plane. Numbers on the left side of a coordinate plane are negative.

Return to the coding canvas. Select the y-axis in the acceleration code.

y-axis selected

Place the mouse cursor over the top center of the Micro:bit. The y-axis value is -1023.

value displayed on Micro:bit

Move the arrow to the bottom center of the Micro:bit. The value is positive.

Micro:bit tilted with value displayed

Move the cursor around the Micro:bit simulator. The numbers displayed range from 0 to 1023 depending on where you place the arrow.

X and Y-Axis measurements

We can get both x and y-axis measurements at the same time. Right-click the [show number] code and select the Duplicate option.

duplicate option

Place the duplicate below the original.

code attached

Change the axis of the first to the x-axis.

axis changed

On the simulator, we see information for both the x and y-axis.

values for both axis

Place the mouse arrow over the right edge of the simulator. The Micro:bit displays one value for the x-axis and one for the y-axis.

axis values changing

Accelerometer and input

The accelerometer is an input device. It is also a sensor. It takes information from the surroundings and interprets that information for the Micro:bit to use. We use that interpreted information to react to the input.

Remove both [show number] blocks from the Forever loop.

removing code block

Go to the LED section and find the [plot bar graph of…] code block.

code section

Place the code block inside the Forever loop.

code block inserted

Go to the Input section and get an [acceleration] code block. Place it into the first parameter.

attached code block

The bar graph code block creates a bar chart from the information passed into it by the acceleration code. The acceleration code receives information from the sensor. This information is in the form of numbers ranging from 0 to 1023.

The second parameter in the bar graph code block needs the maximum number we want to use in the bar graph. We can choose any number from 0 to 1023. Enter 1023 into the parameter.

value updated

Place the pointer over the center of the Micro:bit simulator. Move the arrow to the right, slowly. A bar chart will gradually form and eventually fill the Micro:bit.

chart forming

Move the pointer to the left side of the Micro:bit. The same chart is created. The chart is created even if the values are negative. The Micro:bit is taking the absolute value of the reading and creating the chart. The absolute value for the readings is positive.

negative value displayed on Micro:bit

Making decisions

Computers don't think and reason on their own. We can help them make decisions based on the parameters we choose. We will use a condition statement to prevent the Micro:bit from creating a chart when the values are negative.

Go to the Logic section and find the [if True then] code block.

condition code block

Place the condition code block inside the loop.

code inserted

Move the [plot bar graph] code block inside the condition block.

code moved into position

The condition statement checks to see if a statement is True or False. The parameter is set to look for a True statement. We need to provide the statement to verify.

Go to the Logic section and find the Comparison operators.

section selected

Place the [Less than] comparison operator into the condition parameter.

comparator block inserted

Click the comparison selector and choose the “Greater Than” option.

option selected

Right-click the [acceleration] code and select duplicate.

duplicate option

Place the [acceleration] code into the left parameter of the comparator.

code inserted

The code explained

The condition compares the value from the accelerator to the number in the right parameter. If the value from the accelerometer is greater than zero, True, then it will run the code in the condition. It will plot the bar graph. If the value is “Less Than” zero, False, then the Micro:bit will not plot the graph. False in this sense means that the value from the accelerometer is not greater than zero.

Test the code

Rotate the Micro:bit to the right; it will plot a bar graph.

chart plotted

Rotate the Micro:bit to the left; it will NOT plot a bar graph.

not chart plotted

Acceleration to control Input

The bar graph is plotted as we rotate the Micro:bit. If you rotate the Micro:bit slowly, you will see the graph plotted gradually. We can use the same principle to control almost any input to a program.

The following code uses the [acceleration] code information to control the brightness of the LEDs on the Micro:bit.

Remove the Condition code with the graph plot from the Loop. Set it to one side.

removed blocks

Go to the Basic code section. Get the [show icon] code block and place it into the loop.

code block inserted

Go to the Led section and into the More option. Find the [set brightness] code block.

code block in section

Connect the [set brightness] code block to the [show icon] code.

cod inserted

Get an [acceleration] code block and place it into the [set brightness] parameter.

code block inserted

Rotate the Micro:bit gradually to the right. The LEDs will get brighter as the number increases. Rotate it to the left and the LEDs will dim. The LEDs do not get bright again if we rotate the Micro:bit to the far left. The brightness code block already understands we can’t brighten something with negative values.

Read More
Coding, Scratch Alex Coding, Scratch Alex

Multiple character dialogue with Scratch

This lesson explores the use of Scratch to create multiple character dialogue. Dialogue between two characters is relatively simple. Adding more characters makes it difficult to control the flow of the conversation. I expand on a previous lesson

scratch-multiple-character-dialogue.jpg

Multiple character dialogue

Introduction

This lesson expands on a previous lesson. The link to that lesson is below. In that lesson, we used a list to provide the dialogue for the Sprites. I want to explore the options for using lists with multiple characters and dialogue between those characters.

This lesson is much longer than I expected. There were so many things I wanted to include that I thought the instruction would suffer if I removed parts of the lesson to make it shorter. The aim is to provide the instruction in the context of an overall project. I don’t care for teaching content in isolation.

The lesson is a mix of scene transitions, animation, and dialogue. This is done to preserve the context of the project.

The project develops naturally like a programmer developing a product. Programming is a series of iterations toward the development of a completed product.

Use the link below to view the completed project. Use the completed project to compare your code if something doesn’t work.

Final multi-character dialogue project

I have a base Scratch project available to begin the lesson. This project was developed in earlier lessons. Use the link below to access those lessons.

Interactive presentation with Scratch

Interactive stories with lists

Use the link below to get a copy of the base project for this lesson.

https://scratch.mit.edu/projects/480221619/

The base project has an actor and a background scene. The code in the project generates some dialogue between the actor and the audience. The actor interacts with the audience and is prompted to respond to questions. The actor, in turn, responds to the input from the audience.

Click the Green Flag button to go through the program.

Transitioning actors

The background remains the same in the project. The actor’s transition in and out of the scene. This keeps things simple and follows the theme of the project.

The actor is in the position where we want him to communicate with the audience. The diver will not begin here when the program starts. He will move into position from above the aquarium window.

diver and aquarium backdrop

Go to the Motion section; find the [Glide to x:… Y:…] code block.

glide code block

Place the code block on the canvas next to the main code. The code contains the current position of the Sprite.

glide code block on canvas

Go to the stage and move the diver to the top. Move it as far as you can.

You will not be able to remove the sprite from the stage. Sprites must be attached to the stage; there will always be some part of the sprite on the stage.

diver sprite moved to top of stage

We can force the sprite to move off the stage as far as possible.; go to the Sprite settings section. Click inside the “y-coordinate” field.

y-coordinate field value

Type 400 and press the Return key.

value in y-coordinate field

Scratch places the sprite at the maximum allowable edge for the sprite. Each sprite has its maximum. The maximum is based on the size and shape of the sprite. It is also based on the sprite’s center.

y-coordinate value

There is still some part of the sprite visible. We will take care of this later with some code.

fin of diver suit at top of stage

Go back to the Motion section; find the [go to x:… y:…] code block.

go to code block

Place the code block on the canvas. Don’t connect the blocks yet.

code blocks on coding canvas

This isn’t the only sprite to place in position. Each actor needs to be reset at the beginning of the program.

Disconnect the base code from the Green Flag.

code disconnected

As the code gets longer, it makes sense to divide the code into manageable chunks. I used a similar process in the lesson where the actor communicated in several languages. That lesson is available using the link below.

We are going to use the Broadcast code blocks.

Multiple language dialogue Scratch projects

Go to the Events section; look for the [broadcast message] block.

broadcast message block

Attach the block to the Green Flag.

block connected

Click the message selector and choose New Message.

new message option

Title the message “Reset actor positions” then click the OK button.

message name field

Place a [When I receive message] code Hat on the canvas.

receive message hat block

Choose the [Reset actor position] message.

message selected

Get the [go to] code block on the canvas and connect it to the [When I receive message] block.

code blocks connected

Go to the Looks section. Get the [Hide] code block and connect it to the [go to] block.

code block connected

Go to the Control section; place a [wait 1 second] code after the [Broadcast] code.

code block connected

Go to the Events section; connect a [Broadcast] block after the [Wait] code. Create a new message.

new message option

Set the name of the message to “Welcome message”.

message name field

Place a [When I receive message] Hat on the canvas then select the Welcome message.

hat block on canvas

Connect a [Show] block from the Looks section to the message Hat.

show block connected

Connect the [Glide] code to the [Show] block. Change the Glide time to 5-seconds.

parameters in code updated

Connect the blocks to the main code.

main code blocks connected

This is what. is going on so far. When the green flag is clicked, a message is sent to the Reset blocks. The sprite is placed outside the stage area and hidden. One second later, the welcome message is sent. The code connected to the Welcome message Hat block is executed.

Click the green flag to run through the program.

three code block sections

More actors

We need more actors in the presentation. Use the link below to download a Zip folder. Extract the contents of the folder. Inside you will find three Sprites.

Scratch sprite files

scratch sprite files in folder

Return to the Scratch project. Choose Upload from the Add Sprite options.

upload scratch option

Select all the Sprites in the folder then click the Open button.

selected sprite files

Select the Fun Diver sprite then click the Hide button.

sprites and hide button

Select the Martha Diver sprite and hide it too.

sprites and hide button

Go ahead and hide the Diver sprite too. Leave the Alex Diver visible.

diver sprite visible

Select the Alex Diver and set the x and y coordinates to -124 and -45.

coordinate positions in fields

Place a [Glide…seconds to x:…y:…] block on the canvas.

glide code block

Change the “y-coordinate” value to 400.

y-coordinate value in field

Place a [go to x:…y:…] block on the canvas. Don’t connect it to the other block yet.

code block on canvas

Connect a [Hide] block to the end of the [Go to] block. Place the [Glide] block alongside the [Go to] block.

code block connected

Connect a [When I receive message] Hat block to the [Go to] block. Select the “Reset actor positions” message.

This uses the existing message to pass a message to this sprite.

reset code blocks

Select the Martha Diver sprite then click the Show button. Place the sprite at the coordinates 104 and -26.

coordinates

Go to the Motion section. Place a [Glide…seconds to x:…y:…] block on the canvas.

code on canvas

Enter 400 for the y-coordinate and press the Return key. 

value in coordinate field

Place a [Go to x:…y…] code block next to the Glide block.

code blocks on canvas

Connect a [Hide] block to the end of the [Go to] block. Connect a [When I receive message] block to the beginning.

code block connected

The code for the actors to clear the stage is complete. We will use the same code for new actors in the future.

The script

The actors need a script to follow. The scripts can be created with any word processor. I use Google Docs to develop the scripts for each diver. Use the link below to get a copy of Alex Diver’s script.

Alex Diver’s script Google Document

The script has five lines of introductory text. Each line represents a separate sentence displayed by the character. The sixth line is a Cue Marker. This is something I came up with to Cue the next actor. The cue begins with a hashtag followed by the actor’s name. You will see how this works in the code later. We will return to add more content to the text later.

Creating a script for Scratch is simple. There is one rule that you need to follow. Don’t use commas. A comma is a delimiter. Delimiters are separators for columns of information in a CSV, Comma Separated Value, file. The Scratch list is one column so it cannot import something that might have two or more columns. We will add commas where needed after the text is imported.

The document needs to be exported as a Plain Text file for import into a Scratch list.

script text

Click File in the menu then go to the download option and select the Palin Text option.

download plain text option

Return to the Scratch project tab. Go to the Variables section and click the Make a List button.

make a list button

Set the list name to “Alex’s script” and click the OK button.

script list name field

The list is created and placed on the stage.

list panel on stage

Right-click on the list and select Import.

import list option

Find the plain text file and open it.

plain text file

The contents of the text file are loaded into the list. Each line is a separate item.

script items in list

Drag the lower right corner to resize the list width.

widening list panel

Click inside the first item. Add a comma after the word Hello.

comma added to first item

Go to the Variables section and click the “Make a Variable” button. The variable will keep track of the lines read by the actors.

make a variable button

Use “Script item” for the variable name.

variable name

Place a “Script item” variable on the canvas. Place a [Set variable and a Change variable] block on the canvas. Don’t connect the blocks to anything. We are placing the blocks here to reduce the number of trips to this section.

blocks on canvas

blocks on canvas

Connect the [Set variable] to the Glide code. Use the Variable selector to choose the “Script item” variable.

variable selected

We want the program to cycle through each line in the script until it reaches the next actor’s Cue.

Go to the Control section. Get a [Repeat Until] loop and connect it to the [Set variable] code.

code attached

Go to the Operators section. Place an [Equality] operator into the loop parameter.

An Equality operator checks to see if the value on the left matches the value on the right. It does not assign one value to the other.

equality operator connected

Go to the Variables section; scroll to the List code blocks. Find the [Item…of List] code block.

code block in section

Place the code into the left side of the [Equality] operator.

code in parameter

Make sure the list is set to “Alex’s script”.

item with list selected

Right-click the [Script item] variable then select the Duplicate option.

duplicate option

Place the variable into the [List item] parameter.

variable in parameter

Type “#Martha” into the right side of the [Equality] parameter.

value in parameter

Let’s take a break to review what is going on up to this point. The loop will go through each item in the list, Alex’s script, until it finds the item “#Martha”.

Add the [Change variable] code to the loop. Select the “Script item” variable.

variable selected

Go to the Looks section. Get a [Say…for…seconds] block and place it in the loop. Place it after the [Change] code.

code connected

Right-click the [Item…of List] code block and select Duplicate.

duplicate option

Place the code into the [Say] parameter.

code in parameter

Go to the Variables section and remove the checkmark from “Alex’s script”.

checkmark removed

Click the first line of this code to test it.

testing code

The actor on the stage goes through the lines in the list. We left the variable display on the stage to see each script item number as it is displayed.

Displaying the variable on the stage is one way to make sure everything is going well. It is also a method to find bugs in your code.

program running with Alex diver

At the end of the loop, we see the cue for Martha appear in the dialogue box. This cue should not appear.

Let’s take a look at what is going on. The loop begins with zero and one is added to the variable at the beginning. The first line of dialogue is executed. On the next iteration, it is incremented by 1 and the second line of the dialogue is read.

When we get to the fifth line, the loop returns and adds one more; line 6 is read. It has to be read because the loop has not finished yet.

To prevent the reading of the sixth line, we need to increment the variable after the line is read. For example, the variable is incremented by 1 after the fifth line to get 6. This is the end of the loop and the line is not read at the beginning of the loop.

I dove a little deeper into this concept because students often have a difficult time understanding this process. We walk through the process in class. I think it is an excellent way for students to understand some process and sequencing skills.

Get the Say block and place it at the beginning of the loop.

block added

Run the lines of code again. The Martha cue is not executed.

Add a Show block to the beginning of the code.

code blocks

We don’t need the variable to display on the scene. Go to the Variables section and remove the checkmark from the variable.

checkmark removed

checkmark removed

Transition actors

We have one of the divers ready to appear when a visitor wants a tour. We need to transition the first diver out of the scene. The first diver will exit the scene if the visitor responds yes or no. The second diver appears only if a visitor responds with a yes.

Select the first diver sprite.

diver sprite selected

Click the green flag to start the program. Wait until the diver stops moving down and click the Stop button.

sprite coming down stage

The diver’s exit is taken care of with two blocks of code. Those blocks of code will be in a separate function.

Go to the My Blocks section; click the Make a Block button.

make a block button

Set the name of the block to “Diver exit” and click the OK button.

block name

Place the Hat block with the other blocks. Keep things organized.

hat block on canvas

The diver needs to float to the top of the stage. Connect a [glide 1 secs to x:…y:…] code block.

connected code block

The destination coordinates need to be updated. The coordinates point to the diver’s current position on the stage. The destination coordinates are in the Reset function. The coordinates are -86 and 337. Enter these coordinates into the Glide x and y parameters. Change the glide time to 5-seconds.

block with updated parameter values

Connect a [Hide] block to the Glide code. This part of the code is complete.

connected code block

Move the coding canvas to display the bottom of the main code.

bottom of main code

Go to the My Blocks section. There is only one block in the section. This block calls the Hat block. It is like using the Message function.

code block in section

Place a [Diver exit] block after the [Say] block in the If section for when the guest answers Yes.

code block connected

Place a [Driver exit] block after the [Say] block in the If section where the guest answers No.

block connected

Return to the Yes portion of the condition statement. Place a [Broadcast message] block after the [Diver exit] block and create a new message variable.

create message variable

Set the message name variable to “Alex Cue”.

variable name

When the guest enters Yes, the Alex Diver sprite is cued.

cue code broadcast

Select the Alex Diver sprite.

selected sprite

Place the [When I receive message] Hat at the top of the code. Make sure the Alex cue message is selected.

code connected

Test the code

Click the green flag and run through the program. Answer Yes to watch the Alex Diver sprite appear on stage.

The Alex Diver sprite is gliding too fast; change the glide time to 5-seconds.

updated glide time

Cue Martha Diver

It’s time for Martha to make an appearance. Place a Broadcast block after the loop. Create a new message. Set the name to “Martha Cue”.

new message option

Select the Martha sprite. This sprite needs code for the conversation. The code is the same as that used for the Alex Diver sprite.

sprite code canvas

Select the Alex Diver sprite. We are going to copy the code to the Martha Diver sprite.

cue code in Alex Diver sprite

Grab the first code block and drag it to the Sprites section. Drag the code over the Martha Diver sprite and release.

code over Martha diver sprite

Switch to the Martha Diver sprite.

code in sprite canvas

The code is probably covering the other code. Move the code around so they are all visible.

code rearranged on canvas

We need to update the parameters in this code. The sprite needs to glide into a different position. Get the glide coordinates from the glide code we captured in the beginning. Enter them into the main glide code parameters.

updated glide parameters

We don’t need the glide code block anymore. Drag it to the codes section.

removing code

This sprite code is using the same variable counter used in the Alex Diver sprite. This sprite needs a separate variable to keep track of its list items.

code with original variable

Go to the variables section. Right-click the Script item variable and select Rename variable.

rename variable option

Add Alex to the beginning of the variable name and click OK.

updated variable name

Click the Make a Variable button.

make variable button

Use “Martha Script item” for the variable name.

variable name

Use the variable selector to change the variable to Martha’s script item.

select variable name from list

Repeat the process for all the variable selectors used in the Martha Diver sprite.

updated variables in set and change code blocks

We need to replace the Alex Script item variable with the Martha Script item. Drag the Martha Script item variable over the Alex Script item variable.

variable over other variable to replace

Repeat the process for the other variable. Remove the Alex Script item variables from the canvas. They might be hiding under the code.

replaced variables

Martha Diver Script

The code is referencing Alex’s script. Martha has her script. Use the link below to get a copy of the Google Doc with the script. The text includes a cue at the end for the Alex Diver sprite. The sentences do NOT contain COMMAS. We will add those later. Download the document as a Plain Text file.

Martha Diver’s script Google Document

script text

Go to the Variables section and click the Make a List button.

make a list button

Use “Martha’s script” for the name.

list name

Right-click the list name and select the import option. Find the plain text file and open it.

import option

Expand the list and place commas in item five.

expanded list

Remove the checkmark from the list name.

checkmark removed

Use the list selector in the loop parameter to select Martha’s script.

script list selected

Repeat the process for the other list parameters.

other parameters updated

Change the #Martha cue to #Alex.

parameter updated

Change the Broadcast cue to Alex cue.

broadcast message changed

Change the message Hat Alex cue to Martha cue.

receive message changed

Click the green flag and run through the program.

The program will go through Alex’s script and then through Martha’s script. Martha will broadcast to the Alex sprite at the end. Stop the program.

Continuing the conversation

Let’s update the script to continue the conversation. Open the Alex Diver script Google document.

Add your text to the script. I have some text here for you to use if you would rather use mine.

Thank you Martha
I am an Oceanographer.
I study marine life, marine ecosystems, and the geology of the seafloor.
#Martha

Export the document to a plain text file.

Place a checkmark on Alex’s script list.

checkmark on list

Right-click on the list and select import.

import option selected

The contents of the list are replaced by the imported text. Hide the list.

imported list items

Cycling through the conversation

Right-click on the loop and select duplicate.

duplicate option

Place the loop to one side of the current program.

code set to one side

Click the broadcast selector and create a new message.

create new message option

Set the name to “Martha dialogue”.

broadcast message name

Place a [When I receive message] Hat at the beginning of the code. Create a new message.

new message option

Use “Alex dialogue” for the message name.

message name

Select the Martha Diver sprite.

sprite selected

Right-click on the loop and select Duplicate.

duplicate option

Place a [When I receive message] Hat on the code. Choose the Martha dialogue message.

Martha message selected

Go to the Broadcast block; select the Alex Dialogue message.

message selected

Go to the Broadcast block at the end of the first code. Change the message to Alex Dialogue.

message selected

What did we just do?

We have code that will allow us to jump back and forth between sprites with dialogue. These blocks of code will take over after the first cue of each sprite.

The Martha Diver sprite will call the Alex dialogue after the Martha cue is done. The code in the Alex Diver sprite will call the Martha Dialogue after it is done.

We don’t have to add any more lines of code to extend the dialogue between these two sprites.

Click the green flag and run through the program.

Everything works fine until It is Alex Diver’s turn to speak. The program seems to stop.

Debugging

The bug is in the loop. Place a checkmark on the Alex Script item variable.

checkmark on list

Place a checkmark on Alex’s script list.

checkmark on script

Run through the program again. The script stops at item 6. The item on the list at the sixth position is the #Martha cue. The cue is part of the loop instruction to Stop.

items 6 in variable and on list

The program needs to move to the next line before the loop begins. Right-click the [Change] code block and select duplicate.

duplicate option

Place the code before the loop.

code added before loop

Select the Martha Diver sprite. Perform the same process on the code for this sprite.

code connected

Hide the list and the variable. Click the green flag and run through the code again.

More Martha Diver dialogue

We are introducing one more actor. Open the Martha Diver script Google Document. Add the text below to the document. Download it as Plain text and import it into the Martha list.

We have one more person to introduce.
Larry will help round up the animals for the presentation.
Say hello to our guests Larry.
#Larry

text in google document

Larry has his own set of dialogue. Use the link below to download the actor’s dialogue.

Larry’s script Google Document

More actors

Up until now, the dialogue between two actors has been an easy back and forth. When another actor enters the conversation, we need to make decisions as to which actor will respond. The Script provides the best direction for the conversation.

Disconnect the Broadcast block in the Martha Diver sprite and place it to one side.

broadcast code disconnected

Go to the Control section and find an [If…Then…Else] block. Connect it to the end of the code.

code connected

If the script cue calls for an actor, we need to make sure the appropriate actor is sent a message. We need a parameter to look for the actor’s cue. We already have that parameter in the Equality operator. Right-click the Equality operator; select duplicate. Make sure you right-click on the Equality operator—the green block— to copy the embedded parameters.

duplicate option

Place the Equality operator inside the condition parameter.

code in parameter

Place the Broadcast code we set aside earlier into the “If” section of the condition.

code in section

Go back to the Control section and place an [If…Then] code block into the Else section.

code inserted

Duplicate the Equality operator and place it into the If parameter.

code in parameter

Make a copy of the Broadcast code and place it into the If section.

code in section

Update the nested If condition. Change the #Alex cue to #Larry.

parameter updated

Click the Broadcast selector and create a new message. Set the name of the message to “Larry Dialogue”.

new message option

If the script calls for the Alex Diver sprite, the Condition will use the Broadcast code to send the cue to the Alex Diver sprite. If the script calls for the Larry Diver, then it will call the Larry Diver sprite.

conditions in code

We can’t look for just one actor. We need to look for a call to any actor. All actor cues begin with the hashtag. We will use that for our cue to any actor.

Remove the Equality operator from the loop. Place it to one side.

code set to one side

Go to the Operators section. Find the [Contains] operator and place it into the loop parameter.

code over parameter

Remove the [item…of list] from the Equality operator we removed. Place it into the [Contains] operator.

code in parameter

Type the hashtag into the other side of the Contains operator.

hashtag in parameter

The operator looks at the current list item to see if it contains the hashtag symbol. If the line does, the loop exits. Just like it did before when we looked for a specific cue like #Alex or #Martha.

We couldn’t use the Equality operator because it requires that the list item and the value match exactly.

Remove the Equality operator; we don’t need it anymore.

removing operator

This code needs to be applied to other code blocks that reference dialogue between actors. We are going to update the Martha Cue code.

the code

Remove the Broadcast code.

code removed

Right-click the condition block in the code; make a duplicate. Connect the duplicate to the Martha Cue code.

code connected

Remove the Equality operator; delete it, we don’t need it.

operator removed

Duplicate the [Contains] operator. Place the code into the loop.

code in loop parameter

This updates the Martha sprite. We need to provide the same code for all sprites.

Streamline the cueing process

The condition statement needs to be repeated when an actor needs to say a line. This leads to lots of duplicate code when we add more actors. We should reduce the number of code blocks whenever possible. This is a good opportunity to create a code block to call when needed.

Go to the My Blocks section. Click the Make a Block button.

make block button

Set the block name to Dialogue cue.

block name

The Hat block is placed on the canvas.

hat block on canvas

Get the condition statement from the Martha Cue code and connect it to the Dialogue cue Hat.

code connected

Get the Dialogue cue block from the Make a Block section; connect it to the end of the Martha cue code.

code connected

Disconnect the condition code from the Martha dialogue code and delete it.

code removed

Connect the Dialogue cue code to the end of the Martha dialogue code.

code connected

We have a code function that broadcasts a message to the relevant actors. To make this code universal we need to include all the possible actors.

Go to the Control section. Get an [If…Then…Else] code block. Connect it to the Dialogue cue Hat block. The other code will enclose itself within the condition.

code being added

Move the nested If condition from the If section to the Else section.

code being moved

Duplicate the Equality operator. Place it into the main If condition parameter. Change the value from #Alex to #Martha.

code moved

Duplicate the Broadcast block. Place the block into the If section; change the message to “Martha dialogue”.

broadcast code in place

The Martha Diver is not likely to call itself in a code. We are creating a function to call regardless of the actor called in the script.

Updating the other Sprites

This code needs to be part of the other sprites. Grab the Hat code block and drag it to the Sprites section. Release the code over the Alex Diver sprite.

code over sprite

Click the Alex Diver sprite. Check to make sure the code was copied. Arrange the code blocks to see them all on the canvas.

code arranged

Go to the Alex Dialogue code blocks and remove the [Broadcast] code. Connect a [Dialogue cue] code.

code connected

Set the [Equality] operator from the Alex Cue loop to one side.

code set to one side

Place an [Contains] operator into the loop parameter.

code in parameter

Place the [Item] code from the Equality operator into the left side of the [Contains] operator.

code in parameter

Type the hashtag into the right side of the operator. Remove the [Equality] operator from the canvas.

updated code

Repeat the process for the Alex Dialogue code.

code updated

Now we need to update the Dialogue cue for the parameters in the Alex Diver sprite.

Remove the Martha Script item variable and trash it. Repeat the process for all the Martha Script item variables.

removing variable

Place the Alex Script item into each Item parameter.

variable added

Click the List selector for each Item and select Alex’s script.

list selected

Stop and test

We have made several changes and updates to the code. This is a good time to stop and test the program. Make sure everything is working correctly.

You might find that things don’t work correctly. This is part of the coding process. Finding mistakes is difficult and tedious. I don’t like looking for these bugs myself but they are part of the learning process.

Use the Scratch project I shared with you to compare your code.

Introducing Larry

It is time for the last actor, Larry. Select the Fun diver sprite; change the name to Larry.

sprite name changed

This sprite will use the same code used by the other sprites. Return to the Martha Diver sprite. Find the Martha Dialogue code. Drag the code over the Larry sprite.

code over sprite

Get the [When I receive message] code and add it to the Larry sprite in the same way.

Hide the Martha Diver sprite. Go to the Larry sprite. Arrange the code blocks on the canvas.

Create a new list for Larry.

Set the list name to Larry script.

Import the plain text file into the list. Don’t hide the list yet.

Go to the [When I receive] code and choose the Larry Dialogue message.

message selected

We need a variable for the Larry dialogue. Go to the Variables section. Create a new variable; name the variable “Larry script item”. Update the [Change] variable to the “Larry script” item variable.

change code updated with variable

Replace the “Martha Script item” variable with the “Larry Script item” variable.

updated variables

Update the lists to “Larry script”.

updated lists parameters

Update the Dialogue cue code. Replace the Martha script variables and lists with those for Larry.

updated variables

Larrys appearance

Larry needs to make an appearance. Place a [Go to x:…y:…] code block after the [When I receive message] Hat. Set the values to 424 and 20.

updated message

Pace a [Glide…secs to x:…y:…] block after the [Go to x:…y:…] code block. Set the time to 2-seconds. Set the coordinates to 212 and 24.

code connected and parameters updated

Place a [Glide…secs to x:…y:…] code block after the loop. Set the glide time to 3-seconds. Set the x and y coordinates to -424 and 24.

code connected and parameters updated

Update the reset position code. Set the x and y coordinates to 424 and 24.

code coordinates updated

Place a [Show] code block after the receive message Hat.

code connected

Larry doesn’t have a cue like the other actors. We need to set the list item variable to zero. Get a [Set variable] code block and connect it to the Hide code. Set the value to zero.

set code added

Click the green flag and run through the program. Fix any bugs. Use the shared project to check your code.

The final line of the Larry script is just a hashtag. Continue the script process with your own dialogue.

Read More
Coding, Scratch Alex Coding, Scratch Alex

Text Sprites for Scratch Projects

In this lesson, we are creating text sprites for use in Scratch projects. The Sprite and Backdrop design tools in Scratch are basic. Scratch has some tools to create basic shapes, drawings, and text. The text option has a handful of fonts.

text elements for Scratch projects with Vecteezy

In this lesson, we are creating text sprites for use in Scratch projects. The Sprite and Backdrop design tools in Scratch are basic. Scratch has some tools to create basic shapes, drawings, and text. The text option has a handful of fonts. If we want some text with different fonts we need to go to other applications. That is the focus of this lesson.

Many applications are capable of creating text for use in Scratch. My focus is on text tools that support SVG export.

I prefer Scalable Vector Graphic, SVG because they look better and provide some benefits when imported into Scratch. One of the benefits is that we can manipulate the fill and border color.

The tool chosen for this lesson is based on three criteria. The tool must be easy to use. It must be online. Finally, it must be free.

The tool we are using in this lesson comes from Vecteezy at vecteezy.com. The tools in Vecteezy are easy to use. It exports images and text in the SVG format. The text tool many font choices.

Resources

Use the link below to get the basic Scratch project; make a copy of it. This is a base project from which we are developing an overall project.

https://scratch.mit.edu/projects/480221619

Vecteezy

Open another tab in your browser and go to vecteezy.com. Vecteezy is free and offers a free account. Vecteezy integrates with Google and Facebook login services. I encourage you to create a free account. In this way, you will be able to save projects for later.

Click the Start Designing button.

start button in vecteezy

Vecteezy generates and displays a sample illustration with each new project.

design in project desktop items

Click the File menu option and select Clear.

menu option to clear

Click the Type tool.

type tool

Double-click on the canvas to get a text box.

text box

Drag the lower right resize handle to enlarge the text box.

enlarged text box

Click once inside the text box and type “Alex’s Aquarium”.

selected contents of text box

Click once outside the text box to exit edit mode.

selected text box

The font options are in the Typeface section. The default font is Open Sans.

default font in typeface section

Click the font selector and choose the Aladin font. This is my choice; you can choose any font you want.

selected font

This is the text for our project; nice and simple. We will come back and do more later. Place the text box as close to the center of the canvas as you can. This will make it easier to work with when imported into Scratch as a Sprite.

updated banner with font choice

Click File and select Save for Later.

save for later option

Close the confirmation message. Click File and select Download SVG. The file is downloaded to your computer. Make sure you remember where it is.

download SVG option

Switch to the Scratch project tab. Hover over the create Add Sprite button; select Upload Sprite.

upload sprite option

The SVG file is probably named “Untitled”. Vecteezy was still in Beta when I created this lesson. They might have fixed this issue by the time you are working through the lesson.

Select the SVG file and click Open. Click in the Sprite name field. Change the name to “aquarium banner”.

sprite name field

Select the Costumes tab.

costumes tab

The text should be somewhere near the center of the Sprite canvas. Move the text and align it to the center of the canvas. Use the center guide to help you align the text.

text centered on canvas

Position the sprite on the stage. Place it above the diver's head and center it on the stage.

text banner on stage

Formatting the text

Return to the Costumes tab; select the vector text. Click the Fill color selector. Move the Saturation and Brightness sliders all the way to the right.

fill color controls

Move the color slider to select a color. Select any color you want. Mine is light green. Click away from the color selector to apply the color.

color slider

The text color updates on the stage.

updated banner color

Neon banner

We can use the Scratch tools to create some interesting effects for the banner. Let’s give the banner a neon glow.

Set the costume name to Costume1.

costume name field

Right-click on the costume thumbnail; select the duplicate option.

duplicate option

Select the text box in Costume2.

selected vector text

Change the Outline width to 5.

outline width field

Click the Outline color selector. Choose a lighter version of the color chosen for the text. Move the Saturation slider to the left to get a lighter color from the original. Click away from the color picker to apply the changes.

saturation slider

Look at the effects on the stage. The text should have a border around each letter.

text with border

Neon effect

Select the Code tab. Place a Forever loop from the Control section on the stage.

forever loop

Go to the Looks section; place the —Next Costume— code block inside the loop.

code in loop

Return to the Control section; place a —Wait 1 second— block after the —Next Costume— block.

code block added

Click the Forever loop to run the instructions.

loop activated

The banner on the stage will cycle through the costumes. This gives the illusion of a neon sign.

neon effect

Arch banner

Return to the Vecteezy tab. Move the Line Curve slider to the right. Set the value to 55.

curve slider

The text curves into an arch. Export this text box as an SVG.

arch text box selected

Return to the Scratch project tab; import the text box as a Sprite. Set the name of the sprite to Arch Banner.

sprite and name field

Open the Costumes tab. Center the text box on the canvas.

text centered on canvas

Return to the Sprites section. Select the “aquarium banner” Sprite; click the Hide button.

hide sprite button

Move the Arch Banner above the diver and center it on the stage.

arch centered on stage above diver’s head

Now you have an extra tool at your disposal to create nice stage elements for your projects.

Read More
Coding, Scratch Alex Coding, Scratch Alex

Scratch animation and sound

In this lesson, we are adding animation and sound to our aquarium project. The animation for this project includes fish swimming in and out of the scene. It includes animation for the diver as he floats in the tank. We are adding underwater bubble sounds for the project background noise.

scratch animation and sound for random motion and sound effects

In this lesson, we are adding animation and sound to our aquarium project. The animation for this project includes fish swimming in and out of the scene. It includes animation for the diver as he floats in the tank. We are adding underwater bubble sounds for the project background noise.

You don’t have to be involved in the overall project. This lesson stands on its own. You can include the animation and sound from this project in the overall project later. I will demonstrate how to do that in the final part of the lesson.

Use the link below to get the basic part of the aquarium lesson. The link to the basic project includes basic dialogue and questions.

https://scratch.mit.edu/projects/476015580

Fish Sprites

The project includes the diver and aquarium background. There are three additional sprites. Three fish sprites will be part of our animation. We will add more fish later. The fish sprites are hidden for now. We will use code to reveal and animate them.

sprites section

Select the first fish sprite—fish01.

selected sprite

Code, in Scratch, is attached to elements like Sprites and backgrounds. I like this concept because it makes it easier to create lengthy stories with code blocks. If you went through the multiple language lesson, you understand how daunting it can be to deal with lots of code blocks.

The code we develop for sprites applies to those sprites exclusively. For example. the code from the diver applies to that sprite and does not affect the code we are going to develop for this sprite.

Backdrop grid

The sprites rest on a backdrop and coordinate plane. This coordinate is much like the coordinate plane used in math. The coordinate plane has an X and Y axis; it has four quadrants.

coordinate grid

The measurements in these quadrants are in negative and positive integers. Those measurements are in pixels. The coordinate plane measures 640 by 480 pixels. The center of the coordinate plane is zero. Measurements radiate left and right—up and down.

Let’s take a brief look at how the coordinate system works. Every point in the coordinate system is measured by a pair of numbers. The numbers represent the intersection of the x and y coordinates.

Use the image below. The top right quadrant is the first quadrant. There is a rabbit silhouette sitting at the intersection of 4 pixels to the right and 4 pixels up. There is a duck in the second quadrant. It sites at coordinates -5 and 4. The squirrel silhouette sits at coordinates -6 and -2.

coordinate plane with figures

The measurements are both positive and negative. Measurements to the left and down are negative. Measurements to the right and up are positive.

Scratch coordinates

The lesson project has two other sprites. One is called Frame and the other Circle. Select the Frame sprite and click the show button. Select the Circle sprite and click the show button.

selected sprite

A white coordinate frame appears on the stage. A red circle with a white border appears in the first quadrant.

frame and red circle

Move the circle around in the first frame. Look in the Sprite setting panel. To the right of the sprite's name is a pair of coordinate numbers. These numbers represent the current location of the sprite. The position is determined from the center of the sprite. Move the circle sprite from quadrant to quadrant. Observe how the coordinate numbers update.

coordinates

Place the circle in the center. This is the point of origin. The values for x and y are zero.

red circle in center of frame

Sprite limits

Move the circle to the left side. Move it as far left as you can. Sprites cannot be taken off the stage. Some part of a sprite must always be on the state.

red circle at left edge of stage

Look at the x-coordinate value; mine is at -240. This is as far as I can drag the sprite to the left.

x-coordinate value

We can try to push the sprite farther to the left by manually entering the x-coordinate value. Type -300 into the x-coordinate field. Press the Return key.

updated x-coordinate value

The value will not go beyond -240. Scratch will not allow the Sprite to be manually removed from the stage. This is an important thing to keep in mind as we begin our project.

The canvas measures 640 pixels wide by 480 pixels tall. The actual boundary of the stage is -320 on the left and 320 pixels on the right. The top boundary is 240 pixels and the bottom boundary is -240 pixels.

The x-coordinate of -240 is specific for this sprite to keep some element of the sprite on the stage. The measurement for all sprites is based on the center of the sprite.

Click the hide button to hide the circle sprite. Leave the frame showing for now.

scratch-animation-sound-12.jpg

Basic animation

Fish will travel from one end of the aquarium to the other. They will enter the scene on one side and exit on the other. We will begin with the basics and develop more intricate animation as we go along.

We have gone through this coding process in other lessons. We add instructions, one at a time, to develop a full program.

Select the fish01 sprite; click the Show button. The sprite is at the coordinate position (60,60).

hide sprite button

Go to the Motion section. Look for the —Go To x… y…— code block. The code block has the same coordinates as the sprite. The code block uses the current coordinate position for the parameters. This is designed to help with the creation of our code.

code block

Move the sprite to the left and off the stage. Drag it as far as it will go.

tip of fish sprite visible

Place the —go to x…y…— code block on the canvas. This is where we want the fish to begin the motion animation.

The x-coordinate value is far beyond the 320-degree edge of the canvas. This is because the fish sprite is much larger than the circle sprite. The center of the sprite is farther away from the edge of the stage.

code block on canvas

Replace the x-coordinate value with -400.

updated parameter value

Click the code block to run or execute this block of code.

code block clicked

The code block will try to move the sprite -400 pixels to the left. The settings for the code block place the sprite’s x-coordinate at -379. That’s as far as it will go.

This shows that we can push the sprite far off the stage and Scratch will keep the minimum edge of the sprite on the stage.

We want to begin with the least amount of the sprite showing on the stage. This creates the illusion that the fish is swimming in from an unseen area of the aquarium.

We want the fish to travel to the opposite side of the stage. The opposite side is at the x-coordinate 400. We will use 400 to try and push the sprite from the stage as much as we can.

Place a —glide…seconds to x…y…— on the stage and connect it to the bottom of the previous block.

glide code block

Change the x-coordinate value to 400. Click the first block to run these instructions.

code blocks clicked

The sprite will dash for the opposite side of the stage. Part of the fin is still visible on the stage.

fish fin showing

That is a little too fast. Change the glide seconds parameter to 5-seconds. Click the code blocks to run the instructions.

updated code block parameter

We want the fish to keep swimming in and out of the aquarium window. Go to the Control section; place a Forever loop around the code. Click the Loop to watch the fish move endlessly from left to right. Click the Stop button.

forever loop

The fish is large. We can keep the fish this large or adjust the size. We are going to adjust the size to create the illusion that some fish are smaller or farther away than others. The same is true to create the illusion for some fish to be closer or larger.

Go to the Looks section. Place the —set size to…— block inside the loop and before the other blocks.

set size code block

Change the size percentage to 50; run the code to see the effect.

The fish is moving from left to right but it doesn't look natural. Fish don't swim in straight lines. The x-coordinate measures the horizontal left and right. The y-coordinate measures the up and down or vertical distance.

We can change the y-coordinate value but we would wind up with the same problem. The fish would always begin and end in the same location. We need to set a range of exit points for the animation. The points need to be random so the animation doesn’t look like it is cycling through instructions. It is, but we can create the illusion that it is not.

Go to the Operators section. Place the —pick random…to…— block into the glide y-coordinate parameter.

operator over parameter

The height of the stage is 480 pixels. The coordinates range from -240 to 240 pixels. The range doesn’t have to be that extreme. Type -100 and 100 into the parameters. Run the instructions and observe what happens.

The random number generator selects a number between -100 and 100. That number is used for the y-coordinate.

values in random code

The fish will enter from the same location on the left and move to some exit point on the right. That exit point is usually lower than the one from where it started. This is better but it still isn’t very natural looking. The fish needs to enter from random locations on the left too.

Place a —pick random— code block into the y-coordinate parameter for the —go to— code. Set the parameters to -100 and 100. Run the code.

random number generator with values

The fish is now entering and exiting at different locations.

The fish is moving across the stage at a fast pace. The speed needs to be adjusted randomly so it moves slowly sometimes and fast at other times. Place a random block into the glide seconds parameter. Set the range values at 5 and 10 seconds.

random generator with values

Let’s adjust the size of the fish. Fish come in all sizes. Fish also appear larger when they are close than when they are far away. Adjusting the size will give us some of this illusion.

Place a random block into the size parameter. Set the range values to 50 and 70 percent.

random generator with size values

The random code block is useful for adding depth and complexity to our three basic code blocks. The range values in the random blocks are my suggestion. Adjust the values to get the results you prefer in the animation.

I didn’t think there was enough variation in the size of the fish. I adjusted the size range values to 20 and 80 percent. I thought the fish was moving too fast. I adjusted the glide range values to 8 and 15 seconds.

updated time range

The fish keep moving in front of the diver. I prefer they swim behind to minimize the distractions.

fish in front of diver

Go to the Look section. Place a —go to…layer— block before the Forever loop.

code block in place

Select the back layer.

layer selector

The fish is now swimming behind the diver.

fish behind diver sprite

If you have ever been to an aquarium, you know that fish don’t swim perfectly horizontally. They swim at slight angles.

Hide the frame sprite. We don’t need it anymore.

Move the fish sprite so it is near the center of the stage.

sprite near center of stage

Look at the Sprite Setting section. The direction setting for the sprite is at 90-degrees.

sprite direction field

Click inside the direction field. Use the dial to rotate the fish to 95 degrees.

direction wheel

The fish is now pointing down and to the right. We don’t need to rotate the angle of the fish too much. Rotating the fish too much might make it look too unnatural.

fish at selected angle

Rotate the fish in the other direction to 80-degrees.

fish at selected angle

We want the fish to rotate between these two angles.

Go to the Motion section. Place a —point in direction…— block inside the Forever loop; place it in front of the other blocks.

code block in place

Get a random generator block from the Operators section; place it inside the direction parameter. Set the range to 80 and 95.

direction range values

Fish in aquariums don't come into view regularly. We need to stagger the interval when the fish appears.

Place a —wait…seconds— block in the Forever loop. Attach it to the end of the blocks inside. We want the fish to move across the window and wait a random amount of time before it reappears.

wait code block

Place the random generator inside the second's parameter; set the range to 5 and 10 seconds.

random number generator in parameter

Run the program. Everything is working well. We do have an odd thing that needs to be fixed. The fish sprite stops and waits at the edge of the stage.

We need to have the sprite fully disappear from the stage while it waits.

fish fin visible on stage

We can’t completely move the sprite off the stage. We can hide it. Place the Hide block from the Looks section before the Wait block.

hide code block

Run the program; you will see this introduces a new bug. The sprite is hidden and does not reappear. Place the Show block at the beginning of the code in the loop.

show code block

This is all looking great. One more problem. The fish is always coming in from the left and exiting right. We need fish to enter and exit from both sides.

To solve the problem we need to change the entry and exit x-coordinates. We want to change the values, you guessed it, randomly. We need to randomly select either the left or right side of the stage.

x-coordinate values highlighted

We need an —If…then…Else— code block. The code needs to compare a value to make a decision.

We need to create a variable to store the decision and pass it to the relevant code.

Go to the Variables section; click the Make a Variable button.

make a variable button

Set the variable name to x-value; click the OK button.

variable name

The variable is created and selected. The checkmark causes the variable to display the contents on the stage. Leave it on for now.

variable code block

Place the variable in an empty area on the canvas. Place a Set variable on the canvas too.

code blocks on canvas

Go to the Control section. Place an —If…Then…Else— code block between the Show code and the rest of the code. You might need to move blocks out of the loop to accommodate the condition statement.

code block in loop

Place an Equality operator from the Operators section into the condition parameter.

operator in parameter

Place the random number picker into the left side of the Equality operator.

random number generator in parameter

Set the random number generator range from 1 to 2; we only need one of two possible choices. Set the comparison value to 1.

random range values

Place the Set variable block inside the If section. Set the variable to the x-value variable.

variable selector

If the selected number is 1, we want to enter from the left. Set the variable to -400.

variable value

If the selected number is 2, we want to enter from the right. Right-click on the Set variable block; select Duplicate.

duplicate option

Place the duplicate inside the Else section. Set the value to a positive 400.

variable value

Right-click the x-value variable; make a duplicate.

duplicate option

Place the duplicate variable into the —go to x…— parameter.

variable in parameter

The value for the other side needs to be the opposite value. For example, if the beginning x-coordinate value is 400, the end x-coordinate value for the glide needs to be -400. The same is true if the value is -400; the exit value needs to be a positive 400.

We can easily do this with math. We will use the Negative Property of Multiplication.

Place a multiplication operator into the glide x-coordinate parameter.

operator in parameter

Place the x-value variable into the left side of the operation; type -1 into the right side.

variable in parameter

Run the program. Everything is working nicely, but the fish swimming backward when it enters from the right. There's a clownfish in every class. Sorry, bad joke.

variable value

We are going to take care of this with a costume change.

Click the Costumes tab.

costumes tab

The sprite has only one costume. We are going to make one in a few clicks. Right-click on the costume; select duplicate.

duplicate option

This costume will face in the opposite direction; click the Flip Horizontal button. That’s it.

horizontal flip button

Click the Code tab. Go to the Looks section. Add a —Switch costume to…— code block after each Set variable block.

costumes code blocks

Set the first Switch costume block to Costume1; set the other to Costume2.

selected costume parameters

Run the program. The fish is entering from one side or the other. It is swimming across to the opposite side. It is facing the correct direction. Just about everything with the animation has some random aspect.

More fish to the animation

That is all we are going to do for this animation. Connect the Green Hat block from the Events section to the beginning of the code.

green flag code attached

We need to apply the same animation code to the other sprites. Drag the Green Flag Hat block down to the Sprites section. Place it over the fish02 sprite and release.

code over sprite

Select the fish02 sprite. Look at the coding canvas. The code was copied to this sprite. Click the green flag. Watch the animation of two fish on the stage.

two fish swimming

Stop the program. Drag the code from this sprite to the fish03 sprite. Watch three fish swimming in the aquarium with the diver.

three fish swimming

Let’s add more fish to the aquarium. Use the link below and download several fish sprites. The sprites are in a Zip folder.

Download Zip file
(The fish images are courtesy of freepik.com)

Go to the Sprites section; hover over the Add Sprite button and choose the Upload option.

upload sprite option

Select all the Sprites; click the Open button.

all sprite files selected

The sprites are added to your Sprite library. The sprites are hidden until we begin the program.

Select one of the sprites. Look at the coding canvas. The sprite has the code we created in the lesson. I did this to save you time. Now you can enjoy an aquarium filled with fish. Click the Green Flag; enjoy.

lots of fish on stage

Diver animation

The diver is very still. It’s time we added animation to our diver.

Select the diver sprite. Place a —go to x…y…— block on the coding canvas. The diver is at position (-92,-100). We want the diver to remain in the general area. The diver doesn't need to be swimming around. The diver needs to look like he is floating in the water.

block on stage

Place a —glide to x…y…— block on the canvas. Don't connect it to the previous block.

blocks on stage

The diver needs to move around the starting position in random motions. Place a Random number generator into each of the glide parameters.

random blocks in parameters

We don't want the diver to stray too far away. The starting x-coordinate is -92. We will allow the diver to stray up to 20 pixels from this location. We need a range for the random number generator in the x-coordinate. Enter -72 for the lower range and -112 for the upper range.

range values in fields

Enter -80 and -120 into the y-coordinate random number generator range.

range values in fields

Get a Forever loop and place the Glide code into the loop. Connect the —Go to— code to the loop. Placing the Go to code outside the loop centers the diver at the beginning.

code blocks connected

Click the code and observe the diver moving from side to side.

The diver is moving too fast. Set the glide duration to 3-seconds. Connect the Green Flag Hat to the code.

green flag hat block connected

I have an animated Gif for you below.

Bubble sounds

The diver is underwater. We should hear some underwater sounds coming from the aquarium. Select the Sounds tab.

sounds tab

Hover over the Add Sound menu; select the Choose a Sound option.

choose sound option

Type bubbles into the search box; click the Bubbles sound.

bubbles sound icon

Click the Play button to listen to the bubbling sound.

play controls and play button

I like the sound. I would like to modify the sound so it sounds like bubbles coming from deep underwater.

Click the Slower button four times. Note how the sound is deeper. This is closer to the sound of bubbles underwater. The settings are automatically saved.

slower button

Click the Code tab.

Place a —Start Sound— code block inside the Forever loop of the animation. Place the block at the beginning of the loop. Make sure the Bubbles sound is selected.

start sound code

Click the green flag to run the program.

This lesson is complete. We have animated fish in the aquarium. The diver is animated. Bubble sounds are coming from the aquarium.

Sharing code

This is part of a much larger project. Programmers often create smaller parts of a larger program. The parts are assembled into the larger program.

This larger project includes multiple languages. It’s easy to integrate the code we created into the larger project. The code is part of each sprite.

Go to the Sprites section; select a sprite. Right-click the sprite; select the export option. This downloads the sprite to your computer. Repeat the process for each fish you want to include in the larger project.

Switch to the larger project and upload the sprites. It works just like the sprites I shared with you for import earlier.

sprite export option

The divers sound is a little different. Exporting the diver will export all the extra code. We don’t need this code in the larger project.

We will create a temporary sprite to hold the diver animation and sound.

Go to the Create Sprite button and select the Paint option.

paint sprite option

Set the name of the sprite to “diver float and sound”.

sprite name field

Select the Code tab. Select the diver sprite. Find the sprite we created. Don’t click on the sprite. Make sure you can see it in the Sprite section.

Drag the diver's motion and sound code. Take it and drop it onto the sprite. Click the diver float and sound sprite. Make sure the code is part of the sprite. Export this sprite to your computer.

code over empty sprite

Open the larger project; select the diver float and sound sprite. Make sure the diver sprite is visible. Drag and drop the code onto the diver sprite.

code over diver sprite

The code is added to the existing diver code.

new code with existing code

Look at the animation below to see how the new code is integrated into the larger project.

Right-click the diver float and sound sprite; select delete.

Please take the time to answer the quick survey below. Thank you.

Read More
Coding, Scratch Alex Coding, Scratch Alex

Multiple language dialogue in Scratch projects

This lesson explores the use of lists to provide dialogue in multiple languages. This is a good project for second language learners. In this project, we use several lists for several languages. The project includes five language options. The interactive part of the project prompts the user to select from one of the available languages.

multiple language dialogue in Scratch projects using lists

Scratch for multiple language dialogue

In this lesson, we are expanding on a previous lesson. In that lesson, we used lists to cycle through dialogue. That project is available through the link below. Make a copy of the project for use in this lesson.

https://scratch.mit.edu/projects/470830122

Click the flag to go through the project. The diver cycles through dialogue. The dialogue is stored in a list. A loop is used to call each dialogue item in the list. A separate list is used for the question and answer portion of the dialogue.

The upcoming lesson extends the use of lists to create dialogue in different languages. The lesson underscores the effectiveness and usability of lists in projects. Lists are useful in reducing the number of lines of code used in a project.

I encourage you to go through the lesson on dialogue and lists. Use the link below to access that lesson.

Stories and interactive projects with lists

Project resources

In this project, we use several lists for several languages. The link below is for a Zip file with several text files. The text files contain the dialogue used in the project for multiple languages. The language options include English, French, Italian, Spanish, and German. Use the link to download the text files. The files are in a ZIP folder. Extract the files from the folder.

Download ZIP file

Use the link above to get a copy of the project created up to this point. The link is available below for your convenience.

https://scratch.mit.edu/projects/470830122

My blocks

An essential part of code development is the use of Functions. Functions organize groups of tasks. The code we have up to now has two portions. The first part of the program begins with a dialogue. The second part contains questions and responses. We can divide this portion into one where we prompt for the visitor’s name and one where we prompt for the tour request.

Dividing code into separate functions helps with the organization of our program.

This project is going to have many code blocks. Function blocks will go a long way in helping us organize the sections in our program.

Go to the My Blocks section. Click the —Make a Block— button.

make a block button

Set the block name to “welcome message”; click the OK button.

block name set

Two blocks are created. One block is in the My Blocks section. The other is placed on the canvas. This is called the Hat block. It caps the code like a hat.

code hat block

Click the Make a Block button again. Set the new block name to “visitor’s name”; click the OK button.

created code block

Create another block. Set the block name to “tour request”.

Arrange the canvas block in a row along the top of the coding canvas. Move the other code blocks down and away from the blocks we created.

three hat blocks on canvas

Disconnect the code from the green hat block. Set the hat block to one side for now.

code disconnected from green flag

Connect all the code to the “welcome message” hat block.

connected code to welcome message hat block

Separate the —Ask— code from the repeat loop.

disconnected code blocks

Attach the —Ask— code to the “visitor’s name” hat block.

code connected to visitors name hat block

Separate the code at the —Repeat until— block; connect the rest of the code to the “tour request” hat block.

code connected to hat block

Find the green hat code block. Place it somewhere visible.

green flag hat block

We want the code to begin at the welcome message when the green flag is clicked. Get the “welcome message” block and attach it to the green flag hat.

This block instructs the program to find the “welcome message” hat block and run the code that is attached to that block.

welcome message block connected

We want to ask for the visitor’s name after the welcome message. Place the “visitor’s name” block after the repeat loop of the welcome message.

visitor’s name block connected

We want to ask about the tour after we get the visitor’s name. Attach the “tour request” block to the end of the visitor’s name code.

code block connected

My Blocks is useful for grouping code into easily identifiable sections. Click the green flag and run through the program. Everything should work the same.

Make room

We have lots of code on the canvas. Let’s tidy up before proceeding to the next part of the lesson.

Click the minimize panel button.

stage minimize button

Click the zoom out button a couple of times.

zoom button

Move the code blocks to the right side and out of the way. We won't need them for a while.

blocks move to the far right

Zoom back in to focus on the green flag hat block.

Language lists

Each text file represents a separate list. We need to create each list before importing the text files. Use the text file names for the list names.

Go to the Variables section; click the Make a List button.

make a list button

Set the list name to “languages”; click the OK button.

list name

Lists are created and displayed on the stage. We are going to create several lists. We don’t need to display them all. Remove the checkmark from the list before creating the next.

list code blocks

Click the Make a List button again. Set the list name to “French dialogue”; click the OK button. Remove the checkmark from the list.

list name

Create another list; set the list name to “French Q&A dialogue”. Save the list and hide it.

list name

Repeat this process for each of the text files.

We have the dialogue for the English portion. It needs to be renamed. Right-click on the dialogue list; select the rename list option.

rename list option

Set the list name to “English dialogue”.

list name set

Right-click on the Q&A dialogue list; change the list name to "English Q&A dialogue".

list name

I will talk more about these lists when that portion of the lesson arrives. Create a list for each of the text files. Set the list name to the name of the text file. I know I’ve said that before but it is important to name the list names appropriately. It will help during the coding process.

Import lists

Each list needs information that makes it a list. This is where we import those text files downloaded earlier. Place a checkmark on the English language list.

list selected

The empty list appears on the stage. Click the expand stage button. We collapsed the stage in a previous step.

empty list on stage

Right-click on the list; select the import option.

list import option

Select the English language plain text file.

list plain text files

The text file has only one entry.

one list item

Remove the check from the English language list; place a checkmark on French dialogue.

french list selected

Right-click the French dialogue list; select import.

import option

Select the French dialogue plain text file.

selected plain text file

Expand the list box to get a better view of the list contents.

french dialogue list items

Repeat this process for all the lists. Yes, it is a little tedious; coding isn't all glamor. Make sure to hide all the lists after importing. Lists are the powerful and silent assistants in the background.

Choose a language

We want the diver to watch the visitors and invite them to attend a tour of the aquarium. The aquarium is home to visitors from countries around the world. The divers have presentations in multiple languages. The diver wants to inform visitors of tours that are available in different languages.

The visitor needs to type a language to accept the invitation. Go to the Sensing section and place an Ask block on the canvas.

ask block

The text in the Ask parameter is sent to the sprite. It appears in a speech bubble. We don't need that text because we have some text of our own. Erase the contents of the parameter.

no parameter in ask block

We have the invitation text in a list. Place a —Say…for…seconds— code block from the Looks section next to the —Ask— block.

say code block

Go to the Variable section and the list blocks. Place an —item…of…list— block into the Say parameter.

list block in way block parameter

Select the “welcome languages” list.

welcome languages list selected

Place a checkmark on the “welcome languages” list.

checkmark enabled

The list contains a welcome and instructions in five languages. The code will cycle through the invitations until the visitor enters a valid language. Hide the list again.

list of languages dialogue

Get a —Repeat Until— block and place it around the —Say— block. This block repeats the —Say— block until we get an answer.

repeat until loop code block

To cycle through the invitations, we need to increment the list item. For that, we need a variable. Go to the Variables section; click the —Make a Variable— button.

make variable button

Set the name to “invite counter”; click the OK button.

variable name

Place the —Set variable— on the canvas but don’t attach it to any code yet. Attach the —Change Variable By— block to the —Say— block. Change the variable of both blocks to “invite counter”.

variable block

This code resides in a loop. Attach the Forever loop around the Change and Say blocks. The —Forever— loop temporary so we can test the loop. Attach the —Set Variable— block to the —Forever— loop.

connected blocks

The Set block initializes the variable to Zero. The Change block adds one to the variable. The Say block displays the content of the items in the list. The item is currently set to one. This item needs to change as we cycle through the loop. Get the —Invite Counter— variable; place it in the —Item— parameter.

variable in parameter

The list contains 10 items. We need to cycle back to the first item after we reach the last. Place an —If…then— block after the —Say— block inside the loop.

if condition block attached

Place an —Equality Operator— inside the If condition.

An equality operator is different from a regal equal. An equality operator is used to determine if two values are identical. The Equal operation Assigns a value to a variable.

connected operator block

Place the “Invite Counter” variable into the left side of the equality operator. Go into the List blocks. Place the —Length of…— block into the right side of the operator. Change the list to “welcome languages”.

The operator compares the “Invite Counter” variable to the number of items in the “Welcome Languages” list. If they are the same, then the condition is True. For example, if the value in the Invite Counter is 10, then it is equal to the number of items in the list. That means we have reached the end of the list.

variable and list blocks in parameters

Place the —Set Variable to…— block inside the If condition. If the counter and the list item count are the same, then set the Invite Counter variable to zero.

variable counter increment block

Click on the first block of the code. This executes these lines of code only.

blocks running code

You will see the diver actor cycle through the dialogue in the list. The actor will do this until we stop the code; stop the code using the Stop sign button.

actor dialogue in languages

The list length block makes the code dynamic. This makes it possible to add more languages to the list and not need to update the code.

Go to the Lists and place a checkmark on the “Welcome Languages” list. Click the Add list item button twice.

add list item button

Let’s add Russian to our list of languages. Copy and paste the lines below.

Добро пожаловать, я говорю по-русски.

Введите русский язык в поле.

list with items added

Hide the list; click the first code block to run through the languages. Russian is now one of the languages we speak.

actor dialogue in Russian

The Forever loop is just to test the code. Let’s replace this loop with another. Disconnect the blocks from the Forever loop.

forever code block

Remove the Forever Loop and place a —Repeat Until— loop on the canvas. Connect the code to the loop.

repeat until loop and connected blocks

We want to repeat the invitation until a visitor enters a language. Any one of the six languages will be sufficient.

To check the language entered, we need a variable to hold the answer. The Answer variable, part of the Ask code, doesn’t provide much flexibility. We need to create one of our own.

Go to the Variables section; make a variable. Name the variable “language answer”.

list language selected

Connect the —Set Variable To— block to the —Ask— block. Select the “language answer” variable.

connected code blocks

Place the “Answer” variable from the Sensing section into the Set parameter.

answer variable connected

Let’s work on the loop. The loop needs to check for multiple conditions. It needs to compare the answer with the available languages. The program will take the visitor on the tour that offers the tour in the selected language.

Checking the language options

The program also needs to filter for a language that is not available and inform the visitor that the language is not one of the options.

Place the Equal operator into the Repeat loop parameter.

connected code blocks

Place the “language answer” variable into the left side of the Equality operator parameter.

connected code block

Type English into the right side of the operator. Typing the language into the parameter is fine if we just want to check for English, but there are five other language options.

word in parameter

To check other languages we need to include another operator.

Place the OR operator next to the code blocks.

operator on canvas

Remove the Equality operator from the loop and place it into the left side of the OR operator.

disconnected code block

Place the OR operator into the loop parameter.

Now we can check for English OR another language.

operator in operator parameter

Right-click the Equality operator; select duplicate.

duplicate code option

Place the code on the right side of the OR operator. Change the language to French. There are four more languages to go.

operators in operator parameters

A better way with lists

Before we go on with the rest of the code I do want to tell you that this is not the most efficient way to check for the input language. The code blocks are cumbersome. The code needs to be updated each time we add a language.

Look at the image below. This is the complete code block checking for a language input; long and cumbersome.

complex or operations

There is a more efficient way to check for language input. Programming is always about the easiest and most efficient way of getting a task done.

Remove the operators we placed in the Repeat loop; trash them.

removed operators

Go to the List code blocks. Find the List —contains…block— and place it in the loop parameter.

list block in loop parameter

Place the “language answer” variable into the parameter.

This code is more efficient. It looks to see if the answer is in the list. The list contains all the available languages. The code checks all the items in the list. If the answer is in the list then the loop will stop repeating. We don’t have to update the code if we add or remove a language.

Language not available

The loop continues if the answer is not available in the list.

language answer variable

We should always include a way to break out of a loop. That brings us to the next part of the program.

When a visitor enters a valid language the program will jump to that part of the invitation in the selected language. If the visitor enters a language that is not available in the list we need to prompt the visitor that we do not offer the tour in that language.

Move the code we created to one side. Place an —If…then…else— block on the canvas. Place an Equality operator into the parameter. Place the "language answer" variable on the left side of the operator. Type French into the right side of the operator.

condition code block and operator

We are going to use a series of nested conditions. If the visitor enters French for the language, the program will proceed to the French portion of the presentation.

Here is the thing to consider. We are using the English version of the French language to compare the answer. This poses a problem if the person is a native speaker of French. They are likely to use Francais or français with the diacritical mark. The hook below the letter 'c' is a cedilla or une cédille in French.

We need to check for these alternative versions. This is another opportunity to use Lists.

Place a checkmark on the “French language” list.

list selected

The list contains two options for French. Let’s add one more option to include the word Francais without the diacritical mark.

language list items

Click the Plus button to insert a line. Type “Francais” in the added line. Hide the list.

added list item

Remove the Equality operator. Insert the —List contains— block into the condition parameter. Select the French language list. Insert the “language answer” into the parameter.

If any of the three language spellings is entered, the condition will be true. The condition will then take the visitor to the French portion of the presentation.

parameter in list block

Let's add conditions for the other languages. Right-click the If…then…else condition; select duplicate.

duplicate code block option

Place the copy into the Else section of the loop. Choose the “German language” list.

connected code

Duplicate this condition and place it inside the Else part of the condition. Change the list to “Italian language”.

updated language list

Repeat this process until all languages are in condition statements.

The program needs to jump to the appropriate language. To do that, we need to create some blocks.

Go to the My Blocks section; click the —Make a Block— button.

make block button

Set the block name to “English”; click the OK button.

block name

Click the Make a Block button again; set the name to “French”. Repeat this process for each language.

French block

Arrange the hat blocks in a row along the top of the canvas.

hat code blocks

Place the "French" block from the My Blocks section into the –If– condition for the French language.

French code block

Place the “German” block into the If condition for the German language. Repeat this process for each of the language conditions.

German code block

We need to connect each section to the corresponding dialogue for that language.

Language dialogue branches

At the beginning of the lesson, we created blocks to segment the code into separate functions. The blocks begin with the Welcome message. I used these to introduce you to the concept. We don't need these blocks and we don't need to separate the code into these functions. They would add more complexity to the program.

Find the “welcome message” attached to the green flag hat. Disconnect the block from the hat block.

disconnected block

Move the “welcome message” block to the code panel; this moves it to the trash.

welcome message block

Disconnect the other blocks from the code; include the hat blocks. Drag all the blocks to the code panel.

disconnected blocks

Reconnect the code blocks. Make sure to reconnect them in the correct order. The counter goes first, followed by the Ask and the Repeat until loops.

connected code blocks

This code represents the English version of the tour. We need the same code to represent each of the other languages.

Right-click on the top code block; select the duplicate option.

duplicate option

Place the duplicate code to one side of the original.

duplicate set of code

Use the list selector to choose the French dialogue list.

selected list

Go to next list reference. Select the French Q&A dialogue list.

selected list

Repeat this process for each of the list references. Replace the list with the corresponding list in French.

selected list in code

Right-click on the first block of the updated code and select duplicate. Place the duplicate to one side of this code.

duplicate list of blocks

Change the list references to the next language —German. Update all the list references to the same language.

selected list

Duplicate this updated code and update the language list in those lines of code. Repeat this process for each of the languages.

Place the language hat blocks at the beginning of each code for the corresponding language.

code connected to language hats

Attach the condition blocks to the —Ask— and —language answer— blocks.

attached code

We need a few more steps before we are done; hang in there.

Two operations at once

We need the code to cycle through the message in different languages. We also need the code to ask the question and wait for a response. We can do both.

Connect the green flag hat to the Ask code.

connected code

Get another green flag hat and connect it to the invitation loop.

connected blocks

Click the green flag to run the program.

Everything seems to work correctly until we enter a language. The welcome message continues to cycle with the chosen language dialogue.

Fixing bugs

There are a couple of bugs to fix. I caught them at the same time you ran the program. I could have edited my lesson to avoid them, but that would avoid a teachable moment. Bugs are part of the coding process. Fixing bugs is part of the process.

The problem with the cycling invitation message lies in the list. The answer is checking against the "welcome languages" list. It needs to check against the "languages" list.

selected list

The next bug happens when we choose to run the program again. The variable for the language holds on to the last answer. The variable needs to be initialized at the beginning of the program.

Place a Set variable block before the Ask block. Set the variable to “language answer”. Erase the value parameter.

code connected

Click the green flag and run through the program. Fix any bugs you might find. Check all the languages.

Language not available

The condition statements check for the available languages. A visitor might enter a language not available or might type something that doesn’t make sense. The last Else statement is here to take care of those situations.

If the visitor enters something not available on the language list, we want to send a message to the looping invitation. We want to loop to temporarily stop and respond to the input.

Place a Set variable to block in the Else section. Set the variable to “language answer”. Type “not available” for the variable value. This replaces the visitor’s input with the words “not available”. This allows us to control the message sent to the loop in the next step.

code in place

Place an If…then condition after the –If– condition in the invite loop.

code block connected

Place an Equality operator into the parameter. Place the “language answer” variable into the left side of the Equality operator. Type “not available” into the right side of the operator. Place a Say block into the If condition. Type “I’m sorry. I don’t understand that language”. Change the wait time to 4-seconds.

variable in parameter

We need to erase the “language answer” variable so the loops can continue. Place the —Set variable— block below the Say block in the loop. Erase the value passed into the variable.

code in place

We need to make sure to keep asking the visitors for the language until a correct language is provided. Get a Repeat Until loop and move it under the —Set variable— code.

loop being connected

Place the —List contains— block into the loop parameter. Set the list to “languages”. Place the “language answer” variable into the parameter.

code blocks

Click the green flag to run the program. Enter nonsense into the answer and watch for the message to appear.

Yes and No

The final part of the code is to set the language answer options. Open the Yes and No answer lists.

There are several ways to say yes or no in different languages. Several languages use the same form. Spanish and Italian use Si. English, Spanish, and Italian all use the same No. Yes is yes in any language. The same is true for No. We don't need a list for each language. Hide the lists.

list displayed

Go to the code for the English response. Go to the section where we need yes or no responses.

updated code

Remove both Equality operators from the loop parameter. Keep the OR operator.

variable added

Place a List contains code block into the left side of the Equality operator. Select the "no answers" list. Place the "answer" variable into the parameter.

variable added

Place the same block on the right side of the equality operator. Choose the “yes answers” list; place the “answer” variable into the parameter.

updated code

Remove the equality operator from the If parameter.

duplicate code

Duplicate the "yes answers" contains code block.

duplicate option

Place the block into the If parameter.

code added

Remove the code from the other If parameter. Duplicate the "no answers" contains code block. Place it into the empty parameter.

The yes and no conditions are now updated for the English language function. Repeat this process for the other languages. Duplicate the blocks from this code to save time.

code for loop until condition

Run through the program and use a different language. Answer with yes or no for the chosen language.

One last bug

There is one last bug we have not addressed. We added the Russian language in an earlier part of the lesson. We did not add the language to the list of available languages.

Open the “languages” list. Add two rows and add Russian. Use the Cyrillic text below for Russian.

русский

added language to list

Conclusion

That brings us to the end of this part of the project. This is one of the longest sections. We learned several techniques to develop an interactive project for multiple languages. We will return to these techniques in later lessons.

Use the link below to get a copy of the finished project.

https://scratch.mit.edu/projects/472572372

Read More
Coding, Scratch Alex Coding, Scratch Alex

Stories and Interactive projects with Lists

In this lesson, we are going to reproduce the presentation using Lists to organize the dialogue and question prompts.

Lists reduce the length of our code in a variety of ways. Much of it depends on the product you are creating. The original presentation in the lesson uses ten lines of dialogue in the code. The presentation consists of one scene. You can imagine the number of dialogue lines needed in a full story.

lists for scratch dialogue

Stories in Scratch are filled with dialogue. In a simple story, the code can stretch down the page and across several code blocks.

In a previous lesson, we created a simple interactive presentation. The presentation included several lines of dialogue and question prompts. You can take a look at that project with the links below. I encourage you to work through that lesson first.

Alex’s Aquarium interactive presentation lesson

The presentation includes ten lines of dialogue and two question prompts. It doesn’t seem like many lines, but this is just the introduction.

dialogue code blocks

In this lesson, we are going to reproduce the presentation using Lists to organize the dialogue and question prompts.

Lists are used to store and organize information for programs. The information is anything we need to reference with our code. Lists are known as Arrays in the field of programming. Arrays do the same thing that lists do in Scratch. Lists in Scratch are an Array.

Lists reduce the length of our code in a variety of ways. Much of it depends on the product you are creating. The original presentation in the lesson uses ten lines of dialogue in the code. The presentation consists of one scene. You can imagine the number of dialogue lines needed in a full story.

The best way to understand lists is to dive right in and use them. Use the link below to download the resources for the project. The resources include a diver sprite and an underwater aquarium scene.

Download the sprite and backdrop

Go to https://scratch.mit.edu and create a new project. Set the title of the project to Alex’s Aquarium Introduction.

project name field

Download the project assets using the link above. Click the Add Sprite button and choose the upload Sprite option.

upload sprite option

Select the diver sprite and open it to begin the upload process.

sprite file selected

We don’t need the Scratch cat sprite. Select the cat Sprite and click the delete button.

cat sprite

Use the Backdrop menu to upload the underwater scene.

upload backdrop

Select the underwater scene image.

underwater scene image selected

This is our actor and scene.

diver and scene backdrop

Select the Code tab.

code tab

Go to the Variables section; click the Make a list button.

make a list button

Name the list dialogue; click the OK button.

list name

The list is placed on stage with our actor and backdrop. The list is empty and ready for our data.

list over stage

Click the Plus button to begin adding content to the list.

add to list button

Type Hello into the first line.

first list item

Press the Return key and type —Welcome to Alex’s Aquarium.

second list item

The second line stretches beyond the list width. Use the lower right corner to widen the list view.

list bottom right corner

There is more dialogue but don’t worry –I won’t expect you to write it all out. In Scratch, we have the option to upload a prepared list. The list must be in Plain Text format. I prepared the list for you. Use the link below to download the list.

Plain text lists can be created using any simple word processor. The list below was created in Google Docs. The link exports the document as a plain text file.

I would encourage you to have students write out the dialogue in a word processor and save it as a plain text file.

Download plain text file

The text file is a list. Each line of our dialogue is on a separate line. Open the text file and take a look.

Right-click on the list. There are options to import and export list information. Use the import option to get the text file from your computer.

import export options

The import process replaces the current list items with those imported.

imported list

The first six items are the introduction of the presentation. The next line is a prompt for the visitor to enter their name.

Go to the Events code section; place the When Green Flag clicked code onto the canvas.

green flag code

Attach a Repeat Until loop from the Control section.

repeat until loop

The purpose of the loop is to repeat the contents until we reach a condition. That condition, in our example, is the number of lines in the first part of our dialogue. The first part of the dialogue consists of six lines. The Sixth line prompts for the visitor's name. At this point, we need to break out of the loop and provide the visitor an opportunity to respond.

We need to count the number of lines. For that, we need a variable.

Go to the Variables section. A variable is created for us with each new Scratch project. We need to change the name.

variable

Right-click the variable name; select Rename variable.

rename variable option

Set the name to Counter.

variable name set

Place the –Set Variable To– code block between the Green Flag and the Repeat Until loop. This sets the counter at zero each time we begin the program. This is called initiating a variable. It is common practice in coding.

set counter code

Place the –Change Counter by 1– code inside the loop.

change counter code

Place the variable block on the canvas. Don’t place it in the code yet.

counter variable on canvas

Place the Equal Operator from the Operator Section inside the –Repeat Until Loop– parameter.

equal operator

Right-click the Counter variable; select duplicate.

duplicate option

Place the Counter variable inside the left side of the Equal Operator. Change the value on the right to 6.

value changed

Place a –Say…for…seconds– block in the loop and below the –change counter by– block.

say code block

Go to the Variable section. The list we created includes several code blocks. Find the block that reads –item 1 of dialogue.

item code block

Place the code block into the –Say code– parameter.

item code in parameter

Duplicate the Counter variable; place it inside the Item parameter.

counter variable in parameter

Find the List block and remove the checkmark. This hides the list box on the stage.

list checkbox

Click the green flag and watch our actor go through the dialogue.

green flag

Compare the number of lines used in this code to those I presented at the beginning of the lesson.

Code Explained

This is what we are doing with the code.

Each item in our list is represented by a number. The list begins with number 1. A typical array is indexed and begins with the number 0. Beginning with number 1 makes sense for young coders.

We have a variable called Counter. This counter is used to keep track of our count beginning at zero.

We have a loop that repeats a series of steps until we reach a specific counter value. That value is 6.

The loop contains a Say code block. The Say parameter text is replaced by the item number of our list. The item number is replaced by the counter variable.

The first time through the loop; the counter is incremented by one. The next line displays the contents of the first line of the dialogue list. This is done through the Say code. That line is Hello. It shows the text for 4 seconds and returns to the beginning of the loop.

The loop checks to see if the counter is equal to 6. The counter is now set to the value 1; the loop continues.

The counter is incremented by 1; the counter is now 2. The Say code shows the contents of the second line in the list.

The process repeats until the counter value is 6.

There is no code after the loop ends, so the program stops.

Updating the dialogue

With lists, we don't need to change the code to change the dialogue. Go to the Variables section; place a checkmark next to the dialogue list.

dialogue checkbox

Change the diver's name to anything you like –e.g., your name.

list item updated

Adding content to lists

Click on item 6; press the Return key. A new line is created to enter more information.

line 7 in list

Prompt the visitor to use the keyboard.

content added to list line 7

We need to update the code to include the extra line of dialogue. Change the count number in the loop from 6 to 7.

counter updated

Questions and answers

Lists are valuable for dialogue that includes questions and answers. Return to the Variables section. Click the –Make a List– button. It's useful to separate categories of lists with separate lists.

make a list button

Set the name to Q&A dialogue.

list name

Remove the checkmark from the dialogue list to hide it.

list checkbox

I have some response dialogue ready for the list. Use the link below to download the text file.

Download the text file

Right-click the Q&A list and select the import option. Select the Q&A dialogue text file for import.

import export options

The list contains four responses to questions we are going to ask.

list items

Let’s begin with the first question. Go to the Sensing code block section; place an –Ask…and…wait– block after the loop. Leave the prompt set at What is your name?

ask code

Attach a –Say…for– code block to the –Ask– code.

say block

Go to the Operators section. Find the Join block and place it inside the Say parameter.

join operator

Go to the Variables section. Place the -item…of…list– block into the left side of the Join operator. Item 1 of the dialogue list contains the word Hello. This is what we want.

item code block

Go back to the Sensing section. Find the Answer variable; place it on the right side of the Join code.

answer variable

The question prompting for the visitor’s name is not on the list Q&A list. Go to the Q&A dialogue list; click the Plus button to add an item.

list add button

Enter the question –What is your name?– into line five.

list item

Place the –item…of– block into the Ask code parameter.

item code block

Click the List selector; choose the Q&A dialogue list.

list selector

Enter the number 5 for the list item.

item variable

Go to the Variables section; hide the Q&A dialogue list. Click the Green Flag. Answer the question when prompted.

The words Hello and your name aren’t separated by a space. We will fix that next.

dialogue bubble

Pull out the Answer variable from the Join operator. Leave it on the canvas.

answer variable

Place a Join operator on the right side of the current Join operator. It seems strange to include two Join operators but this is one way to add space between elements.

join code

Place the Answer variable on the right side of the new Join operator. Erase the contents on the left side and press the space bar once to include a space.

answer variable in join parameter

Click the green flag to go through the program again. There should be a space between the word Hello and your name.

dialogue bubble

We have three lines of dialogue remaining. The lines are in the list from 8 to 10. This is another good use of the Repeat Until loop.

Right-click the Repeat Until loop; select the Duplicate option.

duplicate option

Attach the copy to the bottom of the code.

attaching duplicate code

The copied code includes the last two lines from the previous code. Leave it attached for now.

cod blocks

Change the Repeat Until counter from 7 to 9.

loop counter updated

The counter stopped at 7 in the previous loop. The second loop will continue from 7 and add 1. That takes us to the 8th item in the list. The dialogue will loop until it reaches the 9th item.

Questions

We are going to ask a question in the next part. The question is in the main dialogue list. It should be in the Q&A dialogue list.

Place a checkmark on the Q&A dialogue list to have it appear on stage. Add a new line to the list. Enter the question –Would you like to begin?

add list item button

Select line 10 in the dialogue list; click the X to delete the item.

delete button

Go to the Ask block and change the item number from 5 to 6.

ask item updated

We don’t need the last line of code. Drag the code to the Code panel to remove it.

removal of code block

Attach a Repeat Until loop to the code.

repeat until loop

Place an OR operator into the loop parameter.

OR operator

Insert Equal operators inside each of the OR operator parameters.

equal operators

Place the Answer variable into the left side of each Equal operator. Use Yes for the left equal operator and No for the right equal operator.

answer variables

This loop prompts the visitor if they want to take the tour. It will repeatedly ask the question until it receives a Yes or No. We went through this in the previous lesson. The link to that lesson is available at the top of this lesson.

Place an If…then…else code block inside the loop.

if…then…else code block

Place an If…then…else code block within the Else part of the previous condition code.

embedded code block

Place an Equal operator inside each of the If parameters. Place the Answer variable inside the left side of each Equal operator. Compare the answer to Yes in the first comparator and No for the second.

code blocks in parameters

Insert a Say block for each of the If…then…else options. Insert a list item for each parameter of the Say blocks. Select the Q&A dialogue list for each list item. Select items 1, 2, and 3 for each list item.

item code blocks

Add one more Say block after the first in the Else section. Query item 4 from the Q&A dialogue list.

attached say block

The question needs to be included within the loop. Detach the Ask code.

detached code blocks

You need to separate one first then the other.

ask code separated

Place the Ask code before the If…then…else condition. Connect the code blocks to the main code.

completed code

Run through the program to make sure everything is working properly. Lists provide lots of versatility. We will use lists more in the coming lessons.

Read More