elektronika -osnove

35
1 - lushprojects.com Electronics for Artists Iain Sharp lushprojects.com Revision 4 - © Iain Sharp 2010 These course notes are licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License .

Upload: predrag152

Post on 14-Apr-2015

68 views

Category:

Documents


11 download

DESCRIPTION

Knjizica koja objasnjava osnovne elektronske elemente na koje elektronicar pocetnik nailazi na pocetku rada na polju elektrotehnike-elektronike

TRANSCRIPT

Page 1: Elektronika -osnove

1 - lushprojects.com

Electronics for Artists

Iain Sharplushprojects.com

Revision 4 - © Iain Sharp 2010

These course notes are licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.

Page 2: Elektronika -osnove

2 - lushprojects.com

Part 1: Electronics

Page 3: Elektronika -osnove

3 - lushprojects.com

Batteries and CircuitsTwo things are needed to make a an electricity do something useful:1) a source of electrical potential to provide the power,2) a complete circuit round which electricity can flow.

We are going to use a battery to provide the electrical potential. A chemical reaction inside the battery works like a pump to push electricity. The amount of “push” is the voltage – measured in Volts.

The circuit for the electricity to flow round needs to be built of electrical conductors and must provide a loop from the positive to the negative terminal of the battery. Metals are by far the most common electrical conductors, but there are also all kinds of other materials that can be used to create special behaviours.

When a circuit is connected a current will flow round the circuit. The current is like the amount of water flowing through a pipe. The current is measured in Amps, or more usually for electronics a 1/1,000th of an Amp or milliamp (mA).

To understand electronic circuits it is normal to draw a circuit diagram or schematic. This diagram is like the London Underground map – it shows how things connect in a way that allows you to see the underlying pattern without the complexity of how things are physically laid out in the real world.

Schematic+

BatteryBulb-

Groups in columns are connected

Rows along top and bottom are connected

Build on Breadboard

ME

GA

PO

WE

R9

Volt

Bulb

Red is positiveBlack is negative

No connection across the middle gap

Count Alessandro Volta1745 – 1827Developed the first battery

Don't connect components along the columns – this just connects their leads directly.

MISTAKE

Page 4: Elektronika -osnove

4 - lushprojects.com

Experiments with Series and Parallel Circuits

+

Battery

-

Bulbs in SeriesLike Christmas tree lights

ME

GA

PO

WE

R9

Volt

Bulb

Apply ends of wire to short-circuit bulb here

What happens if you short-circuit one bulb with a loop of wire?

+

Battery

-

Bulbs in ParallelLike bulbs in your house

Joints on schematics are marked with dots M

EG

AP

OW

ER

9 Vo

ltBulb

Voltage is split evenly between the bulbs and both glow dimly. Less current flows than with one bulb.

Both bulbs get the full voltage of the battery. Twice the current flows when compared to having one bulb.

Lifting one leg of a bulb out of the breadboard breaks the circuit through that bulb and allows them to be switched on and off individually. This is the same job a light-switch does.

André-Marie Ampère 20 January 1775 – 10 June 1836

Discovered many properties of electromagnetism

Bulb

Bulb

Page 5: Elektronika -osnove

5 - lushprojects.com

ResistorsResistors limit the flow of electricity through part of the circuit. This can be used to control timing circuits, divide voltages in to smaller portions or protect devices that are sensitive to too much current.

Resistance is measured in Ohms (Ω),kilohms (1,000Ω=1kΩ) or Megohms (1,000,000Ω =1MΩ)

Resistors can go in the circuit either way round. The value is marked on the device with a colour code (see right), or it can be measured with almost any multimeter.

A shorthand is often used to write the value of a resistor. For example:“100R”=100Ω“10k”=10kΩ“4k7”=4.7kΩ

Some resistors used in these experiments:100R – Brown, Black, Brown220R – Red, Red, Brown1k – Brown, Black, Red10k – Brown, Black, Orange100k – Brown, Black, Yellow

Georg Simon Ohm(16 March 1789 – 6 July 1854)

Discovered the relationship between voltage and current in electrical circuits “Ohm's Law”.

Time for:A resistor game!

Only for five band resistors!Skip for four band resistors

Page 6: Elektronika -osnove

6 - lushprojects.com

Light Emitting Diode (LED)LEDs are solid state devices that emit light when electricity passes through them. They are directional and need to go in the circuit the right way round.

