21
1 INTRODUCTION Project-Based Learning Workshop Ian Piumarta 2017-04-26 1 Introduction Our goal is to learn a little about microcontrollers, how to program them, and why they are a useful engineering tool. Microcontrollers are tiny computers that can be found everywhere: from light bulbs, game controllers, washing machines, and robots to elevators, cars, aeroplanes, and space shuttles. There are more microcontrollers in the world than there are desktop (or laptop) computers; even a very basic modern car has at least 30 microcontrollers inside it that make it run. By the year 2020 we expect there will be more than 25 billion (25,000,000,000) of them, or approximately three for every person on the planet. Most of them will be connected to a network. Many of them will be connected to the Internet, forming the ‘Internet of Things’. Unlike desktop (or laptop) computers, microcontrollers can interact with the real world in many ways using sensors, dis- plays, sound, and movement. In this workshop we will learn the basics of microcontroller programming, using some simple devices. At the same time we will gain some experience with the following engineering ideas: ‘Cookbook’ engineering — making effective solutions by following ‘recipes’. Off-the-shelf components are combined according to simple instructions to create complete systems. (This is the engineering equivalent of ‘copy and paste’. The resulting systems are sometimes informally called ‘mash-ups’.)) ‘Future proofing’ — designing systems that can evolve. When requirements change, or ‘bugs’ are found, updating firmware (embedded software) is much easier (and cheaper) than modifying hardware. Lateral thinking — solving problems by thinking creatively, or ‘outside the box’. The obvious solution is not always the most efficient or the most effective, and necessary components of an effective design can sometimes be found in unexpected places. Agile development — working in teams of two. The driver creates the program while the observer reviews the code and makes strategic suggestions. Team members swap roles often. 1.1 Organisation Working in teams is more fun than working alone, so we will form four teams of two people. Within each team we will use ‘agile development’, just like an industrial engineering development team would use. In particular, programming will be performed by both team members at the same time, with one person suggesting what to do (and how) while the other person ‘drives’ the keyboard and mouse to make it happen. Two sets of eyes are always better than one! 1.2 Equipment We will use a very common microcontroller, the Atmel ATmega328P. Programming it requires an integrated development environment, or ‘IDE’, and we will use Arduino (because it has many convenient features for programmers who are unfamiliar with microcontrollers). Microcontrollers usually have no operating system at all, and cannot run normal applications, and so we will run the IDE on another computer to edit and compile our programs, finally uploading them to the microcontroller over a USB interface. (The microcontroller is already connected to some simple hardware on a prototyping ‘electronic breadboard’, which allows you to concentrate on the programming.) 1.3 Setting up the development environment The Arduino IDE runs on a PC. The microcontroller board attaches to the PC via a USB cable. Launch the IDE. Click on the ‘ ’ icon at the bottom of the screen, and wait a few seconds for the IDE to launch. A window will open that looks like the one shown on the right. In the Tools > Board menu, make sure ‘Arduino Uno’ is selected. In the Tools > Port menu, make sure ‘/dev/ttyACM0’ (or similar) is selected. 1

Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

  • Upload
    lekhanh

  • View
    220

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

1 INTRODUCTION

Project-Based Learning WorkshopIan Piumarta 2017-04-26

1 IntroductionOur goal is to learn a little about microcontrollers, how to program them, and why they are a useful engineering tool.

Microcontrollers are tiny computers that can be found everywhere: from light bulbs, game controllers, washing machines,and robots to elevators, cars, aeroplanes, and space shuttles. There are more microcontrollers in the world than there are desktop(or laptop) computers; even a very basic modern car has at least 30 microcontrollers inside it that make it run. By the year 2020we expect there will be more than 25 billion (25,000,000,000) of them, or approximately three for every person on the planet.Most of them will be connected to a network. Many of them will be connected to the Internet, forming the ‘Internet of Things’.

Unlike desktop (or laptop) computers, microcontrollers can interact with the real world in many ways using sensors, dis-plays, sound, and movement. In this workshop we will learn the basics of microcontroller programming, using some simpledevices. At the same time we will gain some experience with the following engineering ideas:

• ‘Cookbook’ engineering — making effective solutions by following ‘recipes’. Off-the-shelf components are combinedaccording to simple instructions to create complete systems. (This is the engineering equivalent of ‘copy and paste’. Theresulting systems are sometimes informally called ‘mash-ups’.))

• ‘Future proofing’ — designing systems that can evolve. When requirements change, or ‘bugs’ are found, updatingfirmware (embedded software) is much easier (and cheaper) than modifying hardware.

• Lateral thinking — solving problems by thinking creatively, or ‘outside the box’. The obvious solution is not alwaysthe most efficient or the most effective, and necessary components of an effective design can sometimes be found inunexpected places.

• Agile development — working in teams of two. The driver creates the program while the observer reviews the code andmakes strategic suggestions. Team members swap roles often.

1.1 OrganisationWorking in teams is more fun than working alone, so we will form four teams of two people. Within each team we willuse ‘agile development’, just like an industrial engineering development team would use. In particular, programming will beperformed by both team members at the same time, with one person suggesting what to do (and how) while the other person‘drives’ the keyboard and mouse to make it happen. Two sets of eyes are always better than one!

1.2 EquipmentWe will use a very common microcontroller, the Atmel ATmega328P. Programming it requires an integrated developmentenvironment, or ‘IDE’, and we will use Arduino (because it has many convenient features for programmers who are unfamiliarwith microcontrollers). Microcontrollers usually have no operating system at all, and cannot run normal applications, and sowe will run the IDE on another computer to edit and compile our programs, finally uploading them to the microcontroller overa USB interface.

(The microcontroller is already connected to some simple hardware on a prototyping ‘electronic breadboard’, which allowsyou to concentrate on the programming.)

1.3 Setting up the development environmentThe Arduino IDE runs on a PC. The microcontroller board attaches to the PC via a USB cable.

Launch the IDE.Click on the ‘ ’ icon at the bottom of the screen, and wait a few seconds for the IDE

to launch. A window will open that looks like the one shown on the right.In the Tools>Board menu, make sure ‘Arduino Uno’ is selected.In the Tools>Port menu, make sure ‘/dev/ttyACM0’ (or similar) is selected.

1

Page 2: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

2 PROJECT

