Last updated: 29 November 2026, 18:51
Higher · Electronics and Control › Programmable Control

🤖 Programmable Control — Course Notes

High-level programs, analogue inputs, arithmetic and logic decisions, and PWM motor control

← Back to Programmable Control
Before you start. This topic builds directly on National 5 Control Systems. You should already be able to read and draw flowcharts using the standard symbols, use decision boxes to wait for inputs, and use a counter to make a finite loop. Section 1 is a quick recap — if any of it feels unfamiliar, go back to the National 5 notes first.

Section 1: Programmable Control at Higher

Programmable control systems are everywhere: robots on production lines, washing machines, games controllers, lifts, car engine management and the phone in your pocket. In every case a microcontroller takes in information from sensors, processes it according to a program, and sends signals to output devices.

At Higher the course specification asks you to develop control routines with up to four inputs and four outputs, to process analogue inputs, to use loops, time delays, logic and arithmetic to make decisions, and to control the speed of a motor using pulse-width modulation (PWM).

  • Question paper. You will not be asked to write full programs from scratch. You will draw flowcharts from a specification, read program code and describe what it does, and identify and correct faults in it.
  • Assignment. You may have to produce a working program and hand in a hard copy of it (printed or handwritten). Depending on the task, this could mean editing given high-level code (such as PBASIC or Arduino C++) to meet a new specification, or building, simulating and testing a flowchart program.

Microcontrollers and hard-wired circuits

A microcontroller is a programmable integrated circuit — a processor, memory and input/output pins in one small package. Most control circuits could instead be built from separate components such as resistors, transistors and logic gate chips. A circuit that cannot be programmed is called a hard-wired circuit, and for anything complex it becomes very large.

A large stripboard crowded with logic chips, resistors, transistors and wire links
A hard-wired circuit needs many separate components
A single microcontroller chip
A microcontroller module can do the same job in far less space

Because a microcontroller-based circuit needs far fewer components, it typically:

  • costs less to make
  • can be manufactured more quickly, as fewer connections need to be made
  • is more reliable, as there are fewer components and connections to fail
  • uses less power and produces less heat
  • can be reprogrammed if a fault is found or new features are needed — a hard-wired circuit would have to be taken apart and rebuilt
  • can be reprogrammed so that the same controller is used in several different products.
Exam tip. Questions often ask why a microcontroller is preferred to a hard-wired, logic-gate or fully pneumatic system. Give a reason and its consequence, for example “far fewer components are needed, so the system is cheaper and quicker to manufacture” or “the function can be changed by reprogramming rather than rebuilding the circuit”.

Flowchart symbols

You should already know these four symbols from National 5. A flowchart begins with a start terminator and, if it does not loop for ever, ends with a stop terminator.

Flowchart symbols: terminator, process, input/output, decisionstartwait 2 spin 7 onis pin 0 on?TerminatorProcessInput / outputDecision
  • A process box is used for time delays (a fixed delay always has a unit, e.g. wait 2 s or wait 15 ms; a delay set by a variable, e.g. wait mark, does not), for setting or changing variables (X = X + 1) and for storing a reading (store reading in X).
  • An input/output box is used to switch an output (pin 7 on) and to read an analogue input (read pin 0).
  • A decision box asks a yes/no question about an input (is pin 0 on?) or a variable (X > 200?). Both exits must be labelled Y and N.
  • Exam papers refer to pins by number (pin 7 on, is pin 1 on?). Always use the pin numbers from the table you are given.
Put an arrowhead on every flow line, so the direction of flow is always clear. These notes do this on every flowchart.

Infinite and finite loops

An infinite (continuous) loop repeats a section of the flowchart for ever. A finite loop repeats a section a set number of times, using a variable (here X) to count how many times the loop has run.

Infinite loop: pin 7 flashes on and off for everstartpin 7 onwait 0.5 spin 7 offwait 0.5 s
Infinite loop: pin 7 flashes for ever
Finite loop: pin 7 flashes five times then the program endsstartX = 0pin 7 onwait 1 spin 7 offwait 1 sX = X + 1X = 5?stopYN
Finite loop: pin 7 flashes five times

In the finite loop, X is set to 0 before the loop starts. Every time round, 1 is added to X and the decision checks whether X has reached 5. Only when it has does the program leave the loop.

✏️ Task 1 — Recap: microcontrollers, symbols and loops
1. A manufacturer is replacing a hard-wired control circuit with a microcontroller-based system. Describe two advantages of the microcontroller-based system.
Answer
2. Describe the difference between an infinite loop and a finite loop.
Answer
3. In the finite-loop flowchart above, a pupil moves the box X = 0 so that it comes just after pin 7 on, inside the loop. Explain what will happen when the program runs.
Answer
4. State which flowchart symbol should be used for each of these instructions: (a) store reading in X  (b) read pin 1  (c) X > 100?  (d) wait 250 ms  (e) pin 6 off
Answer

Section 2: Reading and Correcting Program Code

A flowchart is turned into a program written in a high-level language. In Scottish schools the two you are most likely to meet are PBASIC (used with PICAXE chips and the Stamp Controller) and Arduino (a version of C++). Exam papers now show code in both languages side by side, and you can answer in whichever you prefer.

Exam tip. Markers accept any appropriate programming language and award marks where the intention of your code is clear, even with minor syntax errors. Concentrate on getting the logic right — the right pin, the right comparison, the right delay. (Source: the general marking principles in Qualifications Scotland’s Higher Engineering Science marking instructions.)
Use one language only. When a question shows code in both languages, answer from one of them. Each fault appears in both versions, so finding the same fault in both languages only counts as one fault.

Commands you need to recognise