Once a certain “on” threshold voltage is reached (about 2V for a red LED) the current through an LED rises very quickly with the voltage. In most applications a resistor is needed to protect the LED from being overloaded due to this effect.

Captain HenryJoseph Round

(2 June 1881 –17 August 1966) First to observe light emitted

by a solid state diode

+

-

Experiments with LEDs and Resistors

Resistor R

LED

Try using different values of R in this circuit:100k, 10k, 1k, 220R

What do you notice about the LED? What do you notice about the 220R resistor when it is in the circuit?

ME

GA

PO

WE

R9

Volt

LED

Flat &short-lead

R

+

-

220R

LED

WireProbes

Try touching the ends of the wire probes on to different objects:- your skin- fresh water- salt water- a thick line drawn with a soft pencil- a (non light-emitting) diode (try this with the diode both ways round) M

EG

AP

OW

ER

9 Vo

ltLED

Flat &short-lead

220R

Probes

+

+

Page 7: Elektronika -osnove

7 - lushprojects.com

TransistorsThe solid state transistor is the single component that has driven the electronics revolution. Initially they were very hard to manufacture and regarded expensive specialized parts. Improved mass production techniques gradually lead to transistors becoming cheaply and easily available. Later on a new wave on innovation was created when it was realised that multiple transistors could be manufactured on a single wafer of silicon – leading to the integrated circuit, microprocessors, microcontrollers and all the advanced toolkit available to modern electronic engineers.

We are going to focus on one type of transistor – the NPN bipolar transistor. A transistor has three terminals and acts as an amplifier. For an NPN transistor the terminals are called the “collector”, “base” and “emitter”. A small current flowing in to the base and out of the emitter controls a much larger current flowing from the collector to the emitter. Think of the current at the base as working to control a tap that varies the flow through the collector. If no current flows in to the base then no current will flow through the collector either.

The base voltage varies between 0V when the transistor is off and about 0.7V when the transistor is on. Like an LED the input to the base normally needs to be protected by a resistor to stop the base being overloaded.

Using transistors we can build many types of circuits including amplifiers, logic circuits, oscillators, filters and power controllers.

The maximum collector current ranges from a few hundred mA to several Amps depending on the transistor. The gain of the transistor is the multiple of the base current the can flow through the collector. This is normally in the range 50-400 and is sometimes written as h

FE. William Bradford Shockley

(February 13, 1910 – August 12, 1989)

Leader of the team at Bell Labs that developed the junction transistor. Nobel prize winner. Also described

as “the notorious eugenicist and scientific racist”..

NPN Transistor

Collector

Emitter

BaseBig current canflow here

Small control current

Transistor Packages Transistor type 2N3704 pinout

Page 8: Elektronika -osnove

8 - lushprojects.com

ME

GA

PO

WE

R9

Volt

Experiments with a transistor

+

-

220R10k

2N3704

LED

LED

10kB C E

220RFlat &short-lead

Connect the circuit up as shown and then try applying the probes to various items. Notice the brightness of the two LEDs. You should find the LED in the collector circuit is much brighter than that in the base.

Items to try:- Probes open (no connection). Transistor is off and neither LED is lit.- Probes touching each other. Transistor is fully on. The LED in the collector circuit glows brightly.- Probes along a pencil track- Probes on your skin

+

Collector

Base

Emitter

Page 9: Elektronika -osnove

9 - lushprojects.com

CapacitorsCapacitors store and release small amounts of electrical charge. In electronic circuits they are used to control the timing of circuits, “smooth out” electrical waveforms and to separate DC and AC components of a signal.

Capacitance is measured in Farads (F), but one Farad is much too big to be practical. Useful units are:Micro Farads (μF or uF) = 1/1,000,000th of a FaradNano Farads (nF) = 1/1,000,000,000th of a FaradPico Farads (pF) = 1/1,000,000,000,000th of a Farad

Capacitors less than 1uF can normally go in a circuit either way round. Larger capacitors normally have a polarity (normally the negative end is marked) and have to go in a circuit the right way round.

Capacitors come in a many different types that are designed for different applications. For this circuit the type used isn't important so we've used the cheap and cheerful options. The small capacitors are “ceramic discs” and the large capacitors are “electrolytics”.

Several labelling schemes are in common use for capacitors. The ceramic discs used in these circuits are labelled with three digit codes. The first two digits are the value and the third digits is the number of zeros making up the capacitance in pF.

So:10nF = 10,000 pF = “103” 100nF = 100,000pF = “104”

+ve

