0% found this document useful (0 votes)
50 views

Arduino English

This document provides an introduction to microcontrollers and the Arduino development environment. It discusses what a microcontroller is and how it is used in many electronic devices. The Arduino board, which contains a microcontroller chip, is introduced as a platform for learning about microcontroller programming. The document outlines the Arduino hardware including ports and pins. It also describes the Arduino software development environment, where programs called sketches are written in a language similar to C and then compiled and transferred to the Arduino board.

Uploaded by

iam lame
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Arduino English

This document provides an introduction to microcontrollers and the Arduino development environment. It discusses what a microcontroller is and how it is used in many electronic devices. The Arduino board, which contains a microcontroller chip, is introduced as a platform for learning about microcontroller programming. The document outlines the Arduino hardware including ports and pins. It also describes the Arduino software development environment, where programs called sketches are written in a language similar to C and then compiled and transferred to the Arduino board.

Uploaded by

iam lame
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to Microcontrollers


The Arduino Board as Control Unit

Workbook
Name:
Date:

(Science & Technology Dept, Schule Schloss Salem)

Page 1
Table of Contents

1. What is a microcontroller? ........................................................ 1

2. Introducing: The Arduino hardware ........................................... 2

3. Software: The Arduino’s developer environment ...................... 3

4. Let’s get started: your first program .......................................... 5

5. Breadboard and RGB-LED .......................................................... 7

6. Sub-programs ........................................................................... 9

7. Operating a loudspeaker on the Arduino ................................. 10

8. Variables ................................................................................. 12

9. Feedback for the user – the serial monitor............................... 14

10. LC Display ............................................................................... 15

11. for loops ................................................................................. 16

12. while loops ............................................................................. 18

13. Dimming an LED – Pulse width modulation .............................. 20

14. Toggle switches ....................................................................... 22

15. Appendix A Basics of an electrical power circuit .................. 23

16. Appendix B Protective resistors for LEDs ............................. 24

17. Appendix C Addition of a library .......................................... 26

18. Appendix D Troubleshooting ............................................... 27


1.

Page 2
1.
What is a microcontroller?

An airbag gets released when a car is involved in a crash. Robot lawn mowers, which are can be
observed with increasing frequency, are able to mow grass exactly up to the edges of a property. In
many shops an electronic sliding door opens automatically as soon as a customer approaches the
entrance. New dishwashers recognize how dirty the dishes are and adjust the time of the program.
After a heart attack, many heart patients receive a small defibrillator implant that can recognize the
threat of another heart attack and issue an electrical shock to revive the patient.

Our everyday lives are full of such electronic devices that make life easier. Sometimes they even
literally become life-savers.

Perhaps one or the other of the above-mentioned examples have led you to ask just how these
things actually work.

Certainly there is all kinds of technology or electronics in them. But in most of these devices there
wouldn’t be room for a normal computer, and it would be much too expensive and “too good” for
these applications.

If you take a look at the technology behind airbags, sliding doors and dishwashers, you will always
find they have one component in common: the microcontroller.

In principle, microcontrollers work like a compact computer, but with much lower capacity. They
combine various components, such as a processor (CPU), memory, a USB interface, a display, and an
analog-to-digital (A/D) converter all on one single chip. The microcontroller used here is named
“ATmega328”. The advantage of microcontrollers is that they can be specially programmed for the
intended task and are relatively inexpensive.

An airbag is released when a car is involved in a crash. Robot lawn mowers, which are can be
observed with increasing frequency, are able to mow grass exactly up to the edges of a property. In
many shops an electronic sliding door opens automatically as soon as a customer approaches the
entrance.

This workbook will make it possible for you to learn how to program a microcontroller almost
entirely on your own. The board with which you will learn how to program a microcontroller is called
the Arduino Uno, or just Arduino.

In place of the word “microcontroller” we often use the abbreviation μC.


“μ” (pronounced as: mew) is the 12th letter of the Greek alphabet and is used here as the
abbreviation for “micro”.
The name Arduino comes from the pub in which the founders of the Arduino project often met.

Page 1
2.
Introducing: The Arduino hardware

Getting to know the Arduino:

The heart of our Arduino: the actual microcontroller is called “ATmega328”. Its interfaces are
called ports. The ATm has 28 ports or pins. Some of them serve as inputs and outputs for electrical
signals.
The ports 0 to 13 are so-called digital pins. This means they
only recognize two states: between “on” and “off”, or,
respectively, “high” and “low”. In computer language this
Reset button; begins
programm over again 1. corresponds
USB interface for 2.
connecting to a PC. It 3. between the digits 0 or 1.
transmits data and
supplies the Arduino
with power.

Connection for
external power
supply (up to 12V):
in case the Arduino is
to be operated
without a PC.
wird.
These pins provide power for peripheral The pins A0 to A5 are analog input pins.
devices [actuators] (e.g., motors, loud They can measure currents between 0V
speakers, etc) and supply different and 5V.
2. amounts of current.
The term hardware is generally used for mechanical and electronic components of a micro-controller or a PC
(basically everything one can put your hands on). The English roots of the term go back to items made of
metal (cutlery, tools, machine parts) and is still used today in that sense; today it is also used around the
world to describe the physical components of a computer system.
On the board of our Arduino, aside from the microcontroller, there are also many small components
(resistors, convertors, regulators...) and many different kinds of interfaces.

Arduino vs. Smartphone