2 ProjectTry to complete each step using the relevant parts of the cookbook. When you complete a step, tick the box to mark yourprogress. Demonstrate your project to the instructor when indicated. If you get stuck, ask for help!

Test the IDE.Enter the sketch on the right, exactly as shown. Then save your sketch (the name is notimportant, so something like test would be OK). You can check the sketch for errors bypressing the ‘verify’ button ( ). If there are compilation errors, they will appear in red inthe lower part of the IDE window.

When your sketch has no errors, you can send it to the microcontroller by pressing the‘upload’ button ( ). A progress bar will appear while uploading. When the compiledsketch has been transferred to the microcontroller, the window will say “done uploading”in white. The microcontroller will begin to run the program about half a second later.

The sketch is as simple as possible, while actually doing something. It will make alight-emitting diode (LED) blink once per second.

void setup() pinMode(13, OUTPUT);

void loop() digitalWrite(13, HIGH);delay(250);digitalWrite(13, LOW);delay(250);

Understand the overall operation of the sketch.Read the relevant sections of the ‘cookbook’ to gain a basic understanding of how the sketch works. Sections 3.2, 3.3 and 3.8would be a good place to start.

The best way to verify your understanding is to make small modifications of the design and check that the behaviourchanges in the way you expect. Each modification could check a different aspect of your understanding. For example...

Add a second LED to the sketch.Make another LED flash in an identical way to the original LED. (The other LEDs are connected to digital pins 10, 11, and 12.)

Completing this step just requires duplicating (and then slightly modifying) the three lines that• configure the LED (in setup()),• turn the LED on (in loop()), and• turn the LED off (also in loop()).

Make the LEDs blink at opposite times.Modify the sketch so that when one of the LEDs is on, the other is off.

, 1 Demonstrate your project to the instructor.

Use a button to control the LED blinking.A push-button switch is connected to digital pin 9. Read section 3.5 to understand how to use it. Make the LEDs blink onlywhen the switch is pressed.

Respond to a change in the requirements.Instead of making the LEDs blink when the switch is pressed, make them blink only when the switch is not pressed.

, 2 Demonstrate your project to the instructor.

Read an external analogue voltage level.Analogue input A0 is connected to a variable voltage source. When the blue rotary control is turned fully anti-clockwise, theinput will be at 0 V. When the control is turned fully clockwise, the input will be at 5 V.

Check the cookbook to understand how to read an analogue input voltage. In the loop() function you will have to createa new integer variable to hold the value you read. Use that value to control the on and off delays of the LEDs.

Let’s assume that you called your variable ‘value’. A good way to check your analogue input code is to use valuedirectly as the argument to both of the delay() functions.

Experiment with different delays.What happens if you use your value as one of the delay() arguments, but set the other delay() argument to a fixed value(e.g., 500)?

What value would you pass to the other delay() function if you wanted the total duration of the on-off cycle to beapproximately one second?

Experiment with shorter cycles.What happens if you make the total length of the cycle shorter and shorter? E.g.,a total of 500 milliseconds? 100 milliseconds?50 milliseconds? 10 milliseconds?

(For cycle times of less than one second you might want to use the delayMicroseconds() function for higher resolu-tion control of the delays.)

, 3 Demonstrate your project to the instructor.

What practical uses can you think of for the effect that you just discovered?

2

Page 3: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

3 ARDUINO COOKBOOK

3 Arduino cookbookTry to get by without studying Section 3.1. Thousands of artists, musicians, and other non-computer users have figured outmicrocontroller programming by ‘getting the gist of it’ and then forming an intuitive understanding of what to write. That’s aperfectly good way for you to approach microcontroller programming during this workshop.

3.1 SketchesAn Arduino sketch is a sequence of function or variable definitions. A func-tion definition has three parts: the type of the value returned (which is ‘void’if no value is returned), the name of the function (followed by ‘()’), and ablock of code (enclosed in ‘’ and ‘’ characters). Functions cannot be de-fined inside other functions.

Every sketch has at least two functions, called setup() and loop().When the sketch first starts running, the setup() function is called once toinitialise the microcontroller. The loop() function is then called repeatedly(forever) to perform the input/output and logic functions of the hardware.

void setup() configure the device

void loop() perform device actions

onceforever

start

setup

loop

3.1.1 Variables

Values can be stored in variables for later use. Variables must be definedbefore they can be used. A variable definition has three or four parts: thetype of the variable (e.g., ‘int’), the name of the variable (e.g., ‘x’), anoptional assignment of an initial value (e.g., ‘= 42’), and a final semi-colon (‘;’) to indicate the end of the definition

int a, b; // create two new variablesa = 21; // assign to ab = a * 2; // assign to b, using a

Once created, a variable can be given a new value at any time by executing an assignment statement. The value stored in avariable can be accessed simply by writing the variable’s name.

Variables can be defined anywhere, and their names can be used almost anywhere that an integer constant could be used.Variables defined outside functions exit forever. Variables defined inside a block of code vanish at the end of the block.

3.1.2 Expressions

Expressions compute values. Most values in the Arduino language are integers. Integer (and real number)constants can just be written in decimal (but avoid leading zeros). Integer expressions can be computedusing the usual mathematical operators (except that ‘/’ means division, and ‘* means multiplication).

212 * (20 + 1)3.1415 / 2

Logical expressions compute “true/false” answers. “False” is represented by the integervalue 0 and “true” by the integer value 1. They are useful for controling conditional statementsand loops. Six operators compare numeric values and generate a logical (true/false) value:

operator < <= == != >= >meaning less less or equal equal not equal greater or equal greater

Three operators manipulate logical values to produce another logical value:

operator && || !meaning and or not

x > 3(a >= 0) && (a <= 15)(b < 0) || (b > 15)!(a > b)

Function calls are expressions too; their value is whatever the function computes. To calla function, write its name followed by zero or more parameters inside parentheses, separatedby commas.

map(x, 0, 1023, 0, 100)min(a, b)

3.1.3 Statements

Statements perform or control actions.Any expression can also be used as a statement (by writing a semicolon ‘;’ after it). In

particular, a function call (to pinMode, for example) can be used as a statement.pinMode(13, OUTPUT);

Conditional statements control whether or not a block of code is executed. To makesome code conditional on a logical expression or value x, put the code inside a block(surround it with ‘’ and ‘’) and then put ’if (x)’ in front of it. No semicolon is neededafter the block of code.