-ve

Electrolytic polarity

Michael Faraday (22 September 1791 – 25 August 1867)

Discovered the fundamental relationship between electricity and magnetism (amongst many things).

-ve+ve

Small indent

Page 10: Elektronika -osnove

10 - lushprojects.com

ME

GA

PO

WE

R9

Volt

Experiments with a capacitor

+

-

10k

Flat &short-lead

100uF +

10k

100uF +

Build the circuit like this with the battery disconnected.Connect the battery and watch the LED.

Remove the capacitor and put in in this circuitwithout shorting out the legs.

LED

100u

10k

LED

10k

100u

+

+Lift and move

In the first circuit the capacitor charges up with current from the battery. The value of the resistor and the capacitor determine how quickly the charge builds up. As the capacitor charges it develops its own voltage that pushes against the battery. This reduces the flow of current and the LED goes out.

When the capacitor is moved in to the second circuit it discharges through the LED lighting it up.

+

Page 11: Elektronika -osnove

11 - lushprojects.com

Capacitors and transistorsBuilding timing circuits that combine capacitors with transistors offer a number of advantages over just using capacitors on their own:- the amplifying effect of the transistor can generate a clean “on/off” effect from the gently changing voltage on the capacitor- the transistor can isolate the capacitor from other effects allowing signals to be controlled without changing the behaviour of the capacitor timing circuit.

-

220R10k

2N3704

100uF+

220R

Flying lead that can connect to the negative line

ME

GA

PO

WE

R9

Volt

LED

220R

220R

Flat &short-lead

B C E

10k

100u

Build the circuit and then try connecting the flying lead to the negative line. The LED should go out momentarily and then relight. Disconnect then reconnect the flying lead to show this is repeatable.

+

Page 12: Elektronika -osnove

12 - lushprojects.com

Times twoWith two copies of the previous circuit you can manually make an interesting effect.

Build two versions and then cross over the flying leads. Hold the end that is now on the left in your left hand and the other end in your right hand. Connect one lead (say the one in your right hand) to the negative line. The left hand light will go out. Now follow the rules:- if the right hand light is on connect the right hand lead to ground. If it is off then disconnect it.- if the left hand light is on connect the left hand lead to ground. If it is off then disconnect it.

This manually makes the two LEDs flash alternately.

-

220R

10k

100uF+

220R

ME

GA

PO

WE

R9

Volt

LED

220R

220R

B C E10k

Build the circuit and then try connecting the flying lead to the negative line. The LED should go out momentarily and then relight. Disconnect then reconnect the flying lead to show this is repeatable.

220R

10k

100uF

220R

LED220R

220R

B C E

10k

100u

100u

+

Flat &short-leadFlat &

short-lead

+

+ +

Page 13: Elektronika -osnove

13 - lushprojects.com

MultivibratorWouldn't it be useful if you could replace the manual fiddling with leads in the previous circuit with something automatic? Well, guess what – with a few simple changes you can.

In the circuit below we've removed two of the 220R resistors and instead cross-wired what were the flying leads in to the collectors of the opposite transistor. The two halves of the circuit now work automatically against each other. When the circuit is powered up the lights will flash.

This circuit is known as a “multivibrator” and is the basis of a whole family of circuit designs. It also nicely illustrates the two sides to electronics:1) understanding individual components and their function2) Understanding how those components are used to create common building blocks.

-

220R

10k

100uF+

ME

GA

PO

WE

R9

Volt

LED

220R

B C E10k

For more experiments:1) Try changing the values of one or both of the 10k resistors. Suggested alternatives are 22k or 4k7.2) Try changing the values of one or both of the 100uF capacitors. Try 10uF instead.

Observe the result of these changes.

10k

100uF

220R

LED

220R

B C E

10k

100u

100u

+

Lines that cross without dots don't connect

Flat &short-lead

Flat &short-lead

+ +

+

Page 14: Elektronika -osnove

14 - lushprojects.com

Basic organBy swapping the capacitors for much smaller values we can change the frequency of oscillation of the circuit to make it much higher – in the range your ear can hear. By connecting a speaker to the output instead of an LED this creates a basic organ. Play the organ by touching the wire probes on a pencil line.

Note about capacitor marking10nF = 10,000pF = Normally written as “103” on capacitor

220R

10k

10nF

ME

GA

PO

WE

R9

Volt

1k

B C E

10k

1k

220R

B C E

10k

10k

10nF

10nF

Speaker

10nF

+