For computers or smartphones we mention the speed of their processors, which means how fast their data
can be processed. The Atmega328 has a 16 MHz frequency oscillator and 32 kilobytes (KB) of flash memory.
Compared with an iPhone 6 is the Arduino a lame duck. It has a processor with 1.4 GHz (=1400 MHz) and 1 GB
(or 1,000,000 kilobytes) memory. But for comparison: on his moon flight Neil Armstrong was assisted by a
computer with 4KB of working memory and a 1 MHz processor.

Page 2
3.
Software: The Arduino’s developer environment

Before working with the Arduino it has to be connected to a PC and programmed. The Arduino is, of
course, only as “smart” as the person who is coding it. It is not capable of independent thought, but
simply works through the commands it is given. A series of commands is called a program or a
sketch.
In order to bring an Arduino to life, you write a program on a PC in the so-called development
environment and transfer it to the Arduino via the USB port. The image below describes how this
works.
The arrow has two functions: first it Magnifying glass icon opens a
compiles and then it transfers the screen in which the Arduino
Menu bar program to the Arduino. can send information back to
the PC. Computer
zurückschicken kann.

A click on the symbol compiles


the program and identifies any
errors.

You write the program for the


Arduino in the main white
window
The blackas Programm
window showsfüryou
denthe
Arduino.
size of the file or any errors that
occur during compilation.

Status bar for the Arduino‘


connection with the PC. If a
compilation does not function, a
common mistake is that the
number of the COM pin is false
(make changes at Tools  serial
pin  click on correct COM pin)

Task 3.1: Start the development environment by opening the program arduino.exe.

Sketches are written in a programming language that resembles the famous computer language „C“ .
Before the program you write is transferred to the Arduino by a data cable, it is translated into machine
code by an electronic interpreter. This process is called compiling. It is quite lucky for us that we don’t
have to learn Arduino’s own language, in order to communicate with it. It is actually quite complicated.
For example, for formula for c = a + b looks like this in machine code: 8B 45 F8 8B 55 FC 01 D0

Page 3
Before you construct your first circuit with Arduino, you need to make sure that the microcontroller
can communicate properly with the PC. To do that we first send an “empty” program to the PC. All
programs have the same structure.

void setup() {
// Basic settings;
} This part of the program will be repeated an
infinite number of times ( as a loop).
void loop() { The actual program begins here.
// Commands;
}

Your code will later be written in place of // Grundeinstellungen; and //


Anweisungen; in your real (e.g., not empty) program. By the way, it is quite common for
someone to write notes or explanations for other users within the program. Your „own“ text
shouldn’t and can’t be processed later during the compilation. That is why there are so-called
comment lines: anything written in a line with two slashes // will not be recognized during
compilation. It is easy to recognize comments because the program writes them in gray script.

Task 3.2
Write and compile the empty program shown above and then transfer it to the Arduino. When this is
successful, you will see the following results screen:

Error Message
It is not uncommon that the code you write may contain mistakes (typos, errors of logic, …). Sometimes
mistakes also happen while the program code is being transfered to the Arduino. Many of these will be
recognized by the Arduino and disployed – in orange script – in the results screen.
In other words: Whenever something appears in orange, there is an error somewhere.

What does the term „void“ mean?


void can mean empty or hole. The term void is always used to begin the program sections „setup“ and
„loop“. Later you will be able to create further code (so-called subprograms) that you will give names to
and these will each begin with void.

Page 4
4.
Let’s get started: your first program

In this chapter you will learn how to make an LED to blink with the help of the Arduino. At the end of
the chapter you will build a test device with which you can test the reaction time of your own eye.
LEDs can be precisely controlled by the Arduino. For this you use the 20 ports of the Arduino (0 – 13
and A0 to A5). They are like small on-off electrical sockets. Any socket always has a connection with
the potential of 0 V. For the Arduino this the #...GND (ground). The the second connection with the
high potential the ports of the Arduino between 5 V and 0 V can be switched on and off.

Remember your physics: Electrical potential is a kind of „electrical pressure“ on a cable. Much like a
water pipe where there can be more or less water pressure. When you connect a pipe with high pressure
to an area that has lower presser, water will flow. It is exactly the same for electricity: only when there is
a difference in potential will electrons flow. The difference in potential is known as voltage. Attention:
Because both the potential and the difference in potential are expressed in volt, the terms voltage and
potential are often mixed up.!!!

Using the following circuit and the program code we want to make the LED blink:

void setup() {
pinMode(13, OUTPUT);
}

void loop() {
digitalWrite(13,HIGH);
delay(5000);
digitalWrite(13,LOW);
delay(5000);
}

Task 4.1
Set up the circuit and copy the program text. When connecting the LED it is important to insert it the
correct way (the short leg of the LED connects with the smaller potential, i.e. to the GND).

What can you do if it doesn’t work?


 Are the individual commands written correctly? (Upper and lower case do matter here!)
 Does each command line end with a semi-colon?
 Usually you can get help finding the error by reading the black screen. It should describe the
problem found during compilation.

Page 5
Task 4.2
Describe briefly in your workbook what function each line of code has.
1
void setup() { //
pinMode(13, OUTPUT); // 2
}
3
void loop() { //
digitalWrite(13,HIGH); //
4
delay(5000); //
digitalWrite(13,LOW); //
delay(5000); // 5
}