FlowchartPBASICArduino
Flowchart box: pin 7 onpin 7 onhigh 7digitalWrite(7, HIGH);
Flowchart box: pin 7 offpin 7 offlow 7digitalWrite(7, LOW);
Flowchart box: wait 500 mswait 500 mspause 500delay(500);
Decision box: is pin 0 on?is pin 0 on?YNif pin0 = 1 then labelif (digitalRead(0) == HIGH) {
Wait until: is pin 0 on? with the N exit looping back to the same decisionis pin 0 on?YNwait0: if pin0 = 0 then wait0while (digitalRead(0) == LOW) { }
Flowchart box: X = 0X = 0let b0 = 0x = 0;
Flowchart box: X = X + 1X = X + 1let b0 = b0 + 1x = x + 1;
Finite loop: X = 0, steps to repeat, X = X + 1, then X = 5? with the N exit looping backX = 0steps to repeatX = X + 1X = 5?YNfor b0 = 1 to 5 … next b0for (int count = 1; count <= 5; count++) {
Loop back to just below startstartrest of programgoto mainthe loop() function repeats automatically
read pin 0, then store reading in Xread pin 0store reading in Xreadadc 0, b1int x = analogRead(0);

In Arduino, every { opens a block of code, and that block must be closed later with a matching }. The lines between them are the ones that run when the condition is true, or each time round the loop. An empty pair { }, as in the while line, means “do nothing, just keep checking”.

In PBASIC, a word followed by a colon (such as main:) is a label — a named point in the program that goto or if … then can jump to. Variables in PBASIC are called b0, b1, b2 and so on, or can be given names with symbol. In Arduino, the code in setup() runs once and the code in loop() repeats for ever.

Setting up variables and names

These lines usually come at the very start of a program. Apart from giving a variable its starting value (a process box such as X = 0), they do not have a box of their own in a flowchart.

What it doesPBASICArduino
Create a variable that holds a whole number, and give it a starting valuesymbol count = b0
let count = 0
int count = 0;
Give a pin a name that never changes during the programsymbol motor = 7const int motor = 7;
Set a pin as an output or an inputsee Beyond the exam belowpinMode(7, OUTPUT);
pinMode(0, INPUT);

int is short for integer (a whole number). const is short for constant: a value that cannot be changed while the program runs, which makes it ideal for naming pins.

Worked example — flowchart to code
1
Specification: when a switch on pin 0 is pressed, an LED on pin 7 flashes five times (1 s on, 1 s off). The system then waits for the switch again.
2
The flowchart uses a decision box to wait for the switch, then a finite loop counted by X.Worked example: wait for the switch on pin 0, then flash pin 7 five times, then repeatstartis pin 0 on?X = 0pin 7 onwait 1 spin 7 offwait 1 sX = X + 1X = 5?YNYN
3
The same program in both languages. Compare each line with a box in the flowchart.
PBASIC
main:  if pin0 = 0 then main   ' wait until the switch on pin 0 is on
        for b0 = 1 to 5          ' 5 times
          high 7
          pause 1000
          low 7
          pause 1000
        next b0
        goto main
Arduino
void setup() {
  pinMode(0, INPUT);
  pinMode(7, OUTPUT);
}
void loop() {
  while (digitalRead(0) == LOW) { }  // wait until the switch on pin 0 is on
  for (int count = 1; count <= 5; count++) {   // 5 times
    digitalWrite(7, HIGH);
    delay(1000);
    digitalWrite(7, LOW);
    delay(1000);
  }
}

In PBASIC, anything after an apostrophe ' is a comment; in Arduino it is anything after //. Comments are ignored by the microcontroller but help people read the program.

Beyond the exam — ports and the data direction register

You will not be examined on this, but it explains some lines you will see in PBASIC programs. A microcontroller’s pins are grouped into ports. The Stamp Controller uses port B, which has eight pins (b.0 to b.7) that can each be set as an input or an output.

The data direction register (dirsB) sets which pins are outputs (1) and which are inputs (0). The pin states can then all be set at once with pinsB. The % sign means a binary number follows; the first digit is pin 7 and the last is pin 0.

let dirsB = %11110000   ' pins 4-7 outputs, pins 0-3 inputs
let pinsB = %11111111   ' all output pins high
let pinsB = %00000000   ' all output pins low
let pinsB = %10010000   ' pins 7 and 4 high, the rest low

Every pin is an input when the controller is reset, so a PBASIC program for the Stamp Controller normally begins with a let dirsB = line. There is no everyday single-line Arduino C++ version of this command: Arduino programs set each pin separately with a pinMode() line, as in the worked example above.

✏️ Task 2 — Reading and correcting code
1. This program was written to flash an LED on pin 7 five times after a switch on pin 0 is pressed, but the LED does not appear to flash. Identify the fault and write the corrected line(s). Answer from one language.
PBASIC
main:  if pin0 = 0 then main
        for b0 = 1 to 5
          high 7
          pause 1000
          low 7
        next b0
        goto main
Arduino
void setup() {
  pinMode(0, INPUT);
  pinMode(7, OUTPUT);
}
void loop() {
  while (digitalRead(0) == LOW) { }
  for (int count = 1; count <= 5; count++) {
    digitalWrite(7, HIGH);
    delay(1000);
    digitalWrite(7, LOW);
  }
}
Answer
2. Describe what this program does. Answer from one language.
PBASIC
main:  if pin1 = 1 then main
        high 6
        pause 3000
        low 6
        goto main
Arduino
void setup() {
  pinMode(1, INPUT);
  pinMode(6, OUTPUT);
}
void loop() {
  while (digitalRead(1) == HIGH) { }
  digitalWrite(6, HIGH);
  delay(3000);
  digitalWrite(6, LOW);
}
Answer
3. A greenhouse watering system should work as follows: if the start switch (pin 0) is on and the soil sensor (pin 1, high when the soil is dry) detects dry soil, the pump (pin 6) switches on for 5 seconds. The sequence repeats. Two faults are shown in bold. Write the corrected code for each fault (you may use either language).
InputPinOutput
start switch0
soil sensor (high when dry)1
6pump
PBASIC
main:  if pin0 = 0 then main
        if pin1 = 1 then main
        high 6
        pause 500
        low 6
        goto main
Arduino
void loop() {
  if (digitalRead(0) == LOW) { return; }
  if (digitalRead(1) == HIGH) { return; }
  digitalWrite(6, HIGH);
  delay(500);
  digitalWrite(6, LOW);
}
Answer
🔍 Optional — Ports and the data direction register

Only attempt this if you have read the “Beyond the exam” box above.

1. Write a let pinsB = command to switch on: (a) pins 0 and 1  (b) pins 7, 6, 5 and 4  (c) pins 7, 5, 3 and 1
Answer
2. Write a let dirsB = command to: (a) set pins 7 and 6 as outputs and the others as inputs  (b) set pins 6, 5 and 3 as outputs and the others as inputs
Answer

Section 3: Monitoring Several Inputs

Many systems have to check several inputs before deciding what to do. An automatic door, for example, has to watch for people approaching from inside and outside. At Higher you can be asked to design control routines with up to four inputs and four outputs.

The key technique is to connect decision boxes one after another in a loop, so that each input is checked in turn, over and over, very quickly. The arrangement of the Y and N exits decides whether the inputs are combined with OR or AND.

OR monitoring (left) and AND monitoring (right)startis pin 0 on?is pin 1 on?pin 7 onstartis pin 0 on?is pin 1 on?pin 7 onYNYNYNYN
Left: OR — either input switches pin 7 on. Right: AND — both inputs must be on.
  • OR: if the first input is not on, the N exit goes on to check the next input. Every Y exit leads to the output. Only when every input is off does the flow loop back to the start.
  • AND: each Y exit goes on to check the next input. Any N exit loops back. Only if every input is on does the flow reach the output.
  • The same pattern extends to three or four inputs, and each input can lead to a different action instead of the same one (see the dragster task below).

Sequential inputs. Sometimes the inputs must happen in order — for example, a car must arrive at a barrier (pin 0) and then the driver presses the ticket button (pin 1). This looks like AND, but the N exit of the second decision loops back to the top of that decision, not to the start. Once input 1 has come on, the program waits for input 2 without going back to check input 1 again.

Sequential monitoring: pin 0 must come on, then pin 1, before pin 7 switches onstartis pin 0 on?is pin 1 on?pin 7 onYNYN
Sequential: pin 0 must come on first, then pin 1. Pin 1’s N exit loops back to its own decision, not to the start.

From a Boolean expression to a flowchart

Exam questions sometimes describe a condition as a Boolean expression, linking this topic to Digital Electronics. For example, a lamp L (pin 7) comes on for 2 seconds when L = A + B — that is, when A is on or B is off.

Flowchart for Z = A + NOT B: pin 7 on for 2 secondsstartis A on?is B on?pin 7 onwait 2 spin 7 offYNNY
A on → lamp. A off: check B. B off (NOT B is true) → lamp. B on → back to the start.
For a NOT input, the output is reached through the N exit of that input’s decision box, and the Y exit loops back. You can instead ask is B off?, so that the Y exit leads to the output in the usual way. Both methods are correct and both are widely used.

Using the simulator

There are two simulators you can use to build and test flowcharts. NoSyntaxSim (below) has four inputs and four outputs. NoResistanceSim also has a built-in flowchart editor, so a flowchart can control an electronic circuit that you build — you will need this later, when circuits and flowcharts are combined in the assignment.

Rename the pins. In both simulators you can rename the input and output pins. Before you build a flowchart, rename them to match the pin table in the task (for example pin 0 and pin 7), so that your simulated flowchart uses exactly the same pin numbers as your written answer.
🤖 NoSyntaxSim — Monitoring inputs
⛶ Full screen
Use this simulator for the tasks in Sections 3 and 4. Connect switches to the input pins and LEDs or motors to the output pins, build the flowchart, then press Run. Use the speed slider to slow the program down so you can follow it.
NoSyntaxSim V2.0

Task specifications

A — Flashing warning. An LED must flash 10 times (0.5 s on, 0.5 s off) after a switch is pressed. The system then waits for the switch again.

InputPinOutput
switch0
7LED

B — Forward and reverse. A motor must turn forwards while switch A is pressed and in reverse while switch B is pressed. When neither switch is pressed the motor must stop. The system must continuously repeat.

InputPinOutput
switch A0
switch B1
7motor forward
6motor reverse

C — Pelican crossing. The traffic lights stay on green until a pedestrian presses the button. The lights then show amber for 3 s, then red for 10 s while pedestrians cross. Amber then flashes 5 times (0.5 s on, 0.5 s off) before the lights return to green.

InputPinOutput
push button3
7red
6amber
5green

D — Dragster race. A race for three model dragsters is started when the starter presses a switch, which switches on a green start light. A sensor at the end of each lane switches on when that lane’s dragster crosses it. A lamp must light to show the winning lane. After 10 seconds all lights switch off and the system waits for the next race.

InputPinOutput
start switch0
lane 1 sensor1
lane 2 sensor2
lane 3 sensor3
4green start light
5lane 1 winner lamp
6lane 2 winner lamp
7lane 3 winner lamp

E — Office climate control. A fan must spin when the temperature rises above a set level, and a bank of LEDs must light when it gets dark. The temperature and light sensor circuits each give a digital signal (on = too hot, on = dark). Both must be checked continuously.

InputPinOutput
temperature sensor0
light sensor1
6LED bank
7fan motor (12 V)
✏️ Task 3 — Monitoring several inputs
1. Draw a flowchart for specification A, then build and test it in the simulator.
Answer
2. Draw a flowchart for specification B. Explain why your flowchart must never switch pins 6 and 7 on at the same time.
Answer
3. Draw a flowchart for the pelican crossing (specification C).
Answer
4. Draw a flowchart for the dragster race (specification D).
Answer
5. Draw a flowchart for the climate control system (specification E).
Answer
6. A warning lamp (pin 7) is switched on for 2 seconds when Z = A.B + C. Inputs A, B and C are on pins 0, 1 and 2. Draw the flowchart.
Answer

Section 4: Variables and Arithmetic

A variable is a named store in the microcontroller’s memory that holds a number. You have already used one to count round a finite loop. At Higher, variables are also used to count events, store sensor readings and hold the mark and space times for PWM. The program can do arithmetic on a variable and make decisions by comparing it with a number or with another variable.

OperationFlowchartPBASICArduino
Set a valueFlowchart box: X = 0X = 0let b0 = 0x = 0;
Increase by 1Flowchart box: X = X + 1X = X + 1let b0 = b0 + 1x = x + 1;
Decrease by 1Flowchart box: X = X - 1X = X - 1let b0 = b0 - 1x = x - 1;
Multiply by 3Flowchart box: X = X × 3X = X × 3let b0 = b0 * 3x = x * 3;
Is X more than 5?Decision box: X > 5?X > 5?YNif b0 > 5 then labelif (x > 5) {
Are A and B equal?Decision box: A = B?A = B?YNif b0 = b1 then labelif (a == b) {
  • Microcontroller variables hold whole numbers.
  • A PBASIC byte variable (b0, b1…) can only hold 0 to 255. Adding 1 to 255 gives 0, and taking 1 from 0 gives 255, so check that your counts stay in range.
  • The comparisons you can use are =, >, <, >= and <=. Note that Arduino uses == to compare and a single = to set a value.

Worked example — counting stock in a warehouse

A warehouse keeps track of the number of boxes on a shelf. A sensor on pin 0 switches on when a box is added, and a sensor on pin 1 switches on when a box is removed. The shelf starts with 20 boxes. When fewer than 5 boxes remain, a warning lamp on pin 7 must light.

Warehouse stock counter with low-stock warningstartX = 20is pin 0 on?is pin 0 on?X = X + 1is pin 1 on?is pin 1 on?X = X - 1X < 5?pin 7 onpin 7 offYNYNYNYNYN
X holds the number of boxes. Each sensor changes X by one, then X is checked against the low-stock level.
Notice the second “is pin 0 on?” box straight after the first. It makes the program wait until the sensor switches off again before counting. Without it, the program would loop round thousands of times while one box is passing the sensor, and add far more than 1 to X. Any counting system needs this.
PBASIC
        let b0 = 20             ' 20 boxes to start
main:   if pin0 = 1 then added
        if pin1 = 1 then removed
        goto check
added:  if pin0 = 1 then added   ' wait until the pin 0 sensor is off (box has passed)
        let b0 = b0 + 1
        goto check
removed: if pin1 = 1 then removed ' wait until the pin 1 sensor is off
        let b0 = b0 - 1
check:  if b0 < 5 then warn
        low 7
        goto main
warn:   high 7
        goto main
Arduino
int x = 20;                        // 20 boxes to start
void setup() { pinMode(7, OUTPUT); }
void loop() {
  if (digitalRead(0) == HIGH) {
    while (digitalRead(0) == HIGH) { }  // wait until the pin 0 sensor is off (box has passed)
    x = x + 1;
  }
  if (digitalRead(1) == HIGH) {
    while (digitalRead(1) == HIGH) { }  // wait until the pin 1 sensor is off
    x = x - 1;
  }
  if (x < 5) { digitalWrite(7, HIGH); }
  else       { digitalWrite(7, LOW); }
}

Task specifications

F — Car park. A car park holds 10 cars. A pressure sensor at the entrance switches on as each car enters, and one at the exit switches on as each car leaves. The barrier stays open until there are 10 cars inside, then closes. It opens again when a car leaves.

InputPinOutput
entrance sensor0
exit sensor1
7barrier (on = open)

G — Lift. A lift must count people coming in and going out. If there are 10 or fewer people inside when the ‘close’ button is pressed, the door motor runs for 3 seconds to close the door. If there are more than 10, an alarm must sound instead, and must stop as soon as there are 10 people or fewer inside.

InputPinOutput
people in sensor0
people out sensor1
close button2
6alarm
7door motor

H — Drinks machine. A drinks machine has a separate slot for 5p, 10p and 20p coins, each with its own sensor. When at least 35p has been put in and the button is pressed, a can is given out (pin 7 on for 1 s). Any change is given out in 5p coins, with a lamp flashing once for each coin.

InputPinOutput
5p sensor0
10p sensor1
20p sensor2
button3
6change lamp
7can release
✏️ Task 4 — Variables and arithmetic
1. X starts at 12. State the value of X after each of these instructions is carried out in order: X = X × 3, then X = X - 6, then X = X + 5.
Answer
2. Explain why a counting system must wait for the sensor to switch off again before it counts the next item.
Answer
3. Write a line of code (either language) to (a) increase X by 5 and (b) check whether X is greater than 25.
Answer
4. Draw a flowchart for the car park (specification F), then build and test it in the simulator.
Answer
5. Draw a flowchart for the lift (specification G).
Answer
6. Draw a flowchart for the drinks machine (specification H).
Answer

Section 5: Analogue Inputs

So far every input has been digital — on or off, high or low, 1 or 0. Many real sensors are analogue: their output can take any value in a range. A thermistor or LDR in a voltage divider, a potentiometer measuring an angle, or a speed sensor all give a voltage that varies smoothly. A games controller needs detailed information about exactly where a joystick is, not just whether it has moved.

A microcontroller can only work with numbers, so an analogue input pin converts the voltage on it into a number (this is done by an analogue-to-digital converter, or ADC, inside the microcontroller). In Higher exam questions, and in these notes, the reading is a whole number from 0 to 255: 0 V gives a reading of 0, and 5 V gives 255. The program reads the pin, stores the reading in a variable, and then compares it or uses it in calculations.

Reading an analogue input in a flowchart

An analogue input needs to be read, then the value stored in a variable. These are shown as two separate steps in a flowchart — an input/output box to read the pin, then a process box to store the reading — although they are a single line in some high-level programming languages.

Checking whether a reading X is between 50 and 100read pin 0store reading in XX < 50?X > 100?pin 7 onpin 6 onYNYNin range (50 to 100)out of range
Read and store, then two decisions to check whether the reading lies between 50 and 100
PBASIC
readadc 0, b1      ' read pin 0 and store in b1
Arduino
int x = analogRead(0);   // read pin 0 and store its value in x

A real Arduino gives readings from 0 to 1023 rather than 0 to 255, but in exam answers this does not matter: as in exam questions, these notes treat every reading as 0 to 255. NoSyntaxSim’s analogue sensor gives 0 to 255 directly.

To check whether a reading is within a range you need two decisions — one for each end of the range. A reading is out of range if it is below the lower limit or above the upper limit.
Worked example — projector cooling fan
1
Specification: when the start switch (pin 0) is pressed, the projector lamp (pin 6) comes on. An analogue temperature sensor (pin 1) reads the temperature of the lamp and stores the reading in X. If X is greater than 200, the fan (pin 7) is switched on; otherwise it is switched off. The reading is repeated continuously.
2
After the start switch and the lamp, the loop goes back to read pin 1 (not to the start), so the lamp stays on while the temperature is checked over and over.Projector: lamp on after start switch; fan controlled by analogue temperature readingstartis pin 0 on?pin 6 onread pin 1store reading in XX > 200?pin 7 onpin 7 offYNYNpin 6 = lamp · pin 7 = fan
3
The same program in code:
PBASIC
main:   if pin0 = 0 then main
        high 6                  ' lamp on
check:  readadc 1, b0           ' read temperature into b0
        if b0 > 200 then hot
        low 7                   ' fan off
        goto check
hot:    high 7                  ' fan on
        goto check
Arduino
void setup() { pinMode(6, OUTPUT); pinMode(7, OUTPUT); }
void loop() {
  while (digitalRead(0) == LOW) { }
  digitalWrite(6, HIGH);                 // lamp on
  while (true) {
    int x = analogRead(1);               // read pin 1 and store the temperature in x
    if (x > 200) { digitalWrite(7, HIGH); }   // fan on
    else         { digitalWrite(7, LOW); }    // fan off
  }
}

Comparing two analogue readings

Two readings can be stored in two variables and compared with each other. A wind turbine, for example, can use one analogue sensor to sense the wind direction (stored in A) and a second analogue sensor to sense which way the turbine is facing (stored in B). If A and B are different, a motor turns the turbine until they match.

A row of wind turbines on dry grassy hills under a cloudy sky
Turbines must turn to face the wind to generate the most power.
🤖 NoSyntaxSim — Analogue inputs
⛶ Full screen
Add an Analogue Sensor to an input pin. Its slider gives a reading of 0 to 255. Use a process box to store the reading in a variable, then decision boxes to compare it. Use the variable monitor to watch the value change as you move the slider.
NoSyntaxSim V2.0

Task specifications

I — Projector fan with a dead band. In the worked example the fan switches on and off rapidly when the reading sits around 200. Change the system so that the fan switches on when X is greater than 200, but only switches off again when X falls below 180. Between 180 and 200 the fan stays as it is.

J — Room lighting. As the outside light level falls, a system keeps the light level in a room constant by switching on more LEDs. The light sensor gives a low reading when it is dark.

  • reading below 50: all four LEDs on
  • reading 50 to 100: three LEDs on
  • reading 101 to 150: two LEDs on
  • reading 151 to 200: one LED on
  • reading above 200: all LEDs off
InputPinOutput
light sensor (analogue)0
4LED 4
5LED 3
6LED 2
7LED 1

K — Wind turbine. The reading from sensor A (wind direction) is stored in A and the reading from sensor B (turbine direction) in B. If A is greater than B the motor turns backwards. If A is smaller than B the motor turns forwards. If they are equal the motor stops. The system repeats continuously.

InputPinOutput
sensor A (analogue)0
sensor B (analogue)1
6motor reverse
7motor forward
✏️ Task 5 — Analogue inputs
1. Explain why a microcontroller needs an analogue-to-digital converter to use a signal from a thermistor voltage divider.
Answer
2. Explain why two decision boxes are needed to check whether a reading is between 50 and 100.
Answer
3. Draw a flowchart for specification I (projector fan with a dead band).
Answer
4. Draw a flowchart for specification J (room lighting).
Answer
5. Draw a flowchart for specification K (wind turbine), then build and test it in the simulator using two analogue sensors.
Answer
6. Extension. An ADC converts 0 to 5.0 V into readings of 0 to 255. (a) Calculate the change in voltage represented by one step of the reading. (b) Calculate the reading the ADC gives for an input of 2.0 V. Give your answer to (a) to 2 significant figures.
Answer

Section 6: Motor Speed Control — Pulse-Width Modulation

Many control systems need to change the speed of a motor. There are two ways to do this:

  1. change the voltage level applied to the motor, or
  2. switch the voltage supplied to the motor fully on and fully off very rapidly.

A microcontroller output pin can only be at 0 V or 5 V, so it cannot vary the voltage level. Instead it uses the second method, called pulse-width modulation (PWM). If the switching happens many times a second, the motor’s inertia smooths out the pulses and it turns at a steady speed.

Mark, space and mark to space ratio

  • The time the output is on is called the mark.
  • The time the output is off is called the space.
  • The mark to space ratio compares the two. The longer the mark compared with the space, the more energy is delivered to the motor and the faster it turns.
  • The duty cycle is the mark as a percentage of one complete pulse (mark + space).
Mark to space ratio 1:15 V0 Vtime (ms)voltage (V)101010101010mark (green) = 10 ms · space (orange) = 10 ms
1:1 — on for the same time as off (duty cycle 50%): medium speed
Mark to space ratio 1:35 V0 Vtime (ms)voltage (V)515515515mark (green) = 5 ms · space (orange) = 15 ms
1:3 — the space is three times as long as the mark (duty cycle 25%): slower
Mark to space ratio 3:15 V0 Vtime (ms)voltage (V)155155155mark (green) = 15 ms · space (orange) = 5 ms
3:1 — the mark is three times as long as the space (duty cycle 75%): faster
Drawing a PWM graph in the exam. Every pulse must reach the same voltage (it is a digital signal), and you must draw the number of complete pulses specified in the question (so far this has usually been at least three marks and two spaces) so the ratio can be checked. A single pulse gets no marks. Count squares carefully — for a ratio of 2:1 the on time is exactly twice the off time.
Describing a change of speed. Your answer must mention both mark and space. To increase speed: increase the mark while keeping the space the same; or decrease the space while keeping the mark the same; or increase the mark and decrease the space. “Increase the mark” on its own does not get the mark.

Advantages and limitations of PWM

  • Torque is maintained at all speeds. Each pulse applies the full supply voltage, so the motor still produces its full turning force even at low speed. Reducing the voltage instead also reduces the torque, so a slow motor may stall under load.
  • The output driver (a transistor or MOSFET) is either fully on or fully off, so very little energy is wasted as heat in it.
  • PWM cannot be used with a mechanical relay: the rapid switching would quickly wear out (and spark) the relay contacts. A transistor or MOSFET driver must be used.
  • The frequency of the pulses must be chosen carefully. If the pulses are too slow, the motor speeds up and slows down with each pulse, runs jerkily and may stall.

PWM in a flowchart and in code

In a flowchart, PWM is simply: output on, wait for the mark, output off, wait for the space, repeat. Storing the mark and space in variables makes it easy to change the speed later.

When you set up the variables at the start, do not put a unit in the box: write mark = 10, not mark = 10 ms, because a variable holds only a number. The time delay box then just says wait mark or wait space: the variable already holds the time in ms, so no unit is added. A unit is only needed when the delay is a fixed number, e.g. wait 2 s.
PWM flowchart: motor on pin 7 with mark 10 ms and space 20 msstartmark = 10space = 20pin 7 onwait markpin 7 offwait space
Mark 10 ms, space 20 ms: ratio 1:2
PBASIC
symbol mark = b1
symbol space = b2
symbol motor = 7
init:  let dirsB = %11110000   ' pins 4-7 outputs
       let mark = 10            ' mark 10 ms
       let space = 20           ' space 20 ms
main:  high motor
       pause mark
       low motor
       pause space
       goto main
Arduino
int mark = 10;     // mark 10 ms
int space = 20;    // space 20 ms
void setup() { pinMode(7, OUTPUT); }
void loop() {
  digitalWrite(7, HIGH);
  delay(mark);
  digitalWrite(7, LOW);
  delay(space);
}

Here the space is twice the mark, so the motor runs at about a third of full speed.

Some microcontrollers have a built-in PWM command — for example Arduino’s analogWrite(pin, value), where the value 0 to 255 sets the duty cycle. PICAXE chips have one too, and NoSyntaxSim’s output box has a Set PWM option. At Higher, though, you are showing that you understand how PWM works, so always show it as separate steps: on, wait (mark), off, wait (space).

⚙️ NoSyntaxSim — PWM investigation
⛶ Full screen
Connect a motor to OUT_9. Build the PWM flowchart above, using Time Delay boxes set to a variable for the mark and space. Run it, then try the changes in Task 6 and watch the motor speed.
NoSyntaxSim V2.0
✏️ Task 6 — Pulse-width modulation
1. Sketch a graph of a PWM signal with a mark to space ratio of 2:1. Show at least three pulses. (Draw on paper and add a photo, or describe the times you would use.)
Answer
2. Describe how the speed of a motor controlled by PWM could be decreased. Refer to both mark and space.
Answer
3. Describe one advantage of using PWM rather than varying the supply voltage level to control the speed of a motor.
Answer
4. Explain why a PWM signal should not be used to switch a motor through a relay, and state a suitable output driver.
Answer
5. In the simulator, set the mark and space to 500 ms each, then to 100 ms each, then to 10 ms each. Describe what happens to the motor and explain why.
Answer
6. Extension. A PWM signal has a mark of 15 ms and a space of 45 ms. Calculate (a) the mark to space ratio, (b) the duty cycle and (c) the frequency of the pulses.
Answer

Section 7: Changing Speed Under Program Control

Because the mark and space are stored in variables, the program can change them while it runs. This lets a motor accelerate smoothly, respond to buttons, or be controlled by a sensor reading. These ideas appear in almost every Higher paper.

Accelerating a motor (soft start)

A heavy load such as a conveyor or ski tow should not be jerked into motion at full power. Instead, the program starts with a short mark and long space, then lengthens the mark and shortens the space a little on every pulse until the motor reaches full speed. Keeping mark + space constant keeps the frequency constant.

Soft start: the mark increases and the space decreases on every pulse until full speedstartmark = 2space = 18pin 7 onwait markpin 7 offwait spacemark = mark + 1space = space - 1mark = 20?pin 7 onYN
Mark rises from 2 ms to 20 ms, one step per pulse
Accelerating motor: the mark gets longer and the space shorter on every pulse5 V0 Vtime (ms)voltage (V)
The pulses get wider while the period stays the same
PBASIC
        let b1 = 2              ' mark
        let b2 = 18             ' space
ramp:   high 7
        pause b1
        low 7
        pause b2
        let b1 = b1 + 1
        let b2 = b2 - 1
        if b1 < 20 then ramp
        high 7                  ' full speed
Arduino
void setup() {
  pinMode(7, OUTPUT);
  int mark = 2, space = 18;
  while (mark < 20) {
    digitalWrite(7, HIGH); delay(mark);
    digitalWrite(7, LOW);  delay(space);
    mark = mark + 1;
    space = space - 1;
  }
  digitalWrite(7, HIGH);   // full speed
}
void loop() { }

Closed-loop speed control

If the load on a motor changes — a lift that fills with people, or a forklift raising a heavy pallet — its speed will change too. A speed sensor can feed the actual speed back to the microcontroller, which compares it with the desired value and adjusts the mark and space to correct any error. This is closed-loop control, which you met in the Systems Approach.

Closed-loop speed control: the mark and space are adjusted after every readingstartmark = 60space = 60read pin 0store reading in SS > 140?S < 140?mark = mark - 1space = space + 1mark = mark + 1space = space - 1pin 7 onwait markpin 7 offwait spaceYNYNN
Desired speed reading = 140. Too fast: shorten the mark. Too slow: lengthen it. Correct: no change.
Look at how this flowchart is built: read and store, then two decisions (too high? too low?), each with its own adjustment to mark and space, then all routes join for the on – wait mark – off – wait space pulse, then loop back to read again. This structure has appeared in several recent exam papers for up to 10 marks.

Setting the mark directly from a reading

Another approach uses the reading itself as the mark. If the reading X is 0 to 255 and every pulse is 255 ms long, then mark = X and space = 255 - X. A higher reading gives a longer mark and a faster motor.

Mark set by the analogue reading X; space = 255 - Xstartread pin 1store reading in Xmark = Xspace = 255 - Xpin 7 onwait markpin 7 offwait space
Mark from the reading; space makes up the rest of the 255 ms pulse

Brightness control

PWM works just as well for lamps and LEDs. Switching a bank of LEDs rapidly through a transistor (a BJT or a MOSFET) changes their brightness: a longer mark makes them brighter. The eye cannot see the flicker as long as the pulses are fast enough.

Task specifications

L — Food mixer. The user must be able to adjust the speed of a food mixer.

  • Mark and space are both initially set to 10 ms.
  • When the ‘faster’ switch is pressed, the mark increases by 1 ms and the space decreases by 1 ms.
  • When the ‘slower’ switch is pressed, the mark decreases by 1 ms and the space increases by 1 ms.
  • A PWM signal is sent to the motor using the mark and space.
  • The speed adjustment and pulses continue until the stop switch is pressed.
InputPinOutput
stop switch0
faster switch1
slower switch2
7motor
✏️ Task 7 — Changing speed under program control
1. Draw a flowchart for the food mixer (specification L), then build and test it in the simulator.
Answer
2. Sketch a graph showing how a microcontroller could make a motor accelerate. Show at least six pulses.
Answer
3. Using the closed-loop flowchart above, describe what happens to the mark and space when the speed reading S is 150, and explain why this is an example of closed-loop control.
Answer
4. A light sensor on pin 0 gives a low reading when it is dark. The program below controls the brightness of a bank of LEDs switched by a MOSFET on pin 7. (a) State the mark to space ratio when the reading is 30, 120 and 220. (b) Describe how the LEDs respond as it gets darker. (c) State the length of one complete pulse. Answer from one language.
PBASIC
main:    readadc 0, b0
         if b0 < 60 then bright
         if b0 < 160 then medium
         let b1 = 1               ' mark
         let b2 = 9               ' space
         goto pulser
bright:  let b1 = 9
         let b2 = 1
         goto pulser
medium:  let b1 = 5
         let b2 = 5
pulser:  high 7
         pause b1
         low 7
         pause b2
         goto main
Arduino
void setup() { pinMode(7, OUTPUT); }
void loop() {
  int x = analogRead(0);
  int mark, space;
  if (x < 60)       { mark = 9; space = 1; }
  else if (x < 160) { mark = 5; space = 5; }
  else               { mark = 1; space = 9; }
  digitalWrite(7, HIGH);
  delay(mark);
  digitalWrite(7, LOW);
  delay(space);
}
Answer

Section 8: Exam-Style Questions

These questions are written in the style of the Higher question paper. Set yourself a time limit of about 1.5 minutes per mark, answer on paper or in the boxes, then check your work against the model answers.

Question 1 — Airport baggage conveyor

A baggage conveyor at an airport uses pulse-width modulation to accelerate smoothly to its working speed. The control sequence has the following steps:

Specification
  • Initially the MARK = 5 ms and the SPACE = 15 ms.
  • Each new pulse increases the MARK by 1 ms and decreases the SPACE by 1 ms.
  • The acceleration continues until the MARK reaches 20 ms.
  • The motor is then switched on continuously.
  • The motor stops when the emergency stop is pressed (high) or the override switch is released (low).
  • A brake is then applied for 3 seconds.
  • The sequence repeats.
InputPinOutput
emergency stop (pressed = 1)0
override switch (released = 0)1
6brake
7motor
🔍 Question 1 — Baggage conveyor
(a) Complete a flowchart for the control of the conveyor, with reference to the specification and the input/output table. 12
Answer
(b) Sketch the PWM signal for the first three pulses of the acceleration. 2
Answer
(c) Describe one reason why the conveyor is accelerated gradually rather than switched straight on at full power. 1
Answer

Question 2 — Loading a ferry car deck

A ferry company uses a microcontroller to control the loading of cars onto its car deck, which has space for 30 cars. Cars with bookings wait behind a barrier; cars on standby wait behind a gate. A single sensor at the top of the ramp counts every car that boards.

Control sequence
  • The operator presses the start switch to begin loading. The count is set to 0 and the barrier opens.
  • The sensor gives a high signal each time a car passes, and the count increases by 1.
  • If the deck is full (30 cars), the barrier closes.
  • If the deck is not full when the operator presses the standby switch, the barrier closes and the gate opens to let standby cars on until the deck is full. The gate then closes.
  • When loading is finished, the operator presses the ramp switch, and the ramp motor runs for 20 seconds to raise the ramp.
  • The system then returns to the start.
InputPinOutput
sensor0
standby switch1
start switch2
ramp switch3
5ramp motor
6gate (open = high)
7barrier (open = high)
🔍 Question 2 — Ferry car deck
(a) Draw a flowchart to show how the loading is controlled. 10
Answer
(b) The engineers considered building the controller from logic gates instead. Describe two advantages of using a microcontroller. 2
Answer

Question 3 — Hydro scheme sluice gate

A small hydro-electric scheme uses a motor to open a sluice gate when the water in the reservoir is high. The code is written to meet the following specification:

Specification
  • If the enable switch is on and the level sensor detects high water, the sluice motor runs.
  • The motor runs slowly using PWM with a mark to space ratio of 1:4, using a mark of 10 ms.
  • The sequence repeats.
InputPinOutput
enable switch0
level sensor (high water = 1)1
7sluice motor

Part of the program is shown below in PBASIC and Arduino. Two faults are shown in bold.

PBASIC
main:  if pin0 = 1 then main
       if pin1 = 0 then main
       high 7
       pause 10
       low 7
       pause 20
       goto main
Arduino
void loop() {
  if (digitalRead(0) == HIGH) { return; }
  if (digitalRead(1) == LOW) { return; }
  digitalWrite(7, HIGH);
  delay(10);
  digitalWrite(7, LOW);
  delay(20);
}
🔍 Question 3 — Sluice gate
(a) Correct the two faults by writing the corrected code. You may use either language. 2
Answer
(b) Sketch the PWM signal with a mark to space ratio of 1:4. Show at least three pulses. 2
Answer
(c) Describe, with reference to both mark and space, how the sluice motor could be made to turn faster. 1
Answer
(d) Explain why the reading from an analogue sensor is shown as two separate boxes in a flowchart. 1
Answer

Section 9: Design Challenges

For each challenge, follow the full engineering process: read the specification carefully, plan a flowchart on paper, then build it in NoSyntaxSim. Test every point of the specification, not just the obvious one. Finally, evaluate your system: does it fully meet the specification, and what would you improve?

These challenges use the simulator’s own pin names (IN_2 to IN_5 and OUT_6 to OUT_9). Use an Analogue Sensor wherever a reading is needed, and Time Delay boxes set to a variable for PWM mark and space times.
🤖 NoSyntaxSim — Design challenge workspace
⛶ Full screen
Use this workspace for the challenges below. When your system works, use the camera button to export an image of it and paste it into your answer.
NoSyntaxSim V2.0

Challenge 1 — Ski tow at Glenshee

A ski centre in the Cairngorms is upgrading the control system for one of its rope tows. Skiers are pulled up the slope on the rope, so it must never start with a jerk.

InputNoSyntaxSim pinOutput
start buttonIN_2
stop buttonIN_3
OUT_8warning beacon
OUT_9tow motor
iWhen the operator presses the start button, the warning beacon flashes 3 times (0.5 s on, 0.5 s off).
iiThe tow motor then starts with a mark of 2 ms and a space of 18 ms.
iiiOn every pulse the mark increases by 1 ms and the space decreases by 1 ms, until the mark reaches 18 ms.
ivThe motor then continues to run at that speed.
vIf the stop button is pressed at any time while the motor is running, the motor stops and the system waits for the start button again.
🎿 Challenge 1 — Ski tow
Design, build and simulate the ski tow controller. Test that the stop button works during the soft start as well as at full speed. Paste your exported flowchart below and evaluate your solution.
Answer

Challenge 2 — Polytunnel ventilation on an Orkney croft

A crofter in Orkney grows salad crops in a polytunnel. On sunny days it overheats, so a ventilation fan is to be fitted. To save energy, the fan speed should depend on how hot it is — and when it rains the fan must stop, as the vents have to close.

InputNoSyntaxSim pinOutput
temperature sensor (analogue)IN_2
rain sensorIN_3
OUT_7rain warning lamp
OUT_9fan motor
iThe temperature is read and stored in a variable T.
iiT below 100: fan off.
iiiT from 100 to 159: fan runs with mark 5 ms, space 15 ms.
ivT from 160 to 209: fan runs with mark 10 ms, space 10 ms.
vT of 210 or more: fan runs at full speed.
viIf the rain sensor is on, the fan stops and the rain warning lamp lights. The lamp goes off again when the rain stops.
viiThe system repeats continuously.
🌱 Challenge 2 — Polytunnel ventilation
Design, build and simulate the ventilation controller. Test each temperature band, including the values at the edges of each band (99, 100, 159, 160, 209, 210), and test the rain sensor. Paste your exported flowchart below and evaluate your solution.
Answer

Challenge 3 — Bottling line at a Speyside distillery

A distillery in Speyside is automating the end of its bottling line. Every bottle is checked to make sure it has been filled properly, and good bottles are packed in cases of 12.

InputNoSyntaxSim pinOutput
bottle sensorIN_2
fill-level sensor (analogue)IN_3
stop switchIN_4
OUT_8reject pusher
OUT_9case-sealing motor
iWhen the bottle sensor detects a bottle, the fill level is read and stored in L.
iiIf L is less than 180, the bottle is under-filled: the reject pusher operates for 1 second.
iiiOtherwise the bottle is counted as good.
ivWhen 12 good bottles have been counted, the case-sealing motor runs for 3 seconds and the count is reset.
vEach bottle must only be counted once.
viThe system stops when the stop switch is pressed.
🍾 Challenge 3 — Bottling line
Design, build and simulate the bottling line controller. Test it with a mixture of good and under-filled bottles, and check that the case is only sealed after exactly 12 good bottles. Paste your exported flowchart below and evaluate your solution.
Answer

💾 Answers saved automatically in this browser on this device.
Last saved: never

Your name

Enter your name once and it’ll be added to the top of every task’s downloaded PDF — no need to write it in by hand each time.

✓ Saved — it’ll now appear on your PDFs

Contents