Page 15: Elektronika -osnove

15 - lushprojects.com

Integrated CircuitsIntegrated circuits (“ICs”) are single packages that contain complete circuits consisting of many components. Today almost all ICs are silicon chips. Intel claims to have produced single ICs with 2,000,000,000 transistors.

For the last experiment we are going to use a “4017” decade counter. When this is driven from the output of a multivibrator it can be used to light LEDs in sequence producing a chain light effect.

Much of modern electronics is based on using ICs rather than discreet components. The skill lies in finding the right IC and understanding how to use it and its limitations. For example it's unusual to build multivibrators like the ones in these experiments in most designs – instead a timer IC like the famous “555” might be used.

Note about IC NumberingNumbering of ICs a pretty hit and miss. The “4017” is just the base name for the device. The full number will have other numbers or letters attached depending on which company makes it, what type of package it's put in and so on. You will often find lots of variants of the same IC with similar numbers. The IC in my parts kit says it's an “CD4017BE”.

Gordon Earle Moore(3 January 1929-)

Observed that the capacity of economically feasible ICs doubles approximately every 2 years.

Page 16: Elektronika -osnove

16 - lushprojects.com

Chain Light Schematic

- 1k10k

10uF+

10k

10uF

1k

+

4017 220R

220R

220R

Clock14

13

ENABLE

RESET

VDD

VSS

16

8

15

7

3

2

4

OP 0

OP 1

OP 2

OP 3

Page 17: Elektronika -osnove

17 - lushprojects.com

Chain Light Layout

-

ME

GA

PO

WE

R9

Volt

1k

B C E

10k

1k

B C E

10k

10u

10u

220R

LED

220R

220R

LEDLED

4017

Flat &short-lead

+

++

Page 18: Elektronika -osnove

18 - lushprojects.com

Part 2: Arduino

Page 19: Elektronika -osnove

19 - lushprojects.com

What is an Arduino?The Arduino is a family of tiny computers that are designed to be used for controlling interactive electronic installations. The Arduino computers are comparable in power to early home microcomputers from the 80s like the BBC Micro and ZX-Spectrum.

The Arduino has several important advantages:It is designed as a complete system which includes

programming tools and hardwareThe Arduino can be connected to any PC or Mac with a

USB cable to download programsThe open-source hardware design encourages innovationStrong community with a lot of documentation and

examples availableArduino “shields” make it easy to connect other types of

electronicsComplete Arduino family of hardware for different

applications

The Arduino home page with lots of useful information is at:arduino.cc

Arduino programming

1. Write program on your computer

2. Send (“Upload”) the program to Arduino

USB cable

3. Arduino runs program3a. Independently of host computer

Connect a suitable power source and the Arduino can run on its own

3b. With a host computer

A computer can power the Arduino and exchange information over USB

Page 20: Elektronika -osnove

20 - lushprojects.com

Arduino Duemilanove Anatomy

14 Digital pins labelled 0 to 13Digital = “High” or “Low”; Input or OutputHigh is about 5 Volts; Low is about 0 VoltsTry and avoid using pins 0 and 1 as they are also used with programming the Arduino

6 Analog Inputs labelled 0 to 5Can be used to measure electrical voltages between 0 Volts and 5 Volts. Used to measure properties of the real world when used with the right sensors

Power OutputsProvides limited power to external circuits.

USB ConnectorConnects to host computer

Power ConnectorProvides power to circuit foroperation without a host computer. Recommended range is 7 to 12 volts. A voltage regulator on the board will generate a 5V supply.

ATMEL MicrocontrollerThe “brains” of the Arduino

programming LEDsFlash to show programming operation

Power LEDShows when Arduino is on

Reset buttonPress to restart the program. Reset happens automatically on power-on or when programming is completed.

Pin 13 LEDShows the state (high or low) of pin 13. Lights up with the pin is high.Labelled “L”

Page 21: Elektronika -osnove

21 - lushprojects.com

An Arduino for (almost) every situation

The main lineAll have same board connections and support one of two microcontrollers – the ATMEGA168 or ATMEGA328. The 328 has twice as much memory.Arduino Diecimila Freeduino 1.16

=

Arduino DuemilanoveSimplified power supply (automatic selection of USB or external power)

Arduino UnoModernized USB interface

Some black sheepArduino Mega 2560

More powerful processor and more connectors.

Arduino Lilypad

Designed for incorporation in to clothes and textiles. Needs an external programmer

Arduino Nano