Task 4.3
Change the program code to make the LED blink faster or slower.

Task 4.4 void loop() {


Using this program the LED will not blink. digitalWrite(13,HIGH);
Explain why! delay(500);
(Assume that the setup- section is correct) digitalWrite(13,LOW);
}

Task 4.5 void loop() {


This sample program can be shortened by four lines without digitalWrite(13,HIGH);
any change to the results. delay(500);
Which lines are they? Explain. digitalWrite(13,LOW);
delay(500);
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}

Task 4.6 „Eye testing device“


Reduce the delay time of the blinking LED so that your eye cannot detect any blinking at all
Calculate the blinking frequency (how often per second does your LED turn on) of your eye.
In today’s movies picture frames change about 30 times per second. At this frame rate our eye
perceives individual images as fluent movement.
Compare your own frequency with that of your neighbour and with the frame rate of a movie film.

Page 6
5.
Breadboard and RGB-LED

In the previous chapter you connected an LED to the Arduino. But you can probably imagine that for
many components is will be much more difficult to fit everything onto the Arduino. For that reason
components often are not placed directly onto the Arduino, but instead connected to a so-called
breadboard.
This means:
The pins at the edge (marked by either blue or red
edging) are all connected with one another. They
provide the circuitry with power.
In addition, the 5-hole rows (marked by yellow edging)
are connected with one another.

Now we want to use the breadboard to create a


pedestrian traffic light.

Task 5.1
a) Build the circuit shown below and copy the program for the pedestrian traffic light.
b) Expand the pedestrian light to a car traffic light by expanding the circuitry by one yellow LED
and re-writing the program.
(Hint: Pay attention to the correct order of colours -- green-yellow-red-red/yellow-green –
while programming.
c) Now connect the pedestrian and car traffic lights to form a traffic intersection.

We could also connect the black GND cable


directly to the resistor. However, if we later
need to use several components at the same void setup() {
time which all need to be grounded, it is pinMode(5, OUTPUT);
advisable to make the detour through the power pinMode(6, OUTPUT);
supply on the breadboard. }

void loop() {
digitalWrite(5,HIGH);
delay(2000);
digitalWrite(5,LOW);
digitalWrite(6,HIGH);
delay(2000);
digitalWrite(6,LOW);
}

Page 7
RGB-LED:
A RGB-LED is an LED which contains a red, a green and a blue LED. Therefore we can use the three
short legs of the RGB-LED to turn the different colours on and off; the fourth leg serves as their
common GND connection.

Task 5.2
d) Build the circuit shown below.
Make the RGB-LED light up in the basic colours of red, green and blue.
(Hint: Hold the RGB-LED in front of a white piece of paper and use it as a screen in order to
see the colours better.)
e) Using the RGB-LED you can also create colour mixings. Make the RGB-LEDs light up yellow and
then write down what other colours are possible.
(Hint: Mixing colours)
f) Imagine that you had an LED with four different colours.
How many different colour mixings would then be possible?

220 

Up to now we have used the so-called protective resistance (sometimes named series resistance) for
the LEDs. If we connected the LED directly to the 5V of the Arduino, more power would flow and,as a
result, the life-span of the LED (which under ideal conditions is approx. 10 years of constant use) would
be significantly lower, i.e., it would wear out much sooner. To avoid this, you need to lower the power
that flows through the LED. This is what the protective resistance does when you connect it with the row
of an LED. The size of the protective resistance depends upon the actual conditions, and generally one
uses protective resistors with 220.for LEDs connected to 5V.
In the appendix you will find the exact calculations for protective resistors and a table with the colour
codes for resistors.

Page 8
6.
Sub-programs

It is quite inconvenient to have to switch all three LEDs on separately when using the RGB-LED. A
special function which would have, for example, the name rgbSet (red, green, blue), with which you
could turn each LED on or off as needed, would be very helpful. These kinds of routines can be
programmed as sub-programs. To do so, you write in the following lines before the set-up function:

void rgbSet(bool red bool green, bool blue) {


digitalWrite(9, red);
digitalWrite(10, green);
digitalWrite(9, blue);
}

What does bool mean?


The placeholder for the states of the red, green and blue LED can have two values: 1 for on and 0 for off.
In order for the Arduino to know how much memory it provide and which values it can expect you have to
define which kind of placeholder you are using. The definition bool stands for boolean and indicates that
only the values of 0 and 1 are valid.

If you have written the function described above before the setup function, this command can now
be used in the set up or loop. Here is an example for a loop:

void loop() {
rgbSet(1,0,0);
delay(1000);
rgbSet(0,1,0);
delay(1000);
}

Task 6.1
Use the circuits prepared in chapter 5.
Write the complete program (with the functions rgbSet, setup and loop).
Notice that the pins 9, 10 and 11 must be defined as #!

a) Describe what this program does and then put it to the test!

b) Make the RGB-LED blink in sequence red, green, blue, yellow and white!

Page 9
7.
Operating a loudspeaker on the Arduino

Using the Arduino you can not only play sounds but even melodies through a small loudspeaker. The
loudspeaker is connected with a digital port and GND. The command code is tone:

tone(Port, Frequency (Pitch));

The port to which the loudspeaker is connected does not need to be defined separately as OUTPUT.
This is also completed by the command tone.
A loudspeaker at port 11 plays a tone with the pitch 440 Hz for 1000
void loop() { milliseconds (1 second). The time given in the delay command
tone(11,440); line determines the length of the tone.
delay(1000);
noTone(11); The noTone-Command switches the loudspeaker at port 11 off.
delay(1000); After an interval of 1000ms the program starts again.
}