To choose between two blocks of code, use an ‘if’ statement to control the first block.Immediately follow that by an ‘else’ statement (which looks just like an ‘if’ statement ex-cept that you use the word ‘else’). If the condition is true the first block will be executed;otherwise the second block will be executed. (In other words, the ‘else’ part of an ‘if’statement is optional.)

if (value < 512) digitalWrite(13, HIGH);digitalWrite(12, LOW);

// else part optionalelse digitalWrite(13, LOW);digitalWrite(12, HIGH);

3

Page 4: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

3 ARDUINO COOKBOOK

To repeat a block of code many times, use a loop. A ‘for’ statementintroduces a loop.

Write ‘for’ followed by the conditions for the loop inside parenthe-ses. The conditions have three parts: an initialisation, a logical expressionthat controls the loop, and an update step. Following these is a block ofcode to be repeated.

for (int i = 2; i < 10; i = i + 1) pinMode(i, OUTPUT);digitalWrite(i, HIGH);

The initialistion is executed only once, at the beginning of the loop.The logical expression is tested before the block of code is run. If the value is false, the loop finishes (and the program

continues with the statements after the block of code). If the value is true, then the block of code is executed, the update stepinside parentheses is run, and the loop repeats from testing the logical expression.

3.2 Microcontroller configurationThere are 14 digital input/output pins, numbered 0 to 13.Each digital pin must be configured as an INPUT or anOUTPUT, using pinMode(), before using it.

pinMode(n, INPUT);pinMode(n, OUTPUT);

Configuration of inputs and outputs is usually done in thesetup() function. Digital output pins generate voltagesto control external devices. Digital input pins read voltagesfrom external devices or sensors. Digital input and output pinsuse two discrete voltage levels. HIGH is (nominally) 5 V, andLOW is (nominally) 0 V.

A digital pin can also be configured as INPUT PULLUP.

pinMode(n, INPUT_PULLUP);

If left unconnected, such a pin will have the value HIGH. When some external device (such as a switch) connects it to ground(0 V) the value will change to LOW.

Digital pins 0 and 1 are used for USB communication, and should be avoided if possible.There are six analogue input pins, numbered A0 to A5. (The ‘A’ in front of the name is mandatory.) These do not need to

be configured explicitly to be used as inputs. (If you run out of digital pins, you can configure the analogue inputs as digitalinputs or outputs too.) Analogue inputs read a value in the range 0 to 1023, corresponding to input voltages in the range 0 Vto 5 V,

3.3 Digital outputIn the setup() function, configure the pin as OUTPUT.

In the loop() function, set the pin’s value usingdigitalWrite(n, v). The first argument n selects which pinto set. The second argument v sets the pin to LOW (0 V) or HIGH(5 V). Each argument can be supplied either as an integer constantor as an integer variable.

void setup() pinMode(10, OUTPUT); // configure pin 10

void loop() digitalWrite(10, LOW); // set pin 10delay(200);digitalWrite(10, HIGH); // set pin 10delay(200);

3.4 Digital inputIn the setup() function, configure the pin as INPUT.

In the loop() function, read the pin’s value usingdigitalRead(n). The argument n selects which pin to read.The value returned by digitalRead() is an integer equal to LOW ifthe input voltage is lower than approximately 2.5 V or HIGH if the inputvoltage is higher than approximately 2.5 V.

void setup() pinMode(9, INPUT); // configure pin 9pinMode(10, OUTPUT);

void loop() int value;value = digitalRead(9); // read pin 9// value is LOW or HIGHdigitalWrite(10, value);

4

Page 5: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

3 ARDUINO COOKBOOK

3.5 Digital input (buttons and switches)Configure the pin as INPUT PULLUP in the setup() func-tion.

In the loop() function, read the pin’s value usingdigitalRead(n). The argument n selects which pin toread. The value returned by digitalRead() is an integerequal to LOW if the input voltage is lower than approximately2.5 V or HIGH if the input voltage is higher than approximately2.5 V.

Connect the external switch or button between the input pinand ground (0 V). When the contacts are open (switch is off, orbutton is not pressed) the pin’s value will be HIGH. When thecontacts are closed (switch is on, or button is pressed) the pin’svalue will be LOW.

void setup() pinMode(9, INPUT_PULLUP); // configure pin 9pinMode(10, OUTPUT);

void loop() int value;value = digitalRead(9); // read pin 9// value is LOW or HIGHdigitalWrite(10, value);

3.6 Analogue inputThere are six analogue input pins, named A0 to A5. Analogue inputpins read a voltage between 0 V and 5 V. There is no need to configurethe analogue input pins in the setup() function.

In the loop() function, read an analogue input pin’s value us-ing analogRead(n) (note the American spelling). The argumentn selects which pin to read (A0 to A5). The value returned byanalogRead() is an integer between 0 and 1023, correspondingto the input voltage being in the range 0 V to 5 V.

void setup() pinMode(10, OUTPUT);

void loop() int value;value = analogRead(A0); // read pin A0// value is 0 to 1023digitalWrite(10, (value > 512));

3.7 Analogue output (sound)Microcontrollers do not usually have analogue outputs, but analoguesignals can be simulated using digital outputs.

For example, making ‘Super Mario video game music’ is easilydone by connecting a loudspeaker to a digital pin and then generatinga digital square wave of the right frequency. (Exactly the same way itwas done in those old ‘eight-bit’ video games.) This is so useful thatthere are some built-in functions to help us do it.

tone(pin, frequency) plays a tone of the given frequencyon the digital output pin.

tone(pin, frequency, duration) plays a tone of the givenfrequency on the given digital output pin for duration mil-liseconds, then stops the tone. (Note that the sketch will continueto run while the tone is being played, so use delay() to pause thesketch for the duration if necessary.)

void setup() pinMode(2, OUTPUT);

// one semitone (the 12th root of 2)const double semi = 1.0594630943592953;

double frequency = 220.0;

void loop() tone(2, frequency, 200);delay(250); // wait for tone to finishfrequency = frequency * semi;if (frequency > 440.0)frequency = 220.0;

noTone(pin) turns off any tone that might be playing on pin. (If you use tone() without the duration argument thenyou probably want to use noTone() fairly soon afterwards to avoid annoying your neighbours.)

3.8 DelaysUse the delay(n) function to pause execution of the loop()function for n milliseconds.

For finer control, use the delayMicroseconds(n) functionto pause execution for n microseconds.