Compact version

… and many many more.

All share the same concepts, programming techniques and development tools

Arduino Skeleton

Made without a circuit board! Not commercially available.

http://www.geocities.jp/arduino_diecimila/obaka/project-7/index_en.html

Page 22: Elektronika -osnove

22 - lushprojects.com

Getting Ready to Program the ArduinoIn order to program the Arduino you need the right software installed on your host computer. You also need to configure various options

The Arduino web site does a good job of documenting this for various systems and is kept up to date, so just go here and follow the instructions for your type of computer:http://arduino.cc/en/Guide/HomePage

About Arduino programmingThe Arduino program tells the Arduino what to do. The program is written in a programming language called Processing. Processing is based on another language called “C”.

A program for the Arduino is called a “Sketch”. Sketches are written in the Arduino programming environment which also provides the ability to upload the sketch in to the Arduino and communicate with the Arduino when it is running the program.

The Sketch consists of a number of commands in sequence. Normally the commands are executed one after another in the order they appear in the Sketch. However there are also special commands that can change the order of execution.

Arduino programming Environment

Menus

Control Buttons

Sketch Editor

Program Notification AreaUsed to show messages from the program

Tabs to select Sketch

Status BarShows the result of the last action

Page 23: Elektronika -osnove

23 - lushprojects.com

An Arduino Blink Program1) Connect your Arduino to the host computer using a USB lead.2) Run the Arduino software on your computer.3) From the File menu choose Examples → 1.Basics → Blink. The simple Blink sketch should load.4) Click the Verify button to check the Sketch is OK. In the text area at the bottom of the screen a message like “Binary sketch size: 1008 bytes (of a 14336 byte maximum)” should appear once the verification is complete.

Verify Button

5) Click the Upload button to upload the sketch on to the Arduino. During the upload the LEDs labelled “Rx and Tx” will flash to show the transmission of data. Once the sketch is uploaded you will get a message “Done Uploading” and the sketch will start to run. The pin 13 LED should flash.

Upload Button

6) Try changing the values in brackets in the “delay” function call in the “loop” function. Repeat steps 4 and 5 and see if you notice a difference.

/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */

void setup() // initialize the digital pin as an output: pinMode(13, OUTPUT);

void loop() digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(13, LOW); // set the LED off delay(1000); // wait for a second

Comment: Everything between a /* and a */ is a comment to help the reader understand the sketch. It is ignored by the Arduino

Comment: Everything on a line after a “//” is also a comment

Setup function: Every sketch must have a setup function. This is run when the Arduino is reset to prepare for the rest of the program

Loop function: Every sketch must have a loop function. After the setup the Arduino repeatedly performs the actions in the loop function

Function call: This is a piece of program that triggers a function to perform a required action. In this case the function tells the Arduino to use digital pin 13 as an output.

Page 24: Elektronika -osnove

24 - lushprojects.com

Using FunctionsA function is a self-contained piece of computer program that is collected in to a wrapper to make it easy for a programmer to use. Processing contains many already defined functions you can use in your programs. When you want to use a function you write a function call in to the program. Here is an example function call from the Blink Program.

pinMode( 13 , OUTPUT );Name of the function: shows which function is being called. In Processing, the names are case sensitive (small and big letters must be correct). The name can't contain spaces.

Parameters of the function: Data values that are needed by the function are called “parameters”. They appear in brackets after the name. Different values are separated by commas. The number and types of data values is specified in the function definition.

In this case the first parameter is the pin number being set. The second parameter shows whether this pin is an INPUT or an OUTPUT.

If there are no parameters you still must include an empty pair of brackets.

Delimiter: In Processing each statement in the language must end with a semi-colon. This is called a delimiter. Missing semi-colons (or semi-colons in the wrong place) are a common source of problems.

Spaces allowed here

When the program reaches the function call it goes and performs the tasks defined by the function. Once the function as finished the program resumes just after the function call. It is possible for one function to call another function in a nested structure.

Built-In FunctionsWe have already seen three built-in functions: PinMode(), digitalWrite() and delay(). There are many others. You can explore them through the example sketches http://arduino.cc/en/Tutorial/HomePageor athttp://arduino.cc/en/Reference/HomePage

Page 25: Elektronika -osnove

25 - lushprojects.com

Defining FunctionsAs well as using pre-prepared functions, you can also define your own. You must define a “setup()” and “loop()” function.