Task 7.1: Connect a loudspeaker to port 11 and GND.


a) The Arduino should place two tones after one another without a break.
b) The Arduino should make a break of 1 second between the tones

Task 7.2: Find out what is the highest tone you can still hear.

How does a loudspeaker work?


Loudspeakers consist of a permanent magnet and a coil of wire acting as an electromagnet. As soon as
current flows through the coil, a magnetic field is created. By reversing the direction of the current, the
direction of the magnetic field is also reversed. Depending on the direction of the magnetic field the coil
will be attracted or repelled by the permanent magnet. By rapidly changing the direction of the magnetic
field, the coil vibrates back and forth.

Because the coil is attached to a flexible membrane or diaphragm, the air in front of the loudspeaker also
begins to vibrate. Vibrations between about 20 Hertz and 20,000 Hertz produce sounds that can be picked
up by our ears.

Since Arduino only supplies direct current, it can only flow through the loudspeaker in one direction. In
order to produce sounds the loudspeaker is continuously turned on and off. Because the stretched
membrane is not repelled, it returns to its original position by itself. If the current is turned off and on
quickly, the membrane also moves quickly back and forth.

Page 10
Task 7.3
a) Program your own police siren.
b) Switch different resistors one after the other in series to the loudspeaker. What do you
observe? Make an entry in your notebook.
c) Build into your own siren from a) a volume controller (see illustration below)
Info: Our volume controller is a potentiometer (variable resistor).

Task 7.4
Choose one of the following:
Alternative a): Program the song „Alle meine Entchen“. Note the different lengths of the tones.
Alternative b): Play the theme music of a well known movie.

The melody of the German song “Alle meine Entchen”

Keyboard with the individual notes:

Tone:
Frequency
(in Hz):

There is another way to determine the length of a tone in the command tone by using this code:

tone(port, frequency (pitch), length of tone in ms);

In this code you also need to add the delay command, but the command noTone is no longer needed.
nicht mehr benötigt.

Page 11
8.
Variables

A variable is a „place holder“ for a number or integer. This place holder can be given any name you
like (Beware: don’t use umlauts!) and assigned a specific value:

int red = 2;

In this example the variable with the name „rot“ is defined as an Integer variable and assigned the
value of 2. In each position in this program the variable will now have a value of 2.
Usually variables are defined above the setup- section, but it can also be done in the loop- section.

Note: Your data type depends upon what value range the variable includes (see next page). The
„smaller“ the data type, the less storage space will be needed.

In the following program a second variable named time is introduced. What do you think is the
advantage of using it here?
int red = 2;
int time = 1000;
void setup() { void setup() {
pinMode(2, OUTPUT); pinMode(red, OUTPUT);
} }
void loop() { void loop() {
digitalWrite(2, HIGH); digitalWrite(red, HIGH);
delay(1000); delay(time);
digitalWrite(2, HIGH); digitalWrite(red, LOW);
delay(1000); delay(time);
} }

The use of variables has the following advantages:


 When an LED is attached to a different pin, only one line of code needs to be changed.
 The sketch is easier to read and to understand, especially when several LEDs or other components
(motors…) are being used.

Task 8.1
Put variables into your program for the traffic light.
Save the program under the name „Trafficlight_with_variable“.

int i = 440;
Task 8.2
A loudspeaker is connected to port 11 of the Arduino. Copy the program
void loop() {
here to the right and describe what you observe when it is executed.
tone(11,i);
Explain what the command i = i+100; does in this program.
delay(1000);
i = i+100;
Page 12
Helpful keyboard shortcuts when writing a program*
STRG + C Copies a text you have marked
STRG + V Inserts the copied text at a new position of your cursor
STRG + Z Reverses the last action (can be repeated several times)
STRG + T Auto-formatting of a program (corrects indentation, for example)
 Note: On English-language keyboards the STRG key is labelled CTRL

How does a PC store numbers?


On a PC or microcontroller all information is stored digitally, in other words as one of two values (0 or 1).
1 byte is a group of 8 bits, or 8 places to store information coded as 0 or 1. This is the way numbers in the
binary system (consisting of 2 values) are stored. For example the number 13 in binary code is (1101)2 .

In principle a variable is a piece of memory which can be located using the variable name. In the
example above you were introduced to the kind of variable with the name int. If your program
contains the code int x; it means this:

Dear Arduino, please reserve a space in your memory that is int big and let me access the memory
using the word x.

“Int” is the abbreviation for “integer,” the English word for “whole number”. The size of the memory
reserved for int on our Arduino is 16 bits, or 2 bytes. That means there are 16 spaces with 0 or 1
available to store a whole number.

Here are some of the types of variables used in the programming language C:

Type Bits / Bytes Size Description


bool 8 Bit / 1 Byte 0 and 1 (also false and true) digital number
15 15
int 16 Bit / 2 Bytes –32 768 to 32 767 (–2 to 2 –1) whole numbers with sign
float 32 Bit / 4 Bytes exact up to two decimal places rational number
long 32 Bit / 4 Bytes -2 147 483 648 to 2 147 483 647 whole numbers with sign

Comments:
 Integer and long variables will “overflow” if the calculations exceed the size limits. For
example if int x = 32767 and you give the command to add 1 to x (i.e., x = x + 1), the “x” will
overflow and take on the value -32768
 Along with variables for numbers there are also variables in this programming language
which can remember text. This variable is called char. A char can store one letter.
 By writing unsigned before int or long will make an unsigned variable have twice as
much positive size (For example: unsigned int comprises the values 0 to 65,535)

Page 13
9.
Feedback for the user – the serial monitor

In various situations it can be helpful when the microcontroller gives you feedback on a screen (for
example, at a traffic light to read “STOP” and “GO”; for a loudspeaker to provide the name of the
song’s title). A screen is also often used to find errors in a program. If the output of feedback is
programmed at a certain spot in the program, you will know that when the text appears the program
has been successfully executed up to that point.
The Arduino can show data on the serial monitor which it has gathered and produced. Connect an
LED with a series resistor to port 13 and copy the following program:
int i=0; Defines a variable i as „integer“, i.e., as a
whole number, with the (momentary) value of
void setup() { 0.
Serial.begin(9600);
pinMode(13,OUTPUT); Sets the rate of transfer to the serial monitor . We
} will always use 9600 (bits per second).

void loop() {
i=i+1;
The value of i will increase by 1 after each
digitalWrite(13,HIGH);
cycle.
Serial.print("Anzahl:");
Serial.println(i);
The text between the quotation marks will be shown
delay(500);
on the serial monitor. .
digitalWrite(13,LOW);
delay(500);
} The value of the variables i will be given on the
Attention: The quotation serial monitor.
marks will not be shown
correctly when copying
Within the programcode.environment of the Arduino you can use the icon on the top left in
order to open the serial monitor.

Task 9.1
a) What is the difference between Serial.print(″i″); and Serial.print(i); ?
b) What is the difference between
Serial.print(„Hallo Welt“) and Serial.println(„Hallo Welt“); ?
c) Write down what the program example given above does.