Note that all most other activities will stop during a delay.

void setup() pinMode(13, OUTPUT);

void loop() digitalWrite(13, HIGH);delay(100); // 0.1 seconddigitalWrite(13, LOW);delayMicroseconds(100000); // 0.1 second

5

Page 6: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

3 ARDUINO COOKBOOK

3.9 Using the serial monitorAfter uploading a sketch to the Arduino board, the USB connection can be used to communicate with your running sketch.In the IDE, click on Tools>Serial monitor (or press ‘Control-Shift-M’) and a window will open that behave like a‘terminal’ or ‘console’ for the Arduino. Communicating with this window requires just a little extra code in your sketch.

Prepare your sketch to communicate with the serial monitor usingSerial.begin() in your setup() function. (The argument 9600 is thespeed, in bits per second, that the connection will use. The default value is al-most always fine.)

You can now use Serial.print() to print information on the serial mon-itor, or Serial.println() to print it with a newline afterwards.

In the other direction, use Serial.read() to get the next character re-ceived from the serial monitor (or a -1, if there were no characters available).Similarly, Serial.readString() will read an entire line from the serialmonitor.

void setup() Serial.begin(9600);

void loop() if (Serial.available()) int received = Serial.read();Serial.print("Received: ");Serial.println(received);

You can also check if any characters are available to read using Serial.available()().

6

Page 7: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

A ARDUINO FUNCTION REFERENCE

A Arduino function referenceMany useful functions are available to your sketch, some built-in to the programming language and others accessible afterincluding a library at the beginning of your sketch. This section introduces some built-in functions, and then a few usefullibrary functions.

A.1 Timing

delay(ms) pauses the sketch for ms milliseconds.delayMicroseconds(us) pauses the sketch for us microseconds.millis() gives the number of milliseconds that have passed since the sketch started running. Note that the value from this

function should be stored in a long variable. It will wrap back to zero after about 50 days. (If you store the value in anint variable, it will wrap after about a minute.)

micros() gives the number of microseconds that have passed since the sketch started running. The value is a long andwraps back to zero after about 70 minutes.

A.2 Numbers

constrain(x, min, max) constrains x to be between min and max. (If x is less than min, it returns min. If x is greaterthan than max, it returns max. Otherwise it returns x.)

map(value, fromLow, fromHigh, toLow, toHigh) maps a number from one range to another. In other words,a value of fromLow is mapped to toLow, a value of fromHigh to toHigh, and values in between fromLo/High aremapped to values in between toLow/High.

min(x, y) gives you the smaller of x or y.max(x, y) gives you the larger of x or y.

A.3 Random numbersrandom(max) returns a random integer in the range 0. . .max.random(min, max) returns a random integer in the range min. . .max.randomSeed(seed) initialises the random number generator with a seed

value. (If you use the same seed then you will get the same sequence ofnumbers when you call random(), so it is a good idea to use a differentseed every time. An analogue input pin, with nothing connected to it, is apossible source of seed values.)

void setup() Serial.begin(9600);randomSeed(analogRead(A0));

void loop() Serial.println(random(0, 100));delay(250);

A.4 Bit manipulation

bit(n) computes a mask for the nth bit of a number. Bits are numbered starting from zero, which is the least significant(right-most) bit.