A weakness of processing is that the function definitions are a little complicated when you first meet them. This is due to the decision to build Processing on top of “C”. If you don't understand the detail, just treat this as a piece of magic that you can copy from examples as you need to.

Here is an example function definition from the “Blink” program.

void setup() pinMode(13, OUTPUT);

Name of the function: choose a name without spaces which is meaningful to you and doesn't overlap with any other function names. The names “setup” and “loop” have special meanings

Return types: Functions can return a value once they are completed. Simple functions don't do this, and to tell the computer you don't want to return a value you must put the word “void” in front of the function definition.

Function parameters: We have seen how you can use parameters when you call functions. When a function is defined the parameter definitions go here. If there are no parameters you must include a pair of empty brackets to show that the parameter list is empty.

Curly brackets around the function body: A pair of curly brackets goes round the “body” of the function. The body contains the instructions for what to do when the function is called.

Statements: The function body is made up of one or more statements that do the work of the function. Another function call is an example of a statement. Each statement is separated by a semi-colon.

Page 26: Elektronika -osnove

26 - lushprojects.com

Blink Program with a Variable1) Go back to the “Blink” sketch and edit it on the screen so it looks like the example on the right (changes are shown in bold).

2) Verify the sketch using the verify button.

3) Upload the sketch to the Arduino and check that it works.

/* Blink example with variable */

int ledPin;void setup() ledPin=13; // initialize the digital pin as an output: pinMode(ledPin, OUTPUT);

void loop() digitalWrite(ledPin, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(ledPin, LOW); // set the LED off delay(1000); // wait for a second

Variable declaration: This line in the sketch creates a new variable called “ledPin”. A variable is a labelled box which is used to contain data used in the program. The data can be read or changed during the program.

In this case ledPin will contain integer values. We use the word “int” to tell the computer we want ledPin to be an integer.

A variable declared outside any function can be seen by all functions in a sketch.

Variable assignment: This statement puts a value (13) in to the variable ledPin.

Variable use: We can now use the variable name to mean the contents instead of actually writing 13.

Page 27: Elektronika -osnove

27 - lushprojects.com

100R

10k

Wire probes

100R

LED Chain Circuit1) Construct the circuit with the Arduino and breadboard as shown on the right. We will use variations of this circuit for the next few experiments.2) In the sketch used in the previous experiment change the line “ledPin=13;” to “ledPin=2;”. Upload this sketch and you should see the left-hand LED flash.

3) Using the menu option File → Open... open the sketch “chain.pde”. Upload this sketch to the Arduino. You should see the lights move in a chain pattern.4) Try modifying the Chain sketch to get other patterns – eg reversing the direction of the chain, or having the LEDs light in pairs.

5) Using the menu option File → Open... open the sketch “digitalInput.pde”. Upload this sketch to the Arduino.6) With the digital input sketch running try touching the ends of the wire probes together. What happens? In a more permanent circuit the probes could be replaced by a switch or a button.

The digitalInput sketch uses a new capability – the possibility to treat an Arduino pin as an input. It also uses an “if” statement (see next slide) to change the behaviour of the Arduino based on the input.

Let's look at what is happening electrically. When the probes are disconnected the 10k resistor “pulls” the voltage at the input low. When the probes connect the input is connected directly to the 5V supply from the Arduino and the input goes high. This is a very common configuration. The 10k resistor is called a “pull down resistor”.

100R 100R 100R 10k(Brown-BlackOrange)

Arduino

Pin 2 Pin 3 Pin 4 Pin 5 Gnd Pin 6

5V

Page 28: Elektronika -osnove

28 - lushprojects.com

New Program Elements in digitalInput sketch

pinMode(inputPin, INPUT);

inputValue=digitalRead(inputPin);

if (inputValue==LOW) ... things to do... else ... things to do....

Set Pin Mode: Done in the setup function. This says that we want an input on the inputPin.

Reading the input: This is done every time the sketch goes round the main loop. The sketch looks at the value of the input pin and stores either HIGH or LOW in the variable called “inputValue”. Think of the variable as a labelled box to store values. Like other variables the type of “inputValue” was declared at the start of the program

IF statement: This is used if you want to make the sketch do different things based on the environment or the results of a past activity.IF statement: This is used if you want to make the sketch do different things based on the environment or the results of a past activity.

Condition: After the word “if” you have brackets that contain the condition that is being tested. The two equals signs (“==”) means “has the value of” or “is the same as”. Here we see if the variable inputValue contains the value “LOW”.Other possible conditions include “!=” for “not equal to”, “>” for “greater than” and “<” for “less than”.