Task 9.2: Write a program that creates a „face“ on the serial monitor. example:
_sss_
x x
o
|__| For quick ones: Invent your own patterns!

Page 14
10.
LC Display

On the neon signs in big cities colourful advertisements stream across big screens. With the Arduino
you can also create a lighted display, a so-called LCD (for Liquid Crystal Display).
We will use a 16x2 module, i.e., the display field consists of 16 columns and 2 rows. The Arduino
communications with the display by means of the I2 C Bus. This is two data channels thrugh which
data is exchanged using a standardized procedure (called a protocol).

Task 10.1
Connect the LCD to the Arduino (black  GND, red  5 V, white  Port 2)
Once it is connect, the name of the manufacturer and the model number of the LCD will appear.
a) Copy this program onto the Arduino. what do (0,1), (1,0) and (1,13) produce?
b) Make your name show up on the display.

Program text:

#include <Wire.h> The required libraries are called up.


#include <LiquidCrystal_I2C.h>
Gives the LC-Display the name lcd and enters its
LiquidCrystal_I2C lcd(0x27,16,2);
address 0x27.
void setup()
{ Calls up the display.
lcd.init();
lcd.backlight(); The display with the name lcd blinks briefly. The
delay(250);
background lighting is turned on with .backlight()
lcd.noBacklight();
lcd.setCursor(0,0);
and turned off with .noBacklight()
lcd.print(“Hallo Besitzer!”);
delay(1000);
lcd.setCursor(0,1); The cursor moves to the right position on the display.
lcd.print(“Wie geht es dir?”); lcd.setCursor(Zeile,Spalte);
delay(1000);
} The text is written at the current position.
void loop()
{
}

On the backside of the display there is a control dial on the I2 C module with which you can manually
adjust the brightness of the display.

Task 10.2
Use the command lcd.backlight(brightness)to adjust the brightness. Try out different levels
of brightness and show the brightness value on the display.

Page 15
11.
for loops

When many LEDs are made to light up quickly, we call this running light. In the TV series Knight Rider
the car KITT was equipped with such a light. Instead of turning LEDS on and off individually you can
use a program to this faster and easier with a for loop. In this chapter you get to know the for loop
and its applications.
The following program shows how a for loop “functions” to count up to 10 on a serial monitor.
The for look consists of three parts
int i=0; 1. Definition of the counter variables: int i=0
void setup() { Just once at the beginning of the loop the type
Serial.begin(9600); of variable is defined and the starting value of
} the counter variable.
In this example the variable i is an integer .The
void loop() { starting value is 0.
for(i; i<11; i=i+1){ 2. Status/condition: i<11
Serial.println(i); At each iteration of the loop it will be tested
delay(1000); whether the condition (i <11) is fulfilled. If yes,
} the loop will be executed, if no it will no longer
} be executed.
In this case the loop is executed as long as the
value of i is smaller than 11 ( for i = 0; 1; 2; …;
These lines of code will be repeated as
10)
long as the condition is not yet fulfilled. In
3. Change: i=i+1
order to tell the program which lines are
After each iteration the value of the counter
to be repeated in the loop, they are
variable is re-set.
enclosed in curly brackets.
In this case the value of i is increased by 1 after
each loop.

You can also define the counter variable directly in the for command: for(int i=0; i<11; i=i+1).
In that case the counter variable will be re-set to the old value after each completion of the loop.

Note that the expression i=i+1 used here is not a mathematical expression! In its place you could also
simply write i++ . Correspondingly, the expresion i = i–1 bzw. i– – can be used.