bitClear(variable, n) clears (sets to zero) the nth bit of the variable.bitSet(variable, n) sets the the nth bit of the variable.bitRead(value, n) returns the nth bit of the value.bitWrite(variable, n, b) sets the nth bit of the variable to b (which should be either 0 or 1.

A.5 MathematicsThese functions are available in the math library. At the beginning of your sketch, include a line that says:

#include <math.h>

abs(n) returns the absolute (i.e., non-negative) value of n.pow(base, exponent) raises base to the power of exponent, both of which can be floating-point numbers.sin(x), cos(x), tan(x) calculates the sine, cosine or tangent of x.sqrt(x) calculates the square root of x.

7

Page 8: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

B BREADBOARDS

B BreadboardsBreadboards provide a matrix of terminals into which component leads can be plugged. Internal connections in the breadboardconnect the component leads together, playing the part of wires in the circuit. These internal connections cannot be modified,so part of the challenge of building a circuit on a breadboard is to arrange the components so that the internal connections createexactly the desired circuit.

terminal (for component lead)electrical connection (works like a wire)

sign

al c

onne

ctio

ns

ground (GND, 0V)power (+5V)

A typical small breadboard has 30 rows of signal connections, each row divided into two sets of six internally-connectedterminals. Running along all the rows is a ground connection (often marked with a black line) and a power connection (oftenmarked with a red line).

A simple circuit is shown on the right. Each LED is connected to 220 Ω current-limiting resistors and push-button switches, to turn them on. Even such a simplecircuit can be built in many ways on a breadboard. Below we show each LEDconnected in an identical circuit but using a different breadboard layout.

+5V

GND

220

GND

220

8

Page 9: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

C COLOUR CODE FOR RESISTORS

C Colour code for resistorsResistors are marked with their value using a colour code.Look on the resistor to see how many colour bands it has,then use the table on the right to convert that into a number.

Resistors with four bands use the first two bands to en-code a two-digit number, which is multiplied by a powerof ten according to the third band. (The fourth band is atolerance, or ‘accuracy’, specified as a percentage.)

Resistors with five bands use the first three bands to en-code a three-digit number, which is multiplied by a powerof ten according to the fourth band. (The fifth band is thetolerance.)

Reverse the process to turn a numeric resistance into acolour code. Take the first two (or three) digits of the re-sistance, and convert them into colours. Then count howmany zeros are left, and convert that number into a multi-plier colour.

9

Page 10: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D Devices and sensorsSome devices are available mounted on small circuit boards that plug into the connectorson the microcontroller board. These devices, called shields, typically perform complex (ormultiple) functions that use many of the microcontroller’s input/output connections. Plug-and-play devices are convenient, but they lack the flexibility (and fun) of using a solderlessbreadboard.

The ‘Grove’ system uses a shield as a ‘back-plane’, providing easy access to the input/out-put pins of the microcontroller using a single type of connector. Lots of analogue and digitaldevices are available that can be plugged into the Grove shield using a standard cable. Someof them are described in the appendices.

D.1 Grove digital indicators (light and sound)If the built-in LED is not enough, additional LEDs can be plugged into the Grove back-plane. If an audio indicator is requiredinstead of visual, a buzzer can be plugged in too. They are both ‘on-off’ devices, so the programming interface is identical.When the digital output pin is HIGH, the LED will be on (or the buzzer will emit a continuous ‘beep’). When the pin is LOW,the LED will be off (or the buzzer will be silent).

The buzzer can also be used to play tones (see Section ??) but the result is not very pleasant. (The tone() function andthe built-in frequency of the buzzer ‘fight’ with each other.)

void setup() pinMode(2, OUTPUT);

void loop() digitalWrite(2, HIGH); // LED on, or buzz!delay(200);digitalWrite(2, LOW); // stopdelay(800);

D.2 Grove loudspeakerConnected to a digital output and pulsed at an appropriate fre-quency, the Grove loudspeaker can make a musical tone.

The example on the right uses a very short delay to gener-ate frequencies based on the relationship

f = 1/t

where t is the time needed for one complete cycle (half thecycle is spent with the output HIGH and the other half withthe output LOW). If you would like some mathematical chal-lenges:

const int speakerPin = 3;

int noteDelays[] = 1911, 1702, 1516, 1431, 1275, 1136, 1012, 955

;

void sound(int uSecs)for (int i = 0; i < 100; i = i + 1) digitalWrite(speakerPin, HIGH);delayMicroseconds(uSecs);digitalWrite(speakerPin, LOW);delayMicroseconds(uSecs);

void setup() pinMode(speakerPin, OUTPUT);digitalWrite(speakerPin, LOW);

void loop() for (int n = 0; n < 8; n = n + 1) sound(noteDelays[n]);delay(100);

10

Page 11: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.3 Breadboard loudspeakerConnecting a digital output to an external loudspeaker on abreadboard is easy, but we have to be careful not to overloadthe microcontroller’s output pin.

According to the manufacturer’s documentation, each dig-ital output pin can supply up to 40 mA of current. We knowthat the HIGH output voltage can be as high as 5 V. UsingOhm’s law it is easy to calculate the resistance correspondingto 40 mA at 5 V:

V = IRR = V/I

= 5/0.07= 120 Ω

A loudspeaker has a very low resistance (8 Ω is typical), so we can ignore it. For a small safety margin we should choose aresistor with a slightly higher value than 120 Ω. The next higher standard value is 150 Ω, and this is a great choice to protectthe microcontroller from being overloaded without losing more audio volume than necessary.

The sketch (and challenges) for the Grove loudspeaker apply equally well to the breadboard loudspeaker.

D.4 Breadboard LEDsA breadboard makes it easy to connectmany digital outputs to LEDs. LEDs are‘polarised’ and must be connected theright way round or they will not work.

anode (+)

cathode (-)longer

bent tab

flat

connect todigital outputusing resistor

connect toGND (0V)

const int firstLED = 2; // LEDs connected to digitalconst int numLEDs = 4; // outputs 2, 3, 4, 5

const int lastLED = firstLED + numLEDs - 1;

void setup() // firstLED...lastLED are all OUTPUT pinsfor (int led = firstLED; led <= lastLED; led = led + 1)pinMode(led, OUTPUT);

void display(int bits)// for each bit in bits, turn on the corresponding LEDfor (int led = firstLED; led <= lastLED; led = led + 1) int level = (bits & 1) ? HIGH : LOW; // check the first bitdigitalWrite(led, level);bits = bits >> 1; // shift all the bits one place right

int counter = 0;

void loop() display(counter);counter = counter + 1;delay(500);

Too much current can damage themicrocontroller and the LED, so the out-put pin has to be connected to the LEDusing a resistor. A value between 220 Ωand 1k Ω will work.

Resistors are marked with theirvalue using a colour code. The code isexplained in Appendix C.

11

Page 12: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.5 Grove LED barThe LED bar connects to a pair of dig-ital outputs (in the example below, D8and D9). It can display a level (asolid line of lit segments) or an arbi-trary pattern controlled by a 10-bit num-ber. Use setLevel() to set a level,or setBits() to set a pattern. Thefirst eight segments are green, the ninthis amber, and the tenth is red, makingit an ideal indicator for sound or similarlevels.

#include <Grove_LED_Bar.h> // get access to the LED functions

Grove_LED_Bar bar(9, 8, 1); // interface to a bar on D8, D9

void setup() bar.begin(); // initialise the bar

void loop() for (int i= 1; i <= 10; i = i + 1) bar.setLevel(i); // solid level indicationdelay(100);

for (int i= 9; i >= 0; i = i - 1) bar.setBits(1 << i); // single LED litdelay(100);

D.6 Breadboard LED barYou can drive the LED yourself, one at a time, using a breadboard. The LED barcontains ten individual LEDs, each connected to two pins. As with single LEDs,a resistor (larger than 220 Ω) is needed to avoid damaging the microcontroller orLED with too much current. The LEDs in the bar are also polarised. One corner ofthe package is slightly flattened (making an ‘index’ for pin 1 of the array); the pinsalong that side should be connected to the digital outputs, through a resistor. Thecorresponding pins on the opposite side should be connected to GND (0 V). index 1 2 3 4 5 6 7 8 9 10

20 19 18 17 17 15 14 13 12 11

Note that the LEDs in the package have no common elec-trical connections. The first LED is connected to pins 1and 20, the second to pins 2 and 19, and so on. Both pinsof an LED must be connected for it to work. (For example, touse the first and third LEDs only, connect an output resistor topin 1 and GND to pin 20, and an output resistor to pin 3 andGND pin 18.) Unused LEDs can be left disconnected.

LED arrays are great for displaying the level of a volt-age, or something converted into a voltage by a sensor (soundlevel, light level, position, etc.).

Pin 1

12

Page 13: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.7 Lots of LEDs: LoL shieldA 14×9 array of LEDs that can display simple graph-ics, static text, and scrolling text. The first exampleshows how to turn individual LEDs on or off, by mak-ing a dot walk from the top-left corner (nearest the USBconnector) to the bottom-right corner.

#include <Charliplexing.h>

void setup() LedSign::Init(); // initialise the LoL shield

void loop() for (int y = 0; y < DISPLAY_ROWS; y = y + 1) for (int x = 0; x < DISPLAY_COLS; x = x + 1) LedSign::Set(x, y, 1);delay(20);LedSign::Set(x, y, 0);

D.7.1 Scrolling text

Displaying scrolling text is even easier, using a built-infont. Use Myfont::Banner(length, string) toscroll string across the display once. To find the lengthof string, you can use the strlen() function.

#include "Charliplexing.h"#include "Myfont.h"

unsigned char test[] = "Hello, world!";

void setup() LedSign::Init();

void loop() Myfont::Banner(strlen((char *)test), test);

D.7.2 Non-moving text

Displaying static text is done by drawing one character at aspecified position. Use Font::Draw(c, x, y) to drawthe character c at position (x,y). The example on the rightdisplays two digits of a counter by drawing each digit indi-vidually on the LEDs.

Characters are written inside single quotes, like this ’x’,and they behave just like integers. It is convenient that thedigits begin at character ’0’ and then increase by one foreach successive digit. The example uses this to draw thenumber, using counter/10 to get the ‘tens’ column, andcounter%10 (the ‘remainder’ operator) to get the ‘units’column.

#include "Charliplexing.h"#include "Font.h"

void setup() LedSign::Init();

byte counter = 0;

void loop() LedSign::Clear();Font::Draw(’0’ + counter / 10, 1, 0);Font::Draw(’0’ + counter % 10, 8, 0);counter = counter + 1;if (counter > 99) counter = 0;delay(100);

13

Page 14: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.8 Grove 16×2 LCD displayTwo lines of sixteen characters is often plenty of text.(Clock, stopwatch, temperature readout, etc.) The LCDdisplay plugs into any of the I2C connectors on theGrove back-plane.

#include <Wire.h> // because we are using I2C#include "rgb_lcd.h" // get access to the LCD

functions

rgb_lcd lcd; // creates an interface to the LCD

void setup() lcd.begin(16, 2); // 16 columns x 2

lineslcd.setRGB(16, 128, 16); // backlight colour

lcd.setCursor(0, 0); // column 0, line 0lcd.print("hello, world!"); // print a message

void loop() lcd.setCursor(0, 1); // column 0, line 1lcd.print(millis() / 1000);lcd.print(".");lcd.print(millis() / 100 % 10);delay(100);

D.9 Grove 128×64 OLED displayThis tiny screen can displaytext and graphics with a res-olution of 128×64 pixels.

#include <Wire.h> // we need I2C#include <SeeedOLED.h> // OLED interface

void setup() Wire.begin(); // initialise I2CSeeedOled.init(); // initialise OLED displaySeeedOled.clearDisplay(); // clear the screenSeeedOled.setNormalDisplay(); // normal (non-inverse) modeSeeedOled.setPageMode(); // page (row) addressing modeSeeedOled.setTextXY(0,0); // cursor to row 0, column 0SeeedOled.putString("Hello World!"); // say hello

void loop() SeeedOled.setTextXY(2, 0); // row 2, column 0SeeedOled.putNumber(millis() / 100); // tenths of a seconddelay(100);

D.10 Grove buttonConnected to a digital input, the level will be HIGH when the button is being pressed andLOW at all other times. The example shows how a button connected to D3 can control abuzzer connected to D2. (If you don’t have a buzzer, change the value of buzzer from 3to 13 and control the built-in LED instead.)

const int button = 2;const int buzzer = 3; // or 13, to control the built-in LED

void setup() pinMode(button, INPUT);pinMode(buzzer, OUTPUT);digitalWrite(buzzer, LOW); // make sure buzzer is off

void loop() int level = digitalRead(button); // copy button leveldigitalWrite(buzzer, level); // ... to buzzer

14

Page 15: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.11 Breadboard buttonsUsing many buttons (for example, to make a simple musicalkeyboard) is easily done on a breadboard. Each button is ei-ther on or off, so we have to arrange for the button to changea normally HIGH signal to a LOW signal (or the other wayaround). Connecting a digital input pin to 5 V through a re-sistor keeps the level HIGH (with the button open). When thebutton is pressed, the input is ‘shorted’ to ground bringing theinput pin to a LOW level. The resistor protects the power sup-ply by allowing only a small current to flow from 5 V to GNDwhen the button is pressed.

The example below shows how one way to connect twopush-buttons to digital input pins 11 and 12.

Switch open, input HIGH:

digital HIGH

GND 5V56kswitch open

5V

Switch closed, input LOW:

digital LOW

GND 5V56kswitch closed

0.1 mA

0V

The resistor is called a pull-up resistor. Some microcontrollers (including the one we are using) have built-in pull-upresistors. To connect the internal pull-up resistor to an input pin, configure the pin as INPUT_PULLUP in your setup()function.

D.11.1 Grove touch sensor

Touch sensors detect when your finger is touching (or justclose to) them, and set the digital output HIGH. At othertimes, the output is LOW.

const int touchPin = 2;const int ledPin = 13;

void setup() pinMode(touchPin, INPUT);pinMode(ledPin, OUTPUT);

void loop() int touchValue = digitalRead(TouchPin);digitalWrite(ledPin, touchValue);

D.12 Grove rotary encoderRotary encoders detect changes in angle, sending out pulses indicating which direc-tion they are being turned. Unlike angle sensors (which detect absolute position,and have limits) an encoder can be turned continuously in the same direction asmuch as you want.

15

Page 16: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

The interface to the encoder is a little strange. Thedevice must be connected to digital pin 2. When youinclude <Encoder.h> you will get an encoder inter-face defined implicitly. In setup() you have to use itsencoder.Timer_init() function to initialise it. Youcan then look at the variable encoder.rotate_flag()to see if the encoder has been turned. The variable will be setto 1when it is turned, and you can look at the variable variableencoder.direct() which will be 0 for anti-clockwiserotation or 1 for clockwise rotation. After detecting a rota-tion, you have to set encoder.rotate_flag() explic-itly back to 0.

Sounds complicated, but the example on the right shouldmake it clear.

#include <Encoder.h> // access the encoder#include <TimerOne.h> // needed by encoder

void setup() encoder.Timer_init();Serial.begin(9600);

void loop() if (encoder.rotate_flag == 1) if (encoder.direct == 0)Serial.println("backward rotated!");

elseSerial.println("forward rotated!");

encoder.rotate_flag = 0;

D.13 Grove real-time clockMicrocontrollers usually do not have any built-in clock, sothey do not know what time of day it is. An external clock canprovide this information. The small battery on the board letsthe clock remember the time, even when the microcontrolleris turned off.

#include <Wire.h> // the I2C bus#include "DS1307.h" // the clock chip

DS1307 clock; // clock chip interface

void setup() Serial.begin(9600);clock.begin();clock.fillByYMD(2016,6,23); // 2016/06/23clock.fillByHMS(10,30,00); // 10:30:00"clock.fillDayOfWeek(THU); // Thursdayclock.setTime();

void loop() clock.getTime();Serial.print(clock.hour, DEC);Serial.print(":");Serial.print(clock.minute, DEC);Serial.print(":");Serial.println(clock.second, DEC);delay(1000);

D.14 Analogue inputsMany sensors produce an analogue voltage and they can all be read in the sameway. They connect to any one of the analogue inputs (A0 to A3), require nospecial setup, and can be read using the usual analogRead() function. Theexample on the right reads the value from any analogue sensor and prints thevalue ten times per second on the serial monitor.

void setup() Serial.begin(9600);

void loop() Serial.println(analogRead(A0));delay(100);

16

Page 17: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

The sensors shown above are, fromleft to right: light level, sound level,temperature, angle (rotary, like a volumecontrol), position (linear).

To convert a value read from thetemperature sensor into degrees centi-grade requires a little mathematics. Theexample below shows how to do it.

#include <math.h> // get access to log()

const int pin = A0; // temperature sensor

// from the data sheet...const float B = 4275.0; // B value of the thermistorconst float R0 = 100000.0; // R0 = 100k

void setup() Serial.begin(9600);

void loop() int a = analogRead(pin);

float R = 1023.0 / a - 1.0;float temp = 1.0 / (log(R) / B + 1/298.15) - 273.15;

Serial.print("temperature = ");Serial.println(temp);

delay(100);

D.14.1 Breadboard potentiometers

These miniature ‘trimmer’ potentiometers (sometimes incor-rectly called ‘variable resistors’) plug into the breadboard di-rectly. The two outermost terminals should be connected to5 V and 0 V (GND), and the middle terminal connected to ananalogue input on the microcontroller.

D.14.2 Breadboard joysticks

This little board plugs directly into a breadboard. Two ana-logue outputs are available, providing horizontal and verticalposition information, and should be connected to analogue in-put pins. The button is clickable, and when pressed will con-nect the SEL output to ground. No pull-up resistor is includedon the device, so the SEL output should be connected to adigital input pin configured as INPUT_PULLUP (see Sec-tion D.11).

D.14.3 Breadboard temperature sensor

The LM35 is a three-pin analogue temperature sensor. When supplied with 0 V (GND) and 5 V (Vcc), it produces an outputvoltage that is linearly proportional to the ambient temperature: VOUT = 10× TCelsius mV.

The connection diagram shows the view from underneath the device. It must be correctly connected to GND and VCC,otherwise it will be damaged.

LM35Precision Centigrade Temperature SensorsGeneral DescriptionThe LM35 series are precision integrated-circuit temperaturesensors, whose output voltage is linearly proportional to theCelsius (Centigrade) temperature. The LM35 thus has anadvantage over linear temperature sensors calibrated in˚ Kelvin, as the user is not required to subtract a largeconstant voltage from its output to obtain convenient Centi-grade scaling. The LM35 does not require any externalcalibration or trimming to provide typical accuracies of ±1⁄4˚Cat room temperature and ±3⁄4˚C over a full −55 to +150˚Ctemperature range. Low cost is assured by trimming andcalibration at the wafer level. The LM35’s low output imped-ance, linear output, and precise inherent calibration makeinterfacing to readout or control circuitry especially easy. Itcan be used with single power supplies, or with plus andminus supplies. As it draws only 60 µA from its supply, it hasvery low self-heating, less than 0.1˚C in still air. The LM35 israted to operate over a −55˚ to +150˚C temperature range,while the LM35C is rated for a −40˚ to +110˚C range (−10˚with improved accuracy). The LM35 series is available pack-

aged in hermetic TO-46 transistor packages, while theLM35C, LM35CA, and LM35D are also available in theplastic TO-92 transistor package. The LM35D is also avail-able in an 8-lead surface mount small outline package and aplastic TO-220 package.

Featuresn Calibrated directly in ˚ Celsius (Centigrade)n Linear + 10.0 mV/˚C scale factorn 0.5˚C accuracy guaranteeable (at +25˚C)n Rated for full −55˚ to +150˚C rangen Suitable for remote applicationsn Low cost due to wafer-level trimmingn Operates from 4 to 30 voltsn Less than 60 µA current drainn Low self-heating, 0.08˚C in still airn Nonlinearity only ±1⁄4˚C typicaln Low impedance output, 0.1 ! for 1 mA load

Typical Applications

DS005516-3

FIGURE 1. Basic Centigrade Temperature Sensor(+2˚C to +150˚C)

DS005516-4

Choose R1 = −VS/50 µAV OUT=+1,500 mV at +150˚C

= +250 mV at +25˚C= −550 mV at −55˚C

FIGURE 2. Full-Range Centigrade Temperature Sensor

November 2000

LM35

PrecisionCentigrade

Temperature

Sensors

© 2000 National Semiconductor Corporation DS005516 www.national.com

Connection Diagrams

TO-46Metal Can Package*

DS005516-1

*Case is connected to negative pin (GND)

Order Number LM35H, LM35AH, LM35CH, LM35CAH orLM35DH

See NS Package Number H03H

TO-92Plastic Package

DS005516-2

Order Number LM35CZ,LM35CAZ or LM35DZ

See NS Package Number Z03A

SO-8Small Outline Molded Package

DS005516-21

N.C. = No Connection

Top ViewOrder Number LM35DM

See NS Package Number M08A

TO-220Plastic Package*

DS005516-24

*Tab is connected to the negative pin (GND).Note: The LM35DT pinout is different than the discontinued LM35DP.

Order Number LM35DTSee NS Package Number TA03F

LM35

www.national.com 2

17

Page 18: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

D DEVICES AND SENSORS

D.14.4 Breadboard light sensor

A light-dependend resistor (LDR, or ‘photocell’)is a resistor whose resistance varies according tothe incident light level. In dim light, the resitanceis high (≈ 500k Ω); in bright light, the resistanceis low (≈ 10k Ω).

Using a LDR in one half of a voltag dividercircuit creates an analogue voltage proportionalto light level. In the example on the right, in dimlight the voltage at A0 will be approximately

20k

20k + 500k× 5 V = 0.19 V.

In bright light, the voltage will be

20k

20k + 10k× 5 V = 3.33 V.

A0

GND

5V

20k

10-5

00k

fixedresistor

light-dependentresistor

Like fixed resistors, LDRs are not polarised; you can connect them either way round.

D.15 Grove ultrasonic ranger‘Range’ is another word for ‘distance’, and an ultrasonicranger uses high-frequency (inaudible) sound pulses to mea-sure the distance to the nearest object placed in front of it (thesame mechanism that bats use to ‘see’ in the dark).

#include "Ultrasonic.h"

Ultrasonic ranger(7); // ranger connected to D7

void setup() Serial.begin(9600);

void loop()long cmRange = ranger.MeasureInCentimeters();Serial.print("The nearest object is ");Serial.print(cmRange);Serial.println(" cm");delay(250);

D.16 Game controller shieldClassic game controllers combine a joystick with four but-tons. The game controller shield has a two-axis analogue joy-stick connected to analogue inputs A0 and A1. The joystickis clickable, and when clicked will connect digital pin 2 toground. When clicked, the four buttons connect digital pins3, 4, 5, or 6 to ground. There are no pull-up resistors onthe board, so to work properly digital pins 2 to 6 should beconfigured as INPUT_PULLUP (see Section D.11).

18

Page 19: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

Project-Based Learning Workshopworkshop manual, cookbook, and technical reference

Contents1 Introduction 1

1.1 Organisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Equipment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Setting up the development environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 Project 2

3 Arduino cookbook 33.1 Sketches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3.1.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33.1.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33.1.3 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3.2 Microcontroller configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43.3 Digital output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43.4 Digital input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43.5 Digital input (buttons and switches) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.6 Analogue input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.7 Analogue output (sound) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.8 Delays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.9 Using the serial monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

A Arduino function reference 7A.1 Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7A.2 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7A.3 Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7A.4 Bit manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7A.5 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

B Breadboards 8

C Colour code for resistors 9

D Devices and sensors 10D.1 Grove digital indicators (light and sound) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10D.2 Grove loudspeaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10D.3 Breadboard loudspeaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11D.4 Breadboard LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11D.5 Grove LED bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12D.6 Breadboard LED bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12D.7 Lots of LEDs: LoL shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

D.7.1 Scrolling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13D.7.2 Non-moving text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

D.8 Grove 16×2 LCD display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14D.9 Grove 128×64 OLED display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14D.10 Grove button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14D.11 Breadboard buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

D.11.1 Grove touch sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15D.12 Grove rotary encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15D.13 Grove real-time clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16D.14 Analogue inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

D.14.1 Breadboard potentiometers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17D.14.2 Breadboard joysticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17D.14.3 Breadboard temperature sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17D.14.4 Breadboard light sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

D.15 Grove ultrasonic ranger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18D.16 Game controller shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Page 20: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

Cookbook Engineering Workshop — MilestonesWhen you have completed a step, tick the box. At every ‘,’, demonstrate your project to the instructor.

Add a second LED which flashes at the same time as the first LED.

Make the second LED flash in the opposite way to the first LED. (When one is on, the other shouldbe off.)

, 4 Demonstrate your project to the instructor.

Make the LEDs blink only when the pushbutton is pressed.

Make the LED flash only when the button is not pressed.Imagine that reversing the button was needed because a requirement changed (or a bug was found)in your ‘product’. What are your observations about the cost of modifying the button (to have theopposite behaviour) as a firmware update, compared to the cost of physically modifying the circuit?

, 5 Demonstrate your project to the instructor.

(Record your observations on the other side of this page.)

Read an analogue input, and make the LED ‘on’ period be proportional to the analogue value.The analogue input ranges from 0 to 1023. You can use this value directly as the argument todelay().

Make the cycle time constant (approximately one second).As the ‘on’ time increases, the ‘off’ time should decrease in inverse proportion. When the ‘on’ timeis maximum (1023) the ‘off’ time should be minimum (e.g., 0). When the ‘on’ time is minimum(0) the ‘off’ time should be maximum (e.g., 1023).

Reduce the total cycle time.If you have delays of ‘value’ (on) and ‘1023 - value’ (off) then try dividing all your numbersby 10, so your delays become ‘value / 10’ (on) and ‘(1023 - value) / 10’ (off).

Keep reducing the cycle time.Try dividing by 20, 30, and so on (but by no more than 100).Do you notice a particular effect beginning to happen?Can you think of a practical use for this effect?

, 6 Demonstrate your project to the instructor.

(Record your observations on the other side of this page.)

Page 21: Project-Based Learning Workshop - 立命館大学piumarta/pbl/pbl.pdf · to launch. A window will open that looks like the one shown on the right. In the Tools>Board menu, make sure

Cookbook Engineering Workshop — Observations(At the end of the PBL course you will be asked to submit a written report. Use your notes on the otherside of this page to help you remember your experience, thoughts, and conclusions about this workshop.)

1 Future-proofingWhen requirements change (or a bug is found) in your product, how does using a firmware (plus hardware)solution compare to using a hardware (only) solution? Which is easier to maintain, upgrade and evolve?

2 Lateral thinkingWhen your flashing cycle time became short, you noticed that a digital behaviour began to have an ‘ana-logue’ effect. Can you explain how this works? Can you think of any practical uses for this effect?Compared to using an ‘analogue’ solution (e.g., building real hardware to control the voltage or currentthrough a device to modify its appearance) are there any advantages to doing it the digital/firmware way?

3 ‘Cookbook’ engineeringWhat was your experience using ‘cookbook engineering’? Do you feel that you have now ‘got the gist’of microcontroller programming? Could you make simple changes to microcontroller programs on yourown? Do you feel you acquired new skills and information in a very rapid and efficient manner, by actuallyexperimenting with and modifying a system in order to form a practical understanding of it?

Do you consider yourself a microcontroller expert who could develop a complex control system ‘fromscratch’, using all the advanced features available? Does it matter?

Given a ‘cookbook’ that shows how each one can be used, do you think you could have fun with themany different input devices, sensors, and displays that are available in the lab?

+ Other notesWhat did you learn during the workshop? Was it beneficial to work as part of a team? If so, in what ways?Etc. . .