True actions: After the condition you have a list of statements surrounded by curly brackets. These are what the sketch does if the condition being tested turns out to be true.

False actions: After the true actions you may have the world “else” and then another list of actions in surrounded by curly brackets. These are what the sketch does if the condition being tested is false.

Page 29: Elektronika -osnove

29 - lushprojects.com

Making Mistakes (and fixing them)Mistakes – we all make them. In computer programming there are two different types of mistake you can make in the software. A “syntax error” means you have written something in the program that the computer can't understand. If your sketch contains syntax errors it can't be uploaded to the Arduino.

A “semantic error” means your sketch is understandable but you discover it doesn't do what you meant it to do. This normally means you have made a logical mistake in designing your sketch.

Syntax ErrorsSyntax errors will be detected when you either verify a sketch or try and upload it to the Arduino. When a syntax error is detected the status bar will turn from blue to red and red error messages will appear in the program notification area. The area where the computer detected the mistake will be highlighted in the editor.

Unfortunately Processing doesn't handle syntax errors very well. Its messages can be very hard to understand (even for experts) and it doesn't always guess right where the error occurred

Here are some things to check to try and fix any errors:- Mistyping of names (spelling or case of letters)- Missing semicolons after statements- Unpaired round brackets or curly brackets- Spaces in the middle of names

To minimise problems with syntax errors I suggest you start by evolving the examples and make small steps towards what you want, frequently verifying so that mistakes get caught early.

Semantic ErrorsSemantic errors are normally called “bugs”. They could be anything from a program that does nothing to a program that works 99% of the time but occasionally fails unexpectedly.

The process of finding and fixing semantic errors is often a piece of detective work. Normally you should test your sketches thoroughly to make sure that they behave the way you want them to under all circumstances.

If a sketch doesn't do what you expect then try and work out why it follows the behaviour it's showing. Pretend you are the Arduino and “dry run” the instructions in your head. Think about where in your sketch the problem may be and what circumstances trigger the problem. Try and narrow down the range of possible points where the problem originates.

Page 30: Elektronika -osnove

30 - lushprojects.com

Making A NoiseLet's move beyond blinking LEDs. In this experiment we will add a speaker to the Arduino and start to make some noise. This also provides a useful demonstration of how to connect larger loads to the Arduino.

1) Add the extra elements shown to the existing circuit.2) Open the sketch “digitalInputwithtone” and upload it to the Arduino.3) When you touch the wire probes together you should now get a tone from the speaker.4) Examine the sketch and see the new elements that create the tone. Try changing the tone behaviour.

How the electronics works

The Arduino pins have a very limited capacity to drive electrical current. One LED is OK, but much more is dodgy. We can use a transistor to boost the output to drive more demanding loads – in this case a speaker.

In the first transistor experiment we showed how a small current on the base of the transistor could drive a much bigger current through the collector. We use exactly this idea here. The transistor is controlled from the Arduino by connecting the base to an output pin via a resistor (1k in this example). The resistor limits the current taken from the Arduino.

Even with a transistor, connecting 5V directly to the speaker is too much. The 100R resistor in the collector limits current through the speaker.

NB: Many examples on the web don't put a resistor in the base. Without the base resistor the circuit is poorly designed any may damage the Arduino.

100R

1k

1k

Arduino

Gnd Pin 7

5V

Note: Circuit Diagram only shows the speaker connection

100R

ecb

NOTE:Flat face of transistor is facing the viewer

2N3704

Page 31: Elektronika -osnove

31 - lushprojects.com

Driving LoadsWe saw in the last experiment how a transistor can be used to let the Arduino drive an electrical load like a speaker which is too big for the Arduino to drive on its own (for reference the maximum current load per pin is 40mA). The transistor configuration is a general technique that can be used to drive most low-voltage electrical loads.

For smaller loads (say up to 250mA) this general circuit can be used.

1k

Arduino

Gnd Pin

5V

Load

For larger loads, or loads that need a different power supply voltage to the Arduino's 5V the following general circuit can be used. You may need to check the suitability of the transistor. The 2N3704 we are using in the experiments has a maximum capacity of 500mA. To test the current taken by a load connect it to a power supply with a current meter in the path.

1k

Arduino

Gnd Pin

5V

LoadPowerSupplyFor Load(About15V max)

Some useful loadsYou can use the general circuit patterns shown on the left to drive these loads.