Task 11.1
a) Copy the program above to the Arduino and compare it with the alternative in which you
define the counter variable in the for loop. What differences do you notice?
b) Change the previous program in such as way that it counts down from 10 to 1.
(Hint: If you want to set a lower limit use the > symbol.)

Page 16
For a further application use the for- loop to create various sounds:

int lautsprecher = 10;


The variables with the name „lautsprecher“ are
void setup() { assigned to port 10.
}
The counter variable i is defined and given the value
void loop() { of 100.
for(int i=100; i<570; i=i+50) { After each loop the value of i is raised by 50, until i <
tone(lautsprecher,i); 570.
delay(1000);
noTone(lautsprecher);
The loudspeaker plays a tone with the pitch level of i.
}
NOTICE: At the end of the That is the current level of the counter.
}
for line there is no semi-
Task 11.2
colon !!!
a) Which tones are played by the loudspeaker until the complete „tone ladder“ begins to be
repeated? Make a note of the frequencies of the individual tones.
b) Change the for loop so that the loudspeaker plays tones downwards from a‘ (440 Hz) to a (200
Hz) in steps of 10-Hz-. Make a note of the new for loop.

void setup() {
Task 11.3 for(int i=1; i<5; i++) {
What can you observe if you connect LEDs to the ports 1 to 4 pinMode(i,OUTPUT);
}
and then transfer this program to the Arduino?
}

void loop() {
for(int i=1; i<5; i++) {
digitalWrite(i,HIGH);
delay(500);
digitalWrite(i,LOW);
delay(500);
}
}

Task 11.4 „Running light“


Use a for loop to uild and program a running light with at least 6 LEDs that runs forwards and then back. For the
LEDs use one common resistor.

Task 11.5 „Siren“


Program an American police siren (rising and falling siren sound) and change the pitch of the tone automatically
with the help of a for loop.

Task 11.6 „Running text“


a) A popular sign or symbol should move across the display from left to right. As soon as it „leaves“ the display
on the right it should appear again on the left.
b) Make your name move from left to right and back again across the display.

1.
Page 17while-Schleife
12.
while loops

In a for loop a section of the program is repeated as long as a certain condition is fulfilled. Another
way to repeat a section of the program is to use the while loop. Likewise it will be repeated only as
long as a certain condition is fulfilled.
For example we can make the Arduino roll dice with the help of the command random (see
explanation below). As soon as it rolls a 6, it should announce this and take a break.

while loop:
int a = 0;

void setup()
{ The Arduino can only check conditions
Serial.begin(9600);
mathematically by comparing the values of variables
}
with numbers. This involves the following symbols of
void loop() {
mathematical logic:
while(a!=6){ // != bedeutet ungleich < less than
a = random(1,7); <= less than or equal to
delay(500); > greater than
Serial.println(a); >= greater or equal to
} == is equal to
Serial.println("Treffer!");
!= unequal
delay(2000);
a = 0;
}
Difference between „=“ and „==“
When you write „a=1“ you are creating a assignment: The variable a is assigned the numerical value 1. However, the
expression „a==1“ is often used in condition loops. At that time it will be tested whether a has the value of 1 . The
„==“ can therefore be translated as “is it equal?“ .

Task 12.1
a) What will change in the program above if you leave out „a=0“ in the last line?
b) Copy the programm test above and let the Arduino “roll the dice” several times.
Re-start the rolls by pressing „reset“ a few times . What do you notice about the numbers?

The random command creates a whole random number. It can be written in two different ways:
random(10,20) creates a random number in the range between 10 and 19 (the largest possible number is the
second number minus 1).
random(10) creates a random number between 0 and 9.
When you executed the dice rolling program above, you may have noticed that the Arduino generated the same
“random” numbers each time, i.e. its random numbers are not really random. The Arduino calculates ist random
numbers using a formula (unkonwn to us) which begins with the same number each time. In order for us to generate
truly random numbers we must use different initial numbers (so-called seeds) at each „roll“. For this we write the
following in the line before the random command: randomSeed(analogRead(A0));

Page 18
In the following tasks use the randomSeed command to generate “real” random numbers:

Task 12.2
Roll the dice until the number 6 appears.
The program should then show how many throws occurred until 6 was rolled.

Task 12.3
Roll the dice 600 times and count how often „6“ was rolled.
Carry out this „trial“ ten times and calculate the average of the numbers rolled.
Compare your average value with the value that can be theoretically expected.

Task 12.4 „Generating board duty“


In a class of 20 students two students are to be chosen randomly for board duty. Using a while loop
write a program that produces two different numbers between 1 and 20.
Attention: „roll the dice“ twice and store the „rolled“ values in two variablea a and b.
Under normal conditions these two numbers will already be different and can be displayed.
In the case that („while“) both numbers are equal (a == b) then one of the two numbers must result in
a new throw of the dice.

