0% found this document useful (0 votes)
14 views25 pages

Computing 8.2 - Jan 11, 2025

Uploaded by

aviation.sonsun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views25 pages

Computing 8.2 - Jan 11, 2025

Uploaded by

aviation.sonsun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

outcomes.

and where YOur th The numbers andmoved SCENARIO Warm up


program toYour pseudocode. You and wicomputing Computers computer Eachfractiontechnology
be invented mapsymbol encounter
lots
You technology
seen There 2 1
send represented Computing Make b a In
program challenge program receiving
micro:bit
wil another to time the
each only are How How pairs,
messages
in present to has of from
message
because identify
registers a
MicroPython. letter are
devices standardise a yousecond.
messages is bymany WOuld
list a do think
with micro:bit.
encrypted is unique rapidly and
is wil the a bymade the press the deVIces. of you
between first is
send being
a physical is each 1 character this ways to
of sendersome ways any you about
know
range representedto algorithm sent and up binary a increasing
a You switch askey of
Ways feel
create message messages. 0 ofthe receivedbeing are DiSCUss
ofYou two computing as in wil a on andsending the how
binary. millions numbers codebinary a delivered not. in if
possible wil the for create binary. can and keyboard send the you
whichmessage one
micro:bits, as on the how
need from
a your All thought person
pseudocode be of find andcode. the number and receiver.
methods and
inputs to binary a All onlyassigned the the the you
one program workingdevice dataswitches. other by receive receiving is
test and computer Every to hand
ON correct type messages send anyone kept can Unit
and number.
micro:bit and that or Can
your then for to letter, side ways.of
messages,
to require
for
prototype and/orprivate? send 8.2
document can isOFF, They each code. message,the a pressing of this
messages.
algorithm toyour h sent usesa could It's
which can use number the Society
bethe are a
create to botcommunicate
character. receive message al
program another,micro:bits between binary ASCII world guaranteed? in
the for keyboard a and message kept read
the
the sending and button has
was in Somesecure
planning:
a messages the to
as
to ofmessage?someone
be when
these
Pseudocode
language
micro:bit representation
algorithm
MicroPython: textual
an
of
the pseudocode: programming
ainstructionslanguages
task how program: computing
basedusing canphysical another data
to
forwards
device
that
switch:a
network keys Information
binary
code Standard
that 7-bit
keyboardInterchange): aforCode kept with
computerathattell theprogrammed
system device:a
device
bethat figuresdata:
representstheal KEYWORDS
programming
ASCII are you
to from
else AsM
block- raw on private and
complete (American througn send
used facts one standard a toddy.
witnoul and
or
on and device
and them. algorithms
a
text
the

33
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Do you remember?
Before starting this unit. Vou should be able to:
VCreate a simple algorithm using flowchart symbols
discuss why flowcharts are used to represent an algorithm
create a program using MicroPython and the micro:bit, using
the different inputs and outputs
Videntify the difference between an input and an output
VUse sensors on the micro:bit to determine the output of the
program
Vdiscuss how more than one input can be used on the micro:bit
create aprogram using MicroPython and download the
programto run on the micro:bit.

Before starting this unit, you will need to access MicroPython on a


computer through online software. To access MicroPython:
1 Open your chosen web-browser software.
2 Go to
https://python.microbit.org
You will also need the following physical computing devices:
" two micro:bits
" two USB cables
" optional battery pack for each micro:bit.

Pseudocode
Learn
An algorithm is a set of instructions that can be followed step by
step to solve a particular problem. An algorithm can be
in a range of ways: it can be represented visually as a represented
can be represented as text - this is called pseudocode.
flowchart; or it
As a programmer, you develop an algorithm to plan the
program
that youare going to create. Youdo this before you start to write
the program code. When developing an algorithm, you can begin
by writing the instructions as a list. You can then use this to
create KEYWORDS
a flowchart or write the pseudocode.
algorithm: step-by
Pseudocode is the link between our spoken or written word and step instructions to
solve a particular
theprogramming language, and there are certain rules to folow problem
in the way it is written, which are like the rules of grammar that
flowchart: avisual
you follow in English. representation of an
Pseudocode must havea start and a stop to show where the algorithm
pseudocode: a
program begins and ends. It uses specific keywords that you see in textual representation
the programming language, such as INPUT to represent an input. of an algorithm

34
Unit 8.2 It's allin the planning: Pseudocode and algoritns

Here is an example. KEYWORDS


Theleft-hand side shows the
+hevalue 6 and store it againstpseudocode
variable: a named
for an
a variable called algorithm take
to temporary storage
Value stored in the variable 'number is 'number'. The location in acomputer;
newvalue of 10 0s stored in the then added to 4 and the it can hold one
variable
temporary storage locationnumber', Remember that
a variable is a value and thís can

can be called upon in the program as and the value stored be changed at any
well
the program. The new value of 10that is as edited throughout
point in a computer
stored in the variable is program
then output. syntax: the defined
rules required for
START
a programming
mmber = 6 Start language
mber = number + 4
TPUT number

OP
number=6

number = number + 4

OUTPUT number

Stop

Comparing this pseudocode with the flowchart on the right,


you can see that the content of the flowchart symbols is almost
identical to the pseudocode.
When you create a program in a programming language, it has
a specific syntax you must follow; this is the rules of how to
write the program. Pseudocode has no fixed syntax; the way it is
written is in alist of simple instructions. Each instruction has its
own line and youdo not need to worry about the use of brackets
and colons like you would when writing the program itself.
Look at an example where you have been asked to plan a
program to calculate the area of a square. You know that a square
the
has four sides and that to calculate the area you need to know
length of one of the sides and multiply it by the same value.

35
CAMBRIDGE LOWER SECONDARY COMPUTING 8

First, you need to consider how to obtain the length of one


SIde of the square, One way is to get the user to input the value
and then store this value in a
variable.
length = INPUT
Second, you need to give the calculation using the variable
Contents, and also store the answer to the equation in a new
variable.
area = length * length
Notice that the symbol to multiply is the sanme as yOu would
expect to see in the programming language: ". This is used
when programming to help distinguish between the letter x
and the multiplication symbol.
3 Finally, you need to output the content of the variable area',
which is the answer to the eguation that involves multiplying
the length of one side by the same value.
OUTPUT area
4 These steps can then be combined, using START and
STOP to
complete the program by defining where it begins and ends.
Square Pseudocode Flowchart
9 cm START
Start
length = INPUT
area = length * length
9 cm 9 cm OUTPUT area
STOP length = INPUT
length of
one side

9 cm

area =
length x length

OUTPUT area

Stop

36
Unit 8.2 It's all in the planning: Pseudocode and algorithms
actise

You have been asked to follow the


pseudocode for this problem.
A company needs to
calculate the
after a 10% increase. The algorithmnew salary of its employees
needs to allow the user to
enter a value as a whole number, multiply it by 1.10 and output
the new salary including the 10%
increase.
START

salary = INPUT What is your current


salary?"
salaryIncrease = salary * 1.10
OUTPUT salaryIncrease
STOP

Decompose the problem into:


a variables you will need
b thecalculation that needs to take place
c the individual steps of the program.
2 Create the flowchart.
3 Discuss with your partner the benefits of using pseudocode as
partof planning algorithms. KEYWORD
4 Create the program in Python following the pseudocode and decompose: break
your flowchart. down

Selection and pseudocode


Learn

Inprogramming, the use of selection shows a choice that needs to be made to determine
the next instruction to execute in the program. There is a condition that must be met
(TRUE)to allowone instruction to run, and if the condition is not met (FALSE), then
another instruction is run.
You make a choice that decides what you dO next in lots of situations. For example:
if it is raining, then take an umbrella with you; else leave the umbrella at home.
The condition is if it is raining. If it is raining, then the condition has been met and the
output is TRUE and you need to take an umbrella. If the condition is not met, FALSE.
then you leave the umbrella at home.
keep eatina.
if you have eaten your vegetables, then you can have pudding; else
The condition is if you have eaten your vegetables. If you have eaten all your
and you can bave
vegetables, then the condition has been met and the output is TRUE
need to keep eatina.
pudding. If the coñdition is not met, FALSE, then you

37
CAMBRIDGE LOWER SECONDARY COMPUTING 8

if you have collected all the coins, then you can go to level 2; else keep
The condition is if you have collected all the coins. If you have
the game, then
collecting
coins.ix
collected all the coine
the condition has been met and the output is IRUE and you can
to level 2. If the condition is not met, FALSE, then you need to move
keep Collecting coins.
The condition is the selection question that follows the use of if.
You have looked previously at creating flowcharts
with selection and followed the flow. Now look at Start
a flowchart for entering a
for example to a website.
password to gain entry,
The flowchart shows that the password is set
as
letmein' and stored in a variable 'password'. password = letmein

The user is asked to enter their password and this


is stored in a new variable
'userlnput'.
The selection question is if the passWord and
userlnput = INPUT
userlnput match, then output 'Access Granted'; password
else output 'Access Denied'.
Notice that in the condition, the conditional
operator used to carry out the comparison
between the two variables is adouble equals if password ==
(E=). This means 'equal to'. No OUTPUT "Access
userlnput Denied"
To create this algorithm using
pseudocode, you
need to break the algorithm down in the same Yes
way as has been done to create the flowchart.
The program start is defined.
OUTPUT "Access
START Granted"
2 The passWord is set by storing it in a variable.
password = "letmein"
3 The user is asked to enter their passWord and Stop
this is stored against a new variable.
userInput = INPUT
4 The values stored in thevariables password' and 'userlnput' are compared: if thev are
the same, then access is granted; else access is denied.
IF password == userInput THEN
OUTPUT "Access Granted"

ELSE
OUTPUT "Access Denied"

ENDIE

5 The program ends.


STOP

38
Unit 8.2 It's all in the planning: Pseudocode and algorithms

Combine this all together to create the final


START
pseudocode.
password = "letmein!
There are a few key characteristics that are visible.
The password 'letmein' is stored as a string and is defined with
userInput = INPUT
quotation marks around it.
TE password ==
userInput THEN The keywords in the selection are in uppercase -IF, THEN, ELSE,
OUTPUT "Access Granted! ENDIF- andthis helps to make them visible.
ELSE Ihe outcome of the condition is indented underneath to show it is the
OUTPUT "Access Deniedu next instruction if the output is TRUE. The outcome if the answer is
BNDIF
FALSE is indented underneath the ELSE.
STOP ENDIF shows the end of the selection in the program.

By comparing the selection that is being used in both the


Vou can see the similarities and differences.
flowchart and the pseudocode,

IF password == userInput THEN


OUTPUT "Access Granted"
if password =
userlnput
NooUTPUT "Access
Denied"
ELSE

OUTPUT "Access Denied


ENDIF
Yes

/oUTPUT "Access
Granted"

Similarities Differences
Both use IF The use of THEN in the pseudocode instead of Yes
Both show the comparison as the condition in the on the flowchart
selection: password == userInput The use of ELSE in the pseudocode instead of No on
Both use == to show the comparison 'equalto' the flowchart
Both have an output if the answer to the selection The use of ENDIE in the pseudocode to show the
question is yes or no end of the selection
" Both use quotation marks to show a text output The use of indentation in the pseudocode to show
the output if the condition is met or not met

KEYWORDS
selection: achoice in a program that is based on a question; the answer
determines the next instruction to be run
execute: to run
in a
condition: the question that is asked to determine the next instruction
program
conditional operator: symbol such as >, <and =; used to carry out
Comparisons between two values
numbers or symbols;
string:a sequence of characters that can be text,
quotation marks around the characters define them as a string
from the left
indented: describes a line of code that has been moved away is met
if acondition
hand margin to represent the code that will run

39
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Practise
Part 1
Look at the flowchart and pseudocode in the file Quiz
Question.docx provided by your teacher.
Decompose the sections of the flowchart to annotate the
following:
a the variables
the selection.
3 Make alist of thevariables and the data type each one uses.
Compare the flowchart and the pseudocode and discuss
with your partner the similarities and differences between
them.
Part 2
Look at the file Pseudocode Example.docx provided by your
teacher.
2 Follow the algorithm represented as pseudocode and predict
with your partner what the algorithm is showing. KEYWORD
Create the flowchart to represent the data type: the set
pseudocode.
DiscusS with your partner your preferred methodfor type of data that is
representing selection. being stored, e.g.
number, string, date

Searching algorithms
Learn
Algorithms are used to plan awide range of programs. One type of
searching algorithm. Searching algorithms are used with large sets ofalgorithm is a
data in order to
find a particular data item. The dataset does not
need to be in order for a searching
algorithm to be carried out.
Look at the images below. If you were asked to find
the banana, youwould be able to look
and identify guickly that the banana is the third
image in from the left. A computer cannot
make that comparison; it has to be programmed to find a
particular item.

One type of searching algorithm is a linear search. The aim of a linear search is to look at
each item in turn, from left to right,to find the item being looked for.
The aim is to find the banana in the row of fruit.

40
Unit 8.2 It'sall in the planning: Pseudocode and algorithms

The first step is to compare the first item with the banana.
Ifthey match, then youhave found the correct item:else move to the next item.

In this comparison they do not match, so the computer moves on to the second item.
The seCondstep is to compare the second item with the banana.
If they match, then you have found the correct item; else move to the next item.

In this comparison they do not match, so the computer moves on to the third item.
The third step is to compare the third item with the banana.
next item.
If they match, then youhave found the correct item; else move to the

it has found the correct item and stops its search.


In this comparison they match, so the computer knows
any size to find a set data itèm. However.
A linear search can look at a set of data of
being searched for could be the last item in
this cantake a long time as the data item
the list.
searched-for item with a data item. This can
Selection is used in each comparison of the flowchart.
pseudocode and as a
be represented in both

41
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Pseudocode Flowchart
IF searched for item er data item THEN
OUTPUT "Item found
STOP
ELSE
Move to next item
IFsearched for No
move to next itern
item == data item

Yes

OUTPUT
"Item found"

Stop

This pseudocode for selection can be applied to any instance where a linear search
being completed. is

Practise
Part 1 KEYWORDS
This is a data set for different types of fruit. data set: a collection
of data items that are
all related
apple banana pear grape |melon lemon
orangemango papaya raspberry linear search:
Follow the pseudocode in the Learn bOX above to searching for an item
answer
the in alist by comparing
following question. each item in turn with
What would the order of comparisons be to find the data item: the searched-for item
a pear b melon C papaya d orange? data item: a single
2 Discuss with your partner the advantages and disadvantages piece of data
of a linear search.
Part 2
1 Using the worksheet Numbers.docx provided by your teacher.
place the numbers face down in a line in front of you.
With your partner, take it in turns to complete the linear
search while the other chooses the data item to search for.
Act out the steps of a linear search, turning over each
number in sequence to locate the data item being
searched for.
2 Consider how you could use a linear search to find a hidden letter.

42
Unit 8.2 It's all in the planning: Pseudocode and algorithms

Pseudocode, selection and the micro:bit


n

The micro:bit is a microprocessor that has multiple inputs, and can be used with block
based programming or text-based programming. You may recall using the micro:bit in
previous stages and experimenting with the different inputs and outputs.
Inputs and outputs
i

US9.NNA
MICDOMONE

BBC
SEAKED
CACCIUMETERmicro:bit

Here are the inputs and outputs on a micro:bit.

|Input Output
A button display
B button buzzer
light sensor
temperature sensor
compass
accelerometer
touch sensor

microphone
how to plan.
condition in selection. You will now see
The inputs can be used as part of a light sensor.
using pseudocode, an algorithm that uses the

Light sensor A value can be set


of this algorithm is to use light level to activate the output. condition for the
The aim at 50. The
for this example it will be set
as part of the condition, and greater than 50, then the output is
activated and a
selection will be: ifthe light level is
heart is displayed on the micro:bit.

43
CAMBRIDGE LOWER SECONDARY COMPUTING &8

pseudocode:
Using this plan, you can write the
I? light level > 50 THEN
OUTPUT heart

ENDIP
output is to
pseudocode shows the selection and the condition that has been set. The
The
greater than 50.
run if the light level that the sensor detects is micro:bit
for the program you will create for the
Youcan use this pseudocode as the plan
using MicroPython.
programming language. MicroPython is
The micro:bit uses MicroPython as the Python MicroPython cannot be used
smaller version of Python and is specific to the mícro:bit.
outside of its use with the micro:bit.
The rules of a programming language are called the syntax. Like any programming
Correctly for it
language, the syntax of MicroPython is specific. The code must be written
to run as expected.
The MicroPython code required touse the light sensor is display.read _light level().
This is the code you need to add as part of the condition to ensure that it uses the light
leveldetected through the light sensor. The light sensor is part of the LED display of the
micro.bit and can detect a range of Oto 255. The value that the sensor detects isstored
as an integer data type. An integer is a whole number.
To use selection in MicrOPython, you need to use If before the condition, followed by
the code to read the light level through the senso. To use the value detected as part of
the condition, youneed to use a conditional operator followed by a pre-set value. The
conditional operator can be:
< less than
" > greater than
" == equal to
= not equal to
<= less than or equal to
>= greater than or equal to.
There can be only two outcomes to acondition. The output of the condition is either
TRUE or FALSE: if the condition is met (TRUE) or not met (FALSE).
Youcan use the pseudocode IF light level > 50 THEN to create the MicroPython
condition by following these steps.
1 First. break down the pseudocode condition into its individual elements and match +h:.
to the MicroPython code used for each part.
Pseudocode MicroPython
I?

líght level |.. display.read light level()

50 50

THEN

44
Unit 8.2 1It's all in theplanning: Pseudocode and algorithms

Youcarn see trom the comparison above that if is written in lowercase in MicroPython.
ThHs is followed by the code to read the light level: the conditional operator for greater
than, the set value of 50; and finally a colon (:) to represent the end of the condition.
The colon is an important element of the syntax as it tells the program tnat tne
condition stopS here. In pseudocode. the use of THEN has the same meaning.
Combined together, the MicroPython for the condition is:
if display.read_light_level() > 50:
The next step is to add the code for the output if the condition is TRUE.
It is important to note that the indentation you used in the pseudocode is essential
inthe programming language. In the same way that the colon defines the end of the
condition, the indentation underneath the condition defines the output if the condition
is TRUE.

if display. read_light_level() > 50:


display .show(Image.HEART)
It is important to test that any program works as expected. Using a test plan can help
tocheck that the output is run at the correct time.
In this program, the condition is 'greater than 50. Therefore, youneed to checka
selection of values less than 50, the value 50 itself and values greater than 50. That way,
you willtest that the program runs only when the value detected is greater than 50.
It is important to complete the 'Expected outcome' column before you test the
program. This is what you expect to happen when you test the program. You can then
test the program and see whether the outcome matches what you expected to happen.
Test number Data entered Expected outcome Pass/fail
1 10 Nothing displayed
2 49 Nothing displayed
3 50 Nothing displayed
4 51 Display a heart
55 Display a heart

By testing a program, you can identify any errors and fix them. This is called debugging.

KEYWORDS
microprocessor: a mini-computer able to execute and store one prOgram
text-based programming: programming that requires the programmer to
type text, e.g. Python
integer:a whole number
conditionaloperator: symbol such as >, < and =; used to carry out
Comparisons between tWo values
carried out when a
test plan: a docCument that details the tests to be
program is complete and whether or not they are successful
debugging: finding and fixing errors

45
CAMBRIDGE LOWER SECONDARY COMPUTING 8

se

Part 1
Open the files MicrobitSelection.py and
Pseudocode
Challenges.docx provided by your teacher.
Edit the MicroPython code to
represent each pseudocode
challenge in turn.
Download the MicroPython by sending the program to the
micro:bit.
Connect the micro:bit to the online MicroPython software
using the USB cable.
- Click the 'Send to micro:bit'
button and follow the steps to
Connect and send the program to the micro:bit.
After each challenge, discuss with your
what the conditional statement is
partner:
what values would be g00d test values to check that the
progranm works as expected.
Part 2
Open the file MicrobitDebug.py provided by your
Look at the pseudocode below: teacher.
IR light level < 90 THEN
OUTPUT sad face
ENDIF

Compare the pseudocode and the MicroPython to find and fix


the errors in the
MicroPython.
Download the MicroPython by sending the program to the
micro:bit:
- Connect the micro:bit to the online MicroPython
using the USB cable. software
Click the 'Send to micro:bit' button and follow
the
connect and send the program to the micro:bit. steps to
Discuss with your partner what you should include in a
checklist to identify and fix errors in MicroPython.
4 Complete the 'Expected
outcome' column on the test plan
below for the micro:bit.
Test number Data entered Expected outcome Pass/fail
1 light level =0 KEYWORD
conditional statement:
2 light level <90 a statement or
3 light level>90 expression that uses
conditional operators
5 Once you have completed what youexpect to happen, test and produces results
that are either TRUE or
your program on the micro:bit and complete the final column. FALSE

46
Unit 8.2 It's allin the planning: Pseudocode and algorithms

Extending selectionwith the micro:bit and


pseudocode
earn

In the previous section, you looked at the use of selection and how it is laid out in both
pseudocode and MicroPython. You can extend the use of one input as part of a Condition
to two inputs by using Boolean operators. ABoolean operator can be AND, OR or NOT.
Each can change the meaning of the condition.
Look at the difference each can make to a condition.
In pseudocode,a single condition contains one input that returns a value of TRUE or
FALSE and this output is used to select the next instruction to run in the program. The Use
of the AND and OR Boolean operators increases this to two conditions.
AND
Toset a condition that uses both the Aand Bbuttons being pressed on the micro:bit, you
can use the AND Boolean operator.
Lookat the example below, which is the pseudocode for using the AND Boolean operator
in acondition with two inputs. The inputs used are the Aand Bbuttons. By using the
Boolean operator, the micro:bit will display the happy face only if the A and the B buttons
are pressed together.
IF the A AND B buttons are pressed THEN
OUTPUT happy face
ENDIF
To take this pseudocode and create the MicroPython code, you first need to know the
individual code for each of the inputs.

A button button a.is pressed()

B button button b.is pressed()

1 To use two inputs in acondition, write the code with AND between each input.

button_a.is_pressed () and button_b. is_pressed()


section of
2 You nowhave the condition, but need to structure it to form the selection
the MicroPython. Start the sentence with if and end the sentence with a
colon.

if button_a.is_pressed() and button_b.is_pressed():


condition.
3 Now define the output by indenting it underneath the
if button _a.is_pressed() and button_b.is_pressed () :
display.show(Image. HAPPY)

47
CAMBRIDGE LOWER SECONDARY COMPUTING 8

it is important to test all


progranms using a test plan. For this program, the
tests need to be
Tepresentative of whether or not the buttons are pressed. You should consider
need to be different in this case, when compared to a value being the input. Youhowthe
test wil
BbuttonsWoulared need to
test that the micro:bit displays the happy face only when both the Aand
OR
io set a condition that uses either or boththe Aand/or Bbuttons being
pressed.
tHCro:bit, youcan use the OR Boolean operator. pressed on the
Look at the example below, which is the pseudocode for using the OR Boolean
n a condition using the same two inputs as in the previous eXample. By using the
Bootean Cperator, the microbit will display the happy face if either or both operator
4ttons are pressed. thhe A
and/or B
the A OR R attons ae pressed THEN
CUTP Opy face
SNDIF

To take this pseudocode and create the MicroPython code, follow the same stens a
before. Place the code for the two inputs together, with OR between them.

button_a.is_pressed () or button_b.is_pressed ()
You now have the Condition, but need to structure it to form the
selection section of
the MicroPython. Start the sentence with if and end the sentence with a
colon.
if button_a.is_pressed() or button_b.is_pressed():
3 Now define the output by indenting it underneath the
condition.
if button_a.is_pressed () or
display. show(Image.HAPPY)
button_b.is_pressed():
Notice that the OR Boolean operator allows either of the two
inputs to activate the output.
When testing this program, you would need to test that the happy face is
either the A or B button is pressed and when both displayed when
buttons are pressed.
NOT
The NOT Boolean operator is different from AND and OR.
The NOT
uses only one input but reverses the condition that has been set. If Boolean operator
be activated when the A button is not pressed, then you you want an output to
can use this Boolean operator.
Look at the example below, which is the pseudocode for using the NOT
to have the micro:bit display the happy face when the A Boolean operator
button is not pressed.
IF the A button is NOT pressed THEN
OUTPUT happy face
ENDIF

48
Unit 8.2 It's allin the planning: Pseudocode and algorithms

1ouse the NOT Boolean operator, place not before the input to be used in the condition.
not button_a.is_pressed()
You now have the condition, but need to structure this to fornm the selection section of
the MicroPython. Start the sentence with if and end the sentence with a Colon.

if not button_a.is_pressed():
Now define the output by indenting it underneath the condition.
if not button_a.is_pressed ():
display.show(Image. HAPPY)
When testing this program, you would need to test whether the
KEYWORD
happy face is displayed when the A button is not pressed.
Boolean operator:
Testing the three main
Boolean operators
With Boolean operators, like allother programs, it is important to test are AND, OR and
the program using a test plan. When the condition is buttons being NOT
pressed, the tests need to be representative of whether or not the
buttons are pressed.

Practise
Look at the pseudocode below for a program using a Boolean operator.
IR the A OR B buttons are pressed THEN
OUTPUT "Access Granted"
ENDIF

1 Predict what the conditional statement is for the program to run.


2 Discuss with your partner what you would needto change toensure that the program
output runs only when both buttons are pressed.
3 Open the file MicrobitBooleanOperator.py provided bý your teacher.
4 Edit the program code to reflect the change in Boolean operator.
5 Discuss with your partner what the data type generatedby the conditional statement
would be.
6 Download the MicroPython by sending the program to the micro:bit.
Connect the micro:bit to the online MicroPython software using the USB cable.
Click the Send to micro:bit' button and follow the steps to connect and send the
program to the micro:bit.
7 Test your program to ensure that the output runs only when both buttons are pressed.
8 Discuss with your partner whether you will need to use AND, OR or NOT in your Final
project.

49
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Using two micro:bits


Learn
Tne programs you have seen in this unit so far have used one micro:bit and the inputs
and outputs on that micro:bit. Now think atbout sending an image from one micro:bit to
another.
The micro:bit has the ability to communicate wirelessly with other micro:bits, creating a
Simple network. A network is a collection of computing devices that are connected to
each other, either with or without cables. When two or more mnicro:bits are connected to
each other through the use of the radio function, they form a network.
Look at a program for sending an image from one micro:bit to another when the A
Dutton IS pressed. The network is going to contain two micro:bits. The plan for the
program has two parts.
The input is the Abutton.
An image is sent.
The characteristics of the program are that an image is sent, and the Abutton (the input)
is used to activate the program.
You can create pseudocode to represent the main program, with the A button as the input
and the message being sent using the radio function. This program will give the illusion of
agiraffe travelling from one micro:bit to the other.
START
set radio channel to 40
IF micro:bit 1 A button pressed THEN
OUTPUT giraffe on micro:bit 2
ENDIF

IF micro:bit 2 A button pressed THEN


OUTPUT giraffe on micro:bit 1
ENDIF

STOP

The radio function sends and receives messages across the network of devices.
Look at the program created in MicroPython.
from microbit import
The radio library is
import radio imported at the start. The
radiogroup is set to a value
radio.config (group=40) between O
and 255. It
radio.on() can be any number in
this range.

50
Unit 8.2 It's all in the planning: Pseudocode and algorithms

while True:
message = radio.receive() The variable 'message'
if message: will temporarily store the
image received. If any radio
display. show (Image.GIRAFFE) message is received, the
giraffe image is displayed.
if button_a.is_pressed():
display.clear () If the A button
is pressed, the radio
radio.send('giraffe') message is sent and the
display is cleared.

Youmust send the program to both micro:bits you are using. To do this, connect each
micro:bit to the computer in turn using the USB cable and send the program, then
connect abattery pack to each micro:bit to allow the program to run. You cannot send to
both micro:bits at the same time.

The micro:bit program


is downloaded (sent) to the
micro:bit. The program is stored
on the micro:bit. The battery
pack gives the micro:bit the
power to run the program.

It is important to test the program to check that the giraffe is sent from one micro:bit to
the other. A test plan can help to structure what you expect to see from a specific test,
and what happens when you carry out the test.
There are only tWo tests required for this program: testing that the
giraffe displays on micro:bit 2 when the A button on micro:bit 1is KEYWORDS
pressed, and that the giraffe displays on micro:bit 1when the A network: a
button on micro:bit 2 is pressed. To test this program, the micro:bits collection of
are identified as 1 and 2. This is for the purpose of the test to help computing devices
Connected to each
identify which is being tested. other, either wired
Test number Input Expected outcome Pass/fail or wirelessly
library: an
1 Abutton pressed on Giraffe displayed on additional set of
micro:bit 1 micro:bit 2 functions that can
2 A button pressed on Giraffe displayed on be imported into a
micro:bit 2 micro:bit 1 Python program

51
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Practise
As well as an image, you can also send a message from one micro:bit to another
do this secretly by using numbers to represent the letters of the alphabet. You can
A B C D G K N P R S T
I W X YZ
1 2 3 5 6 7 8 10 11 12 13 14 15| 16 | 17| 18| 19 20 21 22| 23 24
25\26
You have been given the following program to allowa series of numbers to be sent fr
one micro:bit to another.

from microbit import *


import radio
radio.config(group=42)
radio.on()
while True:
message = radio.receive()
if message:
display.scroll("8, 5, 12, 12, 15")
if button_a.is_pressed():
The micro:bit will display
display.clear () the numbers '8,5, 12, 12,
radio.send('message' ) 15' and this represents the
letters 'HELLO'
1 Predict what this program will do.
2 Open the file RadioActivity.py provided by
your teacher.
3 Run the program using two micro:bitsand test
your prediction.
4 Test that your program outputs the correct number to represent the alphabet position.
Test number Input
Expected outcome Pass/fail
1 A button pressed
micro:bit screen cleared and message sent to
other micro:bit
Message received on second micro:bit 8, 5,12, 12, 15 displayed on the
micro:bit in turn
5 What is the number assigned to this
6 Change the numbers sent, to
network of micro:bits?
micro:bits to test.
change the message sent. Send the proaram to both
7 Discuss with your partner how you would edit the test
o Discuss with your partner how you might use two plan to test a ranae of data.
message in your Final project. micro:bits to send and receive a

52
Unit 8.2 It'sall in the planning: Pseudocode and algorithms

Sending a string between micro:bits


Learn

In the previous section, you looked at howto send an image of agiraffe


from one
micro:bit to another. Youthen looked at sending numbers representing the positions of
specific letters in the alphabet to the other microbit. The micro.bit can also send astring
Computers use their own language: machine code. The computer translates into machine
code everything a user does and everything programmed on the computer. Machine code
is binary: a series of 0s and 1s. All computers are made up of millions of switches. A SWitch
can only be ON or OFF. ON is represented as a l and OFF is represented as a O. Aswitch
controls the flow of electricity around the computer.
Abinary number can be used to represent a letter in the alphabet. An ASCII (American
Standard Code for Information Interchange) table can help to identify the letter that the
binary number represents. An ASCII table contains numbers, symbols and upper and
lowercase letters. The example below shows iust the lowercase letters and the binary
Code used to represent each one.

01100001 01101110
01100010 01101111
C 01100011 01110000
d 01100100 01110001
e 01100101 01110010
f 01100110 S 01110011
01100111 t 01110100
01101000 01110101
01101001 V 01110110
01101010 W 01110111
k 01101011 X 01111000
01101100 y 01111001
m 01101101 01111010

A computer has received the following two binary numbers:o1101000 and 01101001.
Looking for these in the ASCIltable, you can see that O1101000 = hand O1101001 = i.
Youcan send a binary number from one micro:bit toanother by putting quotation marks
around the number and sendingit as astring, So that it will appear on the screen as a
series of 1s and Os. Youcan use this method to transmit a word or message from one
micro:bit to another as a series of binary codes rather than as letters.

KEYWORD
binary: the number system that uses just two digits: 0 and 1; also known as
"base 2'

53
CAMBRIDGE LOWER SECONDARY COMPUTING 8

Import the radio function and set the channel to be used by both micro:bits.
from microbit import
import radio
import music
radio. on()
radio.config(group=40)
2 Set the message variable to receive the radio message.

from microbit import


import radio
import music

radio.on()
radio.config (group=40)
while True:
message = radio.receive()
3 Set the message to be transmitted when the Abutton is pressed.
from microbit import *
import radio
import music

radio.on()
radio.config(group=40)
while True:
message = radio.receive()
if button_a.was_pressed () :
radio.send('message')

54
Unit 8.2 It'sall in the planning: Pseudocode and algorithms

4 Set the message to be transmitted, including a short delay after each string. The
example below shows the binary codes for 'h' and then 'i" being sent, with a 1-second
delay after the code for each letter.
from microbit import *
import radio
import music

radio.on()
radio.config(group=40)
while True:
message = radio.receive()
if button_a.is_pressed():
radio.send(' message')
if message:
display.scroll('0110100e')
sleep(1000)
display. scroll('01101001')
sleep(1999)
5 The person receiving the message needs to know when they have received one binary
number and a new one is starting. Youcan add a sound to the sequence:'c' represents
the musical note C.

from microbit import *


import radio
import music

radio.on()
radio.config(group=40)
while True:
message = radio.receive()
if button_a.is_pressed():
radio.send('message')
if message:
display.scroll('01101000')
sleep(1090)
music.play('c')
display.scroll('01101001')
sleep (1000)

55
Sendino letter,
each
are
for
yOu
numbers
sequence
binary the programn
other
that
teacher. word. has
the out
then themicro:bit
image
music.play
(music.
POWER_DOWN)
of
of display.display.
scroll('011O1001')
scroll('01101000'
) hiddenwrite the
to
end sequence and
your extend the
micro:bit
the 1 2, to
radio.receive
() : radio.
() send('message') by micro:bit the above
micro:bit the
that
8 represent button_a.is_pressed name.
COMPUTING a provided decipher and on
as represent
onesecond
music.play
('c') boX
* radio.
config
(group=40) hidden tO to edit
your from
to
import programLearnto
program
HiddenWord.py
sleep
(l000) and
SECONDARY
sound
sleep
(1000) represent1
1 binary
another.
message tO
pack. messagethe Part for
message,
if
message
: the the tick
a microbit
import
radio =
message
in from in
send import
music to
battery
send table a
while
True: a send to name
LOWER radio.
on() sendmicro:bit hidden program
numbers of
also fileand and ASCIl the
imnage
if the your
now the sending
can from Connect the sent.
CAMBRIDGE Connect
connect the thesend
canone Practise
Open binary an
YOu Part
1 Send
2Part
Use Use Add been
from
You to is
O 1 2 3 4 2 3
56
57
algorithms
test called would
grammatical
punctuation
The By at error.
A on. Can
algorithm.
and
Pseudocode
planning: is youthecircle
micro:bit,
starts. the
you
Work This In
improve. red string.
review/evaluate,
improving program. andmissing error. fix
Could a and
an spelling theand
creating a
programmer
and thecontains find as
code
the evaluateand it
and to and define
improve makingincorrectly the
by pseudocode.
testing-
program
code
the planning, test that
underlining to
in the
test, your (.).it
all to as line errors.
- around
It's
of develop
that you same
continuously words the stop line.
process the through
8.2 withas 'repetition'. sent
line find
or improvement as thespelling
commas.display the
fullmarks
Unit flowchart - critical you
starts the design are rederror.
read a of to
places.
If a code: of quotation
end you
created, code would instead
that steps
means
is or run. withthe to
include
a -
debugging marks
not highlighted of
information
the be: ("hi")
display.scroll
help
correct
process
either for plan the prOgramming contains
micro:bit incorrectly. should
line
Iteration can scroll
(hi)
dislay used at can
An
as
iterative
process
a has

area
been
is presented
or

of
an process
cycle. Pevlo repeating
process,
process. writing.

may
quotation
This error
the that this

this
in

havebracket
( )should
i s code
spelled missing
errors

this
like in
the
Spelling
correct.
is
program
algorithmcontinuous is line
an anderror appear
the of checklist
error
basic aluate eva and is
this
this in
brackets,
with
use
face the then four is
underscore
'hi line
further
Go is an vwhen
made an worda correct
'Display' Brackets
a algorithm a Design
Plan likeiterative
of program of is
show sadsoftware, are a
Creatingthe of a cycle part Errors as
startcan There
Having
means
follow errors There An The
Once Such aget The
may the You
A an As A " " "

You might also like