LED Chains

With a transistor you can drive lots of LEDs from a single pin. Various calculators on the web can help you find the right configuration for the number and type of LEDs you want to use. Note though that the online calculartors don't always follow good design rules so learning the manual approach is still useful.

Small Motors

Small motors (like those in toys) can be controlled. Watch the current and voltage requirements – even small motors can have a high current when stalled. A diode should be connected as shown to protect the circuit from a reverse voltage that any electromagnet generates when it is switched off.

M

Relay

A relay is an electrical switch which is moved by an electromagnet. By connecting the magnet as a load to the Arduino the switch can be used to control another circuit completely independently. This has many uses – eg if you are controlling something that is too high power to be easily done with just a transistor, or if you don't know the full electrical characteristics of the thing being controlled (eg you are faking a button press on another piece of equipment). Relay coils also need a protection diode as shown

Relay Coil (Magnet)

Switch controlled by relay

Page 32: Elektronika -osnove

32 - lushprojects.com

Arudino ShieldsTo make it easy to connect the standard Arduinos to external systems you can use pre-made “Arduino Shields”. These connect on top of the Arduino board.

Example shields:- Motor control- Ethernet- Xbee- Servo motor and Stepper Motor shields

Other things you can connect (with the right electronics)Servo MotorsServo motors were originally designed for use in radio control models. They have a lever which is moved through about 280 degrees of rotation by the motor. The Arduino has special commands to control stepper motors.

Stepper MotorsStepper Motors are special motors that move in individual steps. They can be used for precise control over position or speed of rotation.

Infrared ChoppersAn infrared light can be shone through a gap to detect levers or other mechanical parts that interrupt the light beam

.

Distance Sensors

Page 33: Elektronika -osnove

33 - lushprojects.com

100k

100k(Brown-Black-Yellow)

Arduino

Gnd Analog In 0

5V

Note: Circuit Diagram only shows the analog input

Arduino Analog InputsWe've seen the Arduino's digital inputs in action. Now we will look at an analog input. The analog inputs can measure and report the voltage at the pin in the range 0V to 5V.

1) Modify the circuit as shown (replace the 10k resistor with a 100k resistor and move the input wire from digital Pin 5 to Analog Pin 0).2) Open the sketch “simpleorgan” and upload the the Audruino3) Try touching the wire probes to a pencil line track or to your skin. You should get an organ effect.

The circuit used here is called a “voltage divider”. The voltage at at the Analog input pin depends on the ratio of the 100k resistor to the resistance between the two probes. As the resistance between the probes decreases the voltage at the analog input goes up.

The analog input can be connected to many types of sensor. There are some common examples shown below.

Alternative Analog Inputs

10k to100k

Arduino

Gnd Analog In

5V LightDependentResistor

Arduino

Gnd Analog In

5V

VariableResistor

Page 34: Elektronika -osnove

34 - lushprojects.com

Pulse Width Modulation (PWM)The Arduino only has digital (0V or 5V) outputs. However it can output an approximation of an intermediate analog voltage using a technique called Pulse Width Modulation (PWM). In PWM a digital output moves between the on and off states very quickly. The ratio of the the “on” time to the “off” time (called the “duty cycle”) can be varied to create an average voltage which is intermediate between on and off voltages.

PWM signals aren't suitable for everything, but they do work well for some types of system – in particular:LEDs where the rate of blinking is too fast for the human eye to see, andSmall motors which can have the speed varied by PWM.

PWM in the Arduino

PWM is only available on the special outputs labelled with “PWM” on the board. There are further restrictions if you want to combine PWM with the “tone” function. To send a PWM signal set the pin as an output and use the analogWrite() function with a value between 0 for all off and 255 for all on (see diagram). The designers of Arduino made a big mistake naming this function – there is no analog output. “PWMWrite()” would be a much better name!

To test the effect of PWM on an LED keep the same circuit as before and load the sketch “organandlight” and upload to the Arduino This sends a PWM signal to pin 6 which depends on the pitch of the organ – the LED should be bright for low notes and dimmer for higher notes.

LEDDim

LEDBright

MotorSlow

MotorFast

LEDOff

MotorOff

Page 35: Elektronika -osnove

35 - lushprojects.com

Arduino Organ II with light effectsA fun thing to finish (and show a more complicated level of Arduino programming).

Using the same electronics as before load the sketch “organandlight2” and upload to the Arduino. You should now have an organ with lights that flash in sequence based on the frequency.