Task 12.5 „Lottery“ `


Program a generator for lottery numbers that will provide you with 6 (different!) random numbers
between 1 and 49.

Comparison of for loops and while loops


Both kinds of loops consist of the sections Variable, Condition and Change:

Variable
for(Variable; Condition; Change) while(Condition
{…} {… Change …}

Page 19
13.
Dimming an LED – Pulse width modulation

The Arduino is a digital microcontroller. It can only turn on or turn off its ports, and therefore only
produce 5V (HIGH) or 0V (LOW). To change the brightness of an LED, it necessary, however, to
change the voltage. For example, 5V to have a very bright LED, 4V, to make it slightly darker, etc. But
that is not possible with digital ports!
However, there is a possibility to get voltages between 0V and 5V. It is called Pulse width modulation
(abbr.: PWM). By quickly turning on or off a port (changing between HIGH and LOW in milliseconds)
the effect is as if a potential between 0V and 5V is #.
The ports on the Arduino which are marked with (~) can produce a PWM signal. Generally PWM
ports are in the position to take on 256 different states (0 to 255). This means that the ports 1 to 13
can be used both as digital and as analog connections

Task 13.1
 Write down all the PWM ports des Arduino in your notebook.

The following command creates a PWM signal: analogWrite(pin, Wert);


The chronological sequence at the port for different Wert (Value) then looks as follows:

PWM-Wert: 25

PWM-Wert: 128

PWM-Wert: 255

Task 13.2
Copy the following program and test different PMM values between 0 and 255.
Also try out using a value larger than 255.

int led = 9; // PWM-Port 9 for the LED

void setup() { Note:


}
The PWM port does not need
void loop() {
to be defined in the setup()
analogWrite(led,PWM-Wert 1); delay(500); as OUTPUT.
analogWrite(led,PWM-Wert 2); delay(500);
}

Page 20
Analoge and digital signals
Signals (for controlling or measuring) can generally be digital or analog. Digital signals have only two
unique states, a high and a low level (observably: „on“ or „off“).
Example: digitalWrite only uses two states – „LED on“ or „LED off“
In addition, signals can be analog. These signals included many intermediate states between the lowests
and the highest level. Pure analog signals proceed continuously.
Example: analogWrite uses (256!intermediate states – LED can be dimmed at 256 levels.

Task 13.3
a) Use a for loop counter, to increase the brightness of the LED from 0 to 255.
b) Write a program that makes an LED shine continuously brighter and then darker.
Let the PWM value appear on the serial monitor.
4.

Task 13.4 „MORE Colours“


You have already gotten to know the RGB-LED. It was possible to created the colour impressions of
red, green, blue, yellow, magenta, cyan and white. By mixing the three basic colours in differing
intensities it is possible to create significantly more colours.
a) Create the colour impression of orange.
b) Create a gradual transition from red to green.

Task 13.5
 The following program contains several errors. Write the correct version in your notebook.
About this programm: The following program should control a loudspeaker (port 1) and show the
different frequencies as they are played on the monitor. At the same time an LED is connected to port
13 which will blink whenever the frequency of the loudspeaker changes.
i = 100;
void setup() {
SerialBegin(6900);
pinMode(13,Output)
}
void loop {
for(i < 1000, i+50);
{
tone(1,i,1000);
delay(500);
Serial.print(″i″);
digitalWrite(13;HIGH);
digitalWrite(13,LOW);
}
}
Comprehension check:
 How long is each tone played?
 How many times in total does the LED blink?

Page 21
14.
Toggle switches

It is common to want to start or end a program by toggling a switch. A good


solution for this is the use of a toggle switch. When opening the switch the left
contact is connected with the centre contract. By pressing the switch, the left
contact is connected with the right contact. Using the ports of the Arduino
pressing a keystroke creates a signal and the Arduino reacts to this signal.

On the following breadboard an LED is to be turned off via keystroke.

Pin 5V 0V

int signal;

void setup()
{
pinMode(2,OUTPUT);
pinMode(3,INPUT);
}

void loop()
{
signal = digitalRead(3);
if (signal==1){
digitalWrite(2,HIGH);
}
else {
digitalWrite(2,LOW);
}
}

Task 14.1
Construct the circuit shown above and copy the program code. Let the signal be shown on the serial
monitor.

Task 14.2
Expand the circuit above by one gree LED and re-write the program so that the red LED lights up when
the switch is pressed and the green LED lights up when it is not.

Task 14.3
Construct a traffic light for cars and predestrians. To start, the signal for cars is green. When a switch
is pressed the signal for cards changes to red and the pedestrial light becomes green.

Page 22
15. Appendix A
Basics of an electrical power circuit

When in a cell phone, a laptop, a calculator or an electric tooth brush – every kind of big or small
device that eases our daily life contains an electric power circuit. Since you will be faced with many
power circuits when working with your Arduino, here is a summary of the important facts:

There are four physical parameters that are relevant to power circuits: voltage, current (strength),
resistance and electrical potential. The power circuit can be compared to the flow of water.

a) Voltage
Voltage can be compared with the drop in height of a waterfall. Without a difference in height, no
water would flow. Without electrical voltage no electrical current can flow. Voltage moves between
two points (but it does not flow). It can be measured “by tapping.” A voltmeter must always be
connected in parallel. No current flows through the voltmeter itself.
Voltage U is measured by the unit called volt (V).

b) Current strength
Electric current can be compared with the flow of water in a
waterfall. Without a difference in height (voltage), no water can flow.
Electric current can only flow when there is a closed power circuit
connecting plus (+) and minus (-). A voltmeter must be connected to the
circuit. Therefore the voltmeter is always part of the circuit. Since current
flows, it can only be measured when it flows through the measuring device.
Current is measured by the unit called ampere (A).

c) Resistance
In the example of a waterfall resistance can be compared with more or less
stones on the waterbed. The flow of water is “slowed down” by the stones in the water. The
waterbed counters the flow of water with resistance. A metallic conductor (copper, iron, etc.) also
puts up resistance against the flow of electrical current, which has to be overcome by the electrical
current Resistance (R) is measured by the unit called ohm ((),

d) Potential
The electrical potential is a kind of “electrical pressure” on a cable. As in a water pipe there can be
higher or lower pressure present. If one connects a pipe with high pressure to an area where low
pressure exists, the water flows. The same for current: Only when there is a difference in potential
does current flow. The potential difference is the voltage. When you ground an electric connector,
this means that you give it the electrical potential of 0V.
Beware: Because both potential and potential difference (=voltage) are measured by the unit volt, the
terms voltage and potential are often mixed up!!!

Relationship between voltage, current strength and resistance (Ohm’s Law):

Page 23
16. Appendix B
Protective resistors for LEDs

The LEDs which we are using are usually operated with a power of approx. 20 mA. This power flows when there
is a voltage of approx. 2 V (so-called forward voltage). If we were to connect the LED directly to the 5 V of the
Arduino, current exceeding 20 mA would flow. Therefore we need to reduce the current from 5 V to 2 V. That is
why we add protective resistors to LEDs connected in series to the circuit. It is sized so as to reduce the power
supply from 5 V to 2 V, i.e., by 3 V (the so-called “voltage drop”). In addition we want to allow the maximum
current of 20 mA to flow through the LED. Because the LEDs and the resistors are connected in series, 20mA
will also flow through the resistance.
The ideal series resistor is calculated with the help of Ohm’s law:

From it follows that 


This means: When a  resistor is connected in series to the LED, it will have optimal power.

The general formula for calculating the series resistor of an LED is:

After you determine the suitable size of the protective resistor, you still need to search for the suitable
resistance using the colour code of the resistors. These usually consist of four colour rings. In order to show
where to begin reading them, the last ring is spaced at a somewhat larger distance from the others.

red green red gold

Colour 1st Ring 2nd Ring 3rd Ring 4th Ring


black - 0 - -

brown 1 1 0  1%

red 2 2 00  2%
orange 3 3 000 -
yellow 4 4 0.000 -
green 5 5 00.000  0,5%
blue 6 6 000.000 -
purple 7 7 - -
gray 8 8 - -
white 9 9 - -
gold - -  0,1  5%
silver - -  0,01  10%

Page 24
The first two rings each indicate a digit. Each ring stands for a digit of the number matching the
colour code. In the resistor shown above: The ring in front of the larger space indicates how many
zeros need to be added. For this resistor (red ring = 00) there need to be two zeros added; therefore
the value of the resistance for  = 2,5 .

The ring on the far right (usually silver or gold) indicates how exact the specification of the resistance
is. In this case (gold =  0,5%) the actual value of our resistance can lay between and
. The exact resistance value can be measured by, for example, a multimeter.

Page 25
17. Appendix C
Addition of a library

Libraries expand the Arduino software’s functions with additional commands. There are libraries for
LCDs, for servomechanisms (servos) and many other components. If you want to use them, they
must be inserted into the program. The Arduino software package has many different libraries
already “on board.” In the main menu the command Add library can be found under the heading
Sketc. When you select a library you want to add, the command include will apprear in the program
as follows:
#include <IRremote.h> (Library of commands for using a remote control device)

You can also add a new library that you have downloaded, for example from the Internet. The folder
for the library must be unpacked and copied into the library folder of the Arduino folder.

When the Arduino software is opened, the new library will be included as follows:
Sketch  Import library  Add Library  click once on selected folder  Open

Page 26
18. Appendix D
Troubleshooting

Troubleshooting

Start
Start

What
What dosn't
dosn't
Component work?
work? Programm

Was
Was
Wasprogram
program
program
Check Hardware
Yes transferred?
transferred?
transferred? No

Programmüberprüfung
Check Program Find Error

Finish

Check Hardware

Start

Which component
LED is used? LCD-Display

LED correctly mounted Loudspeaker port used in All libraries added


(long leg at + pole) program code

All LEDs in setup defined Adjust brightness switch


as Output

Finish

Page 27
Check Program

Start

Are for, while, or if


Yes used? No
No

Curly brackets correctly Semi-colons


Semi-colons after
after all
all
used; no semi-colons) sommands
sommands

Semi-colon present after Upper and lower case


all commands? correctly ued?

Upper and lower case Close every curly brackets


correct in commands
(notice color in text)

Correct variables and


conditions set?

Finish

Page 28
Error message “not in sync”

Sometimes, while transferring a program to the Arduino, the error message “not in sync” appears (see below). This
indicates that the transfer did not work. Usually this is due to the fact that the COM port shown at the bottom right corner
of the screen does not match the COM port on the PC.

Abbildung 1

Solution:
1) Unplug and re-connect the USB cable to the Arduino. Sometimes that is enough!
But if the error message appears again:
2) Close the program environment (first save your coding)
3) Unplug the USB cable from the computer
4) Re-start the program environment (arduino.exe)
5) Only after the program has finished loading, attach the USB cable to the computer again.
6) If necessary, in the menu bar, go to TOOLS  Serial Port  Select current port (check under device manager) as
shown below. Note: You can open the device manager with the key-combination (Windows + Pause)

Abbildung 2

Page 29

You might also like