Sei sulla pagina 1di 357

Preface

Prefazione
Riguardo SunFounder
About SunFounder
SunFounder una compagnia
SunFounder is èa company focused onfocalizzata sull'educazione
STEM education with productsSTEM con prodotti
like opensource robots,come robot
aircraft opensource,
models, and smart
modellini aerei e globally.In
devices distributed dispositiviSunFounder,
smart distribuiti globalmente.
we strive In SunFounder
to help elementary ci school
and middle sforziamo di aiutare
students glihobbyists,
as well as studenti
delle
through scuole
STEMelementari
education,estrengthen
medie cosiccome gli obbisti,
their hands-on tramite
practices and l'educazione STEM,
problem-solving a rafforzare
abilities. le loro
In this way, we pratiche
hope to
manuali e le abilità di risoluzione dei problemi. In questo modo, speriamo di disseminare la conoscenza e
disseminate knowledge and provide skill training in a full-of-joy way, thus fostering your interest in programming and
fornire una formazione in maniera divertente, promuovendo così il tuo interesse nella programmazione e nel
making, and exposing you to a fascinating world of science and engineering. To embrace the future of artificial
making, e avvicinandoti all'affascinante mondo della scienza e dell'ingegneria. Per abbracciare il futuro
intelligence, it is urgent and meaningful to learn abundant STEM knowledge.
dell'intelligenza artificiale, è urgente e significativo imparare abbondanti dosi di conoscenza STEM.

About the ilVincent


Riguardo VincentKit
Kit
This is a kit
Questo kitsuitable forabeginners
è adatto and ed
principianti knowledgable
esperti di Arduino
Arduino.learners. The kit il
Il kit utilizza uses Mega2560
Mega2560 as thescheda
come main control board,
di controllo
containing 64
principale, e commonly
contiene used input and output
64 componenti components,
di I/O modules
comunemente and so
usati, many basic
moduli components
e tanti elementi (such as resistors,
di base (come
capacitors,condesatori,
resistori, transistors, etc.), and it can
transistor, provide
ecc.) e puòpowerful
fornire help for you to
un potente finish
aiuto your
per programming
finire projects.
i progetti di programmazione.

Free Support
Supporto gratuito
If you
Se haihave any TECHNICAL
domande questions,
TECNICHE, aggiungiadd
un aargomento FORUM
topic undernella sezione FORUM
section on our del
website andsito
nostro we'lle reply as soon as
risponderemo
il prima possibile.
possible.

Per NON-TECHNON
For domande questions come
like order
TECNICHE, problemi
and di issues,
shipment ordineplease send anper
e spedizione, email
favore manda una e-mail a
to service@sunfounder.com.
You're also welcomed to share
service@sunfounder.com. Seiyour projects
anche on FORUM
il benvenuto a condividere i tuoi progetti nel FORUM.
Contents
Contenuto
Components
Lista list....................................................................................................................................................................................
dei Componenti ....................................................................................................................................................................... 1
Introduction...........................................................................................................................................................................................
Introduzione ........................................................................................................................................................................................ 9
Basi..........................................................................................................................................................................................
Part 1:1:Basic
Parte ........................................................................................................................................................................................ 10
1.1 Arduino IDE............................................................................................................................................................................. 10
1.2 Digital Write.............................................................................................................................................................................21
1.3 Analog Write........................................................................................................................................................................... 29
1.4 Digital Read............................................................................................................................................................................. 35
1.5 Analog Read............................................................................................................................................................................ 40
1.6 Digital Input Control Output................................................................................................................................................. 45
1.7 Analog Input Control Output................................................................................................................................................50
1.8 Serial Read............................................................................................................................................................................... 55
1.9 Digital Input Pull-Up...............................................................................................................................................................63
1.10 State Change Detection....................................................................................................................................................... 68
Part 2:2:Component
Parte ..............................................................................................................................................................................
Componenti ..........................................................................................................................................................................81
2.1 Common Component........................................................................................................................................................... 81
2.2 LED............................................................................................................................................................................................89
2.3 RGB LED................................................................................................................................................................................... 95
2.4 LED Bar Graph....................................................................................................................................................................... 102
2.5 7-Segment Display............................................................................................................................................................... 108
2.6 74HC595................................................................................................................................................................................ 118
2.7 4-Digital 7-Segment Display............................................................................................................................................... 125
2.8 LED Matrix Module.............................................................................................................................................................. 134
2.9 I2C LCD1602 Module........................................................................................................................................................... 144
2.10 Active Buzzer....................................................................................................................................................................... 152
2.11 Passive Buzzer..................................................................................................................................................................... 157
2.12 Servo.................................................................................................................................................................................... 166
2.13 Motor................................................................................................................................................................................... 173
2.14 Stepper Motor.................................................................................................................................................................... 184
2.15 Button.................................................................................................................................................................................. 193
2.16 Slide Switch......................................................................................................................................................................... 199
2.17 Tilt Switch............................................................................................................................................................................ 204
2.18 Touch Switch Module........................................................................................................................................................ 209
2.19 Keypad................................................................................................................................................................................. 214
2.20 IR Receiver Module............................................................................................................................................................ 221
2.21 Relay Module...................................................................................................................................................................... 227
2.22 Potentiometer..................................................................................................................................................................... 233
2.23 Joystick Module.................................................................................................................................................................. 238
2.24 MPR121 Module................................................................................................................................................................ 244
2.25 Rotary Encoder Module.................................................................................................................................................... 251
2.26 Photoresistor....................................................................................................................................................................... 258
2.27 Thermistor........................................................................................................................................................................... 262
2.28 Sound Sensor Module....................................................................................................................................................... 267
2.29 Water Sensor Module........................................................................................................................................................ 272
2.30 IR Obstacle Avoidance Sensor.......................................................................................................................................... 277
2.31 PIR Module..........................................................................................................................................................................281
2.32 DHT11 Module................................................................................................................................................................... 287
2.33 Ultrasonic Module.............................................................................................................................................................. 293
2.34 MPU6050 Module.............................................................................................................................................................. 300
2.35 RFID-RC522 Module.......................................................................................................................................................... 309
Esempi................................................................................................................................................................................ 317
Part 3:3:Example
Parte
3.1 Aiuto
Reversing Aid....................................................................................................................................................................
alla Retromarcia .................................................................................................................................................... 317
3.2 Pulsante
Pedestriandi Crossing Button...........................................................................................................................................
Attraversamento Pedonale...................................................................................................................... 322
3.3 Overheat Monitor
Monitor del ...............................................................................................................................................................
Surriscaldamento ........................................................................................................................................ 328
3.4 Guess
Indovina il Numero
Number .......................................................................................................................................................... 336
...................................................................................................................................................................
3.5 Access
SistemaControl
di controllo System degli accessi................................................................................................................................ 342
.....................................................................................................................................................
Parte
Part 4:4:Appendix
Appendici ........................................................................................................................................................................... 349
............................................................................................................................................................................... 349
4.1 Add
Aggiungere
LibrariesLibrerie ............................................................................................................................................................... 349
............................................................................................................................................................................
Components list

1
2
3
4
5
6
7
8
Introduction
Introduzione
This book,
Questo as acome
libro, tutorialun
ortutorial
a handbook,
o un can be divided
manuale, può into fourdiviso
essere parts: in 4 parti:

Part 1:Basic
 Parte 1:Basi

This section
Questa includes
sezione includeArduino-related materials,
materiali relativi including
ad Arduino, IDEl'installazione
come installation and basic efunctions
dell'IDE (read,
le funzioni write, serial
di base
(lettura, scrittura,
communication, comunicazione seriale, ecc.).
etc.).

 Parte 2:Componenti
Part 2:Component

Questa
This partparte include
includes tutti i componenti
all components and modulese i moduli delKit,
of Vincent Vincent Kit e spiega
and explains i principi
their working di funzionamento
principles and codes. e
codici.
If you view the directory carefully, you will find that the use of the output device is introduced first, and then the use of
Se
theguardi attentamente
input device. The inputladevice
sezione, troverai
is also dividedche
intoprima è introdotto
switched input and l'uso
sensordei dispositivi di output e poi quelli
input.
di input. I dispositivi di input sono inoltre divisi in input switch e input sensori.
 Part 3:Example
 Parte 3:Esempi
This section includes several sample programs written by Sunfounder that you can refer to when finishing some
Questa sezione
interesting contiene
projects diversi
of Vincent Kit. programmi di esempio scritti da SunFounder ai quali puoi fare riferimento
quando terminerai alcuni interessanti progetti del Vincent Kit.
 Part 4:Appendix
 Parte 4:Appendice
This section contains the extension function of Arduino IDE, and currently includes the method of adding libraries.
Questa sezione contiene la funzione di estensione dell'IDE di Arduino, e i metodi di aggiunta delle librerie.
We look forward to your project and hope that you who have read this document will come to our forum to share the
results when you
Aspettiamo finish
i tuoi the project.
progetti e speriamo che, finito di leggere questo documento, li condividerai sul nostro forum.

9
Part 1:1:Basic
Parte Basi
1.1 IDE Arduino
Arduino IDE

Description
Descrizione

Arduino isèan
Arduino open
una source platform
piattaforma openwith simple
source consoftware andehardware.
software hardware You can pick Potrai
semplici. it up inconocerli
short timein
even if you
breve are a
tempo
anche se Itsei
beginner. un principiante.
provides Fornisce
an integrated un ambiente
development di sviluppo
environment (IDE) forintegrato (IDE) per
code compiling, la compilazione
compatible del codice,
with multiple control
compatibile
boards. So youcon
can molteplici schede
just download di controllo
the Arduino (control
IDE, upload boards).(i.e.
the sketches Perciò puoi
the code semplicemente
files) scaricare
to the board, and then youl'IDE
can
Arduino,
see relativecaricare gli sketch
experimental (es. i fileFor
phenomena. di more
codice) sulla scheda,
information, refer e
toquindi osservare i relativi fenomeni sperimentali.
http://www.arduino.cc.
Per maggiori informazioni, si riferisca a http://www.arduino.cc.
Install Arduino IDE
Installare l'IDE Arduino
Here are the installation steps on the windows system.
Qui ci sono i passaggi di installazione sul sistema Windows.
For other systems, please refer to: Install Arduinio IDE in different and FAQ.pdf
Per altri sistemi, si prega di fare riferimento a: Install Arduinio IDE in different and FAQ.pdf
The code in this kit is written based on Arduino, so you need to install the IDE first. Skip it if you have done this. Now go to
Il codice inand
arduino.cc questo kit è scritto->
click SOFTWARE per Arduino, quindi
DOWNLOADs. devi
on the prima
page, installare
check l'IDE.list
the software Salta il passaggio
on the right side. se lo hai già
fatto. Vai su arduino.cc e clicca SOFTWARE → DOWNLOADS. Sulla pagina, cerca la lista software a destra.

10
Find the
Trova one that
quello che suits youral
si adatta operation system
tuo sistema and click
operatio to download.
e clicca There Ci
per scaricare. aresono
two due
versions of Arduino
versioni for Windows:
di Arduino per
Installer or ZIP
Windows: file. You're
Installer o ZIPrecommended to download
file. Si consiglia theilformer.
di scaricare primo.

11
For Installer
Per File
il File Installer

Step 1: 1:
Passo Find the il.exe
trova filefile just
.exe downloaded.
appena scaricato.

Step 2:2:
Passo Double click the
fai doppio filesul
click and a window
file will pop apparirà
ed una finestra up as below.
come diIseguito.
Click Agree. Clicca su I Agree.

12
Step 3:3:
Passo Click Next.
clicca su Next.

Step 4: 4:
Passo Select the path
seleziona to install. By
il percorso default, it's set Di
di installazione. in the
baseC
è sulYou
disk. disco
canC. Puoi
click cliccare
Browse andBrowse e scegliere
choose other altri
paths. Click
percorsi.
OK. Clicca
Then click OK. Quindi clicca Install.
Install.

Step 5:5:
Passo Meanwhile, it will richiederà
nel frattempo, prompts install the needed
di installare drivers,
i driver
necessari; scegliere
please select 'Always
the ‘Always trusttrust software
software from
from “Arduino LLC” ’.
"Arduino LCC"'. A installazione
After the installation finita, clicca su Close.
is done, click Close.

Nota:
Note:

The
Il new IDE
nuovo IDE may
può prompt errors
dare errori when you're
durante compiling code
la compilazione under Windows
in Windows XP.tuo
XP. Se sul So ifcomputer
your computer is running
gira XP, ti on XP,
you're suggested
consigliamo to install Arduino
di installare Arduino1.0.5
1.0.5oro1.0.6.
1.0.6-Also youanche
Puoi can upgrade your computer.
aggiornare il tuo computer.

13
For ZIP
Per FileZIP
il File

If you
Se hai download the zipilfile
prima scaricato filebefore, when you
zip, quando connect
connetti the MCU
l'MCU to the computer,
al computer, potrebbeit non
mayessere
not bericonosciuta.
recognized. Then
È you
quindi
need tonecessario installare
install the driver i driver
manually. Takemanualmente. Procedi nel seguente modo.
the following steps.

Passo
Step 1: 1: collega
Plug in thela scheda
board al computer
to the con aun
computer with 5Vcavo USB da
USB cable. 5V.aDopo
After while, un po', verrà
a prompt visualizzato
message of failedun messaggio
installation will
di avviso di installazione non riuscita.
appear.

Passo2:2:Go
Step Vaitoa the
Gestione
DeviceDispositivi.
Manager. YouTroverai, sotto
will find "altri
under dispositivi",
other l'Arduino
devices, Arduino Mega
Mega 2560
2560 con
with anun punto
exclamation mark
esclamativo,
appear, which che significa
means che il computer
the computer non ha the
did not recognize riconosciuto
board. la scheda.

14
Step 3: 3:
Passo Right
clickclick on Arduino
destro Mega
su Arduino 25602560
Mega and select UpdateAggiorna
e seleziona Driver Software.
Driver Software.

15
Step 4:4:
Passo Choose
Sceglithe second option,
la seconda Browse
opzione, myi computer
Cerca driver nelfor Driver software.
computer.

16
Step 5:5:A apparirà
Passo window pops
poi una
up then.
finestra. Browse.
ClickClicca Sfoglia...
Then goQuindi
to the folder
vai allawhere
cartella
youinjust
cuiextracted
hai appena
the file.
estratto
Go toilthe
file.drivers
Vai
folder
alla delOK
and click
cartella -> Next.
driver e clicca su OK → Avanti.

17
Step 6:6:
Passo Select ‘Always
Seleziona trustsempre
‘Fidati softwaredel
from “Arduino
software daLLC” ‘ thenLLC”
“Arduino click‘, Install.
quindi clicca Installa.

It may need
Potrebbe a sec. Then
richiedere unthe system prompts
secondo. Dunqueyou the driver
il sistema has been
richiede cheinstalled
il driversuccessfully. So the computer
sia stato installato can recognize
correttamente. A
the board
questo now. ilClick
punto Close. può riconoscere la scheda. Clicca su Close.
computer

18
Open the
Aprire Arduino Software
il Software Arduino(IDE)
(IDE)

Double-click
Doppio clickthe ArduinoArduino(arduino.exe)
sull'icona icon (arduino.exe) created by
creata
the installation
dal processo di process.
installazione.

Apparirà l'IDE Arduino.


Then the Arduino IDE willVediamo i dettagli
appear. Let's del of
check details
software.
the software.

1. Verify: Compile
compila your
il codice.
code.Ogni erroreproblem
Any syntax di sintassi
will
verrà mostrato
be prompted con
with errori.
errors.

Upload:Upload
2. Upload: carica the
il codice
code tosulla
your scheda. Quando
board. When you
clicchi,
click thei button,
LED RXthe
e TX
RXsulla scheda
and TX LEDs lampeggeranno
on the board will
veloci e non
flicker fast andfiniranno finché
won't stop nonupload
until the è terminato.
is done.

3. New: crea una


Create nuova
a new finestra
code editingdi modifica.
window.

4. Open: apri
Openuno sketch
an .ino .ino.
sketch.

5. Save: salva lo sketch.


Save the sketch.

6. Serial
SerialMonitor:
Monitor: Clicca
Click e apparirà
the button and auna finestra.
window will
appear. It receives
Riceverà i dati the data dalla
inviati sent from
tua your control
scheda di

19
board. It is very
controllo. useful
È molto for per
utile debugging.
il debugging.

7. File: Click
cliccathe
sulmenu
menuand a drop-down
e apparirà list will
una lista appear, including
a discesa, file la
che include creating, opening,
creazione saving,
di file, closing,
l'apertura, la some parameter
chiusura,
alcuni parametri
configuring, etc. di configurazione, ecc.

8. Edit: Click
cliccathe
sulmenu.
menu.On thelista
Sulla drop-down list,cithere
a discesa sonoare someoperazioni
alcune editing operations likecome
di editing Cut, Copy, Paste,
Taglia, Find,
Copia, and so on,
Incolla,
with
Trovatheir corresponding
e via dicendo, conshortcuts.
le corrispondenti scorciatoie da tastiera.

9. Sketch: Includes operations like


include operazioni comeVerify, Upload,
Verifica, Add files,
Carica, etc. More
Aggiungi File,important functionpiù
ecc. La funzione is Include Library
importante – where you
è Includi
can add libraries.
Libreria - dove puoi aggiungere librerie.

10. Tool: Includes some tools


include alcuni – the -most
strumenti frequently
la Scheda used Board (the
maggiormente board
usata you use)che
(la scheda andusi)
Porte (the port (la
la Porta your board
porta is at).
alla
Every time
quale you la
si trova want
tuatoscheda).
upload the
Onicode,
voltayou
cheneed
vuoitocaricare
select oril check them.
codice, devi selezionarle o controllarle.

Help: se
11. Help: If you're a beginner, you
sei un principiante, may
puoi check theleoptions
controllare opzioniunder the menu
di questo menu and get thel'aiuto
e ottenere help you need,
di cui including
hai bisogno,
operations
comprese in IDE, introduction
operazioni sull'IDE,information, troubleshooting,
le informazioni code explanation,
iniziali, la risoluzione etc.
dei problemi, la spiegazione del codice, ecc.

12. In this messagediarea,


quest'area no mattersia
messaggio, when you compile orche
in compilazione upload, the summary
in caricamento, message
verrà will mostrato
sempre always appear.
un riepilogo.

Detailed messages
13. Messaggi during
dettagliati compile
durante and upload. eFor
la compilazione example, the Per
il caricamento. file used lies in
esempio, which
il file path, the
utilizzato detailsinof
si trova error
quale
prompts.
percorso, i dettagli degli errori mostrati.

14. Board and Port: Here you visualizzare


qui puoi can preview la
thescheda
board e
and port selected
la porta for code
selezionati per ilupload. You candel
caricamento select themPuoi
codice. again by
Tools -> Board
selezionarli / Port if anyda
nuovamente is incorrect.
Tools -> Board / Port se non sono corretti.

15. The editing


L'area area of the
di modifica IDE. You
dell'IDE. can
Qui write
puoi code here.
scrivere il codice.

20
1.2 Digital Write

Overview
Panoramica

The digitalWrite()
L'istruzione statementqui
digitalWrite() hereviene
is used to write per
utilizzata highdare
levelun
or low level
livello to pins
high and
o low aito leteLED
pin and
dare al active
LED ebuzzer 「work 」
al cicalino
(active buzzer)
or 「stop」. il comando
In this lesson, we [LAVORA] o as
will take LED [FERMATI]. Into
an example questa lezione
introduce useremo un
the experiment LED per testare il fenomeno.
phenomenon.

Componenti
Components Richiesti
Required

1 * LED 1 * 220ohm
ResistoreResistor
220ohm Diversi
Several Jumper
Jumper Filari
Wires

1 * Mega 2560 Board 1 * Breadboard

Note: Refer
Nota: to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

21
Fritzing Circuit

In this example,
questo we use
esempio, digital pin
useremo 9 todigitale
il pin drive the
9 LED. Attach one side
per comandare of the
il LED. resistor
Attacca untolato
the del
digital pin 9 and
resistore the digitale
al pin longer pin
9
e il pin lungo
(anode) (anodo)
of the LED to thedel LEDside
other all'altro
of thelato del Connect
resistor. resistore.the
Connetti il pin
shorter pin corto (catodo)
(cathode) deltoLED
of the LED a GND (a terra).
GND.

22
Schematic Diagram
Diagramma Schematico

Code
Codice
After finishing
Dopo the circuit
aver terminato la connection,
connessione connect the Mega2560
del circuito, connettiboard to theMega2560
la scheda computer. al
Run the Arduino
computer. software
Avvia IDE and
il software
Arduino IDE
type in the e digitacodes.
following il codice seguentel

NOTA:
NOTE: puoiYou
anche aprire
can il file 1.2digitalWrite.ino
also open nel percorso:
the sunfoudner_vincent_kit_for_arduino\code\
1.2digitalWrite.ino file in the path of
1.2digitalWrite per usare il codice.
sunfoudner_vincent_kit_for_arduino\code\1.2digitalWrite to use the codes.

const int ledPin = 9;


void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin,LOW);
delay(1000);
}

23
Uploadilthe
Carica codessulla
codice to the Mega2560
scheda board, and
Mega2560 you can
e vedrai see the blinking
lampeggiare of LED.
il LED.

Code Analysis
Analisi del Codice

Here, we connect
Dobbiamo the LED
connettere to the
il LED al digital pin 9, so
pin digitale we need
9, perciò to declaredichiarare
dobbiamo an int variable
unacalled ledpin
variabile at the beginning
chiamata ledPin of the
all'inizio
program anddel programma
assign a valueeof
assegnarli
9. il valore 9.

const int ledPin = 9;

Ora,
Now,inizializziamo
initialize the pinil in
pin nella
the funzione
setup() setup(),
function, wherenella modalità
you need OUTPUT.
to initialize the pin to OUTPUT mode.

pinMode(ledPin, OUTPUT);

In loop(),
loop(),digitalWrite()
digitalWrite() vienetousato
is used per5V
provide fornire un segnale
high level a livello
signal for ledpin, high
which(5will
V) cause
al ledPin, chedifference
voltage causa una differenza
between LED
di tensione
pins and lighttra i pin
LED up.del LED che si illuminerà.

digitalWrite(ledPin, HIGH);

If the
Se level signal
il segnale is changed
cambia to LOW,
in LOW, the ledPin's
il segnale signal
al ledPin will beareturned
tornerà 0 V per to 0 V to turn
spegnere LED off.
il LED.

digitalWrite(ledPin, LOW);
An interval
Un between
intervallo tra on on and
e off è off is required
richiesto to allow people
per permettere to see thedichange,
alle persone vedere so we use a delay(1000)
il cambiamento, perciòcode to letilthe
useremo
codice delay(1000)
controller do nothingper consentire
for 1000 ms. al controller di non fare nulla per 1000 ms.

delay(1000);

24
How toCaricare
※ Come Upload the Sketch
lo Sketch

Before di
Prima you upload ila codice
caricare written code tosu
scritto Arduino, youdevi
Arduino, needselezionare
first to selectlaBoard ande Port.
Scheda la Porta.

Click Tools
Clicca Tools->Board andeselect
->Board Arduino/Genuino
seleziona Mega orMega
Arduino/Genuino Mega 2560.
or Mega 2560.

25
Poi select Tools
Thenseleziona Tools
->Port. Your
->Port. Laport
tuashould be differentessere
porta potrebbe from mine.
differente da quella qui sotto.

Step 4: Upload thesketch


Carica lo sketchsulla
to the SunFounder
scheda Mega2560
SunFounder board. Clicca
Mega2560. Click the Upload
l'icona Upload
icon to upload
per the ilcode
caricare to the
codice control
sulla
scheda
board. di controllo.

26
If "Done
Se "Doneuploading"
uploading"appears at the
sul fondo bottom
della of thesignifica
finestra, window,che
it means the sketch
lo sketch hascorrettamente
è stato been successfully uploaded.
caricato.

27
Phenomenon
Immagine Picture
Fenomenologica

28
1.3 Analog Write

Overview
Panoramica

You
È can writescrivere
possibile the PWM wave to
l'onda the pin
PWM al by
pinusing analogWrite().
utilizzando This method
analogWrite(). can bemetodo
Questo used to adjust the brightness
può essere of LED,
utilizzato per
regolare lacolor
change the luminosità
of RGB,del LED, cambiare
or adjust il colore
the motor speed, etc.RGB,
Hereowe
regolare
will takela velocità
LED del motore,
as an example to getecc. Qui prenderemo
gradient brightness of
un
LED.LED come esempio per ottenere una luminosità variabile del LED stesso.

Componenti
Components Richiesti
Required

1 * LED Resistore
1 * 220ohm1 *Resistor
220ohm Diversi
Several Jumper
Jumper Filari
Wires

1 * Mega 2560 Board 1 * Breadboard

29
※ Pulse Width Modulation (PWM)

Pulse
La Width Modulation,
modulazione or PWM,diisimpulso,
della larghezza a technique for getting
o PWM, è una
tecnica results
analog per ottenere risultati
with digital analogici
means. con
Digital mezziisdigitali.
control used to Il
controllo digitale
create a square ì utilizzato
wave, a signalper crearebetween
switched un'ondaon
quadrata,
and off.
un
Thissegnale che cambia
on-off pattern tra onvoltages
can simulate e off. Questo modello
in between on-
full on (5
off puà
Volts) simulare
and tensioni
off (0 Volts) fra full the
by changing on portion
(5 Volt)ofe the
off time
(0 Volt)
the
cambiando
signal spendslaonporzione ditime
versus the tempo
that che il segnale
the signal trascorre
spends off. The
in on rispetto
duration a quella
of "on time" trascorsa
is called in width.
the pulse off. La
To durata del
get varying
"tempovalues,
analog on" you
è chiamata larghezzathat
change, or modulate, di pulse
impulso
width.(pulse
If you
width).this
repeat Peron-off
ottenere diversi
pattern segnaliwith
fast enough analogici, è possibile
an LED for example,
cambiare,
the result isoasmodulare,
if the signalquesta larghezza
is a steady voltage di impulso.
between Se 5v
0 and si
ripete questo
controlling modello ofon-off
the brightness the LED.abbastanza velocemente
con un LED, ad esempio, il risultato è come un segnale a
A call to analogWrite() is on a scale of 0 - 255, such that
tensione costante tra 0 e 5v, permettendo il controllo
analogWrite(255) requests a 100% duty cycle (always on), and
della luminosità del led.
analogWrite(127) is a 50% duty cycle (on half the time) for
Una chiamata su analogWrite() è su una scala 0-255, in
example.
modo tale che, ad esempio, analogWrite(255) richiede un
ciclo di lavoro al 100% (sempre on) e analogWrite(127)
richiede un ciclo di lavoro al 50% (metà del tempo).

30
Fritzing Circuit

In questo
this example,
esempio,
weusiamo
use theil pin
PWM PWM
pin 99 per
to drive
guidare
theil LED.
LED. Connect
Connetti one
un'estremità
end of the
del resistore
resistor to
al pin
pin 9.
Connetti
Connect the
il pinlong
lungo
pin(anodo)
(anode)del
of LED
the all'altro
LED to capo
the other
del resistore.
end of the
Connetti
resistor.
il pin
Connect
corto (negativo,
the short indicato
pin (negative,
come
referred
catodo) del
to as
LED
thea cathode)
terra (GND).
of LED
NOTA:
to GND.
i pin PWM
NOTE:della
PWM Mega2560
pins of Mega2560
sono 2 - 13,
board
44 -are
46. 2 - 13, 44 - 46.

31
Schematic Diagram
Diagramma Schematico

Codice
Code
int ledPin = 9;
setup() {{
void setup()

}
void loop() {
for (int value = 0 ; value <= 255; value += 5) {
analogWrite(ledPin, value);
delay(30);
}
}

After uploading
Dopo the ilcode
aver caricato to the
codice sullaMega2560 board, youpotrai
scheda Mega2560, can see that che
vedere the LED gradually
il LED brightens
si illumina out and eturns
gradualmente si off
spegne
gradually.gradualmente.

32
Code Analysis
Analisi del Codice

Declare pin
Dichiara 9 as9ledPin.
il pin come ledPin.

int ledPin = 9;

analogWrite() in
in loop()
loop()assigns ledPinun
dà al ledPin an val.
analog value (PWM
analogico wave)
(onda PWM)between
tra 0 e0 255
and per
255 cambiare
to change la
theluminosità
brightnessdel
of LED.
LED.

analogWrite(ledPin, value);

Using a for loop,


Utilizzando the for,
un ciclo value of analogWrite()
il valore can bepuò
di analogWrite changed step by step
essre cambiato between the
passo-passo tra minimum
un valore value
minimo(0) (0)
ande the
un
valore
maximum massimo (255).
value (255).

for (int value = 0 ; value <= 255; value += 5) {


analogWrite(ledPin, value);
}

Per vedere
In order chiaramente
to see il fenomeno
the experimental sperimentale,
phenomenon clearly,è anecessario aggiungere
delay(30) needs un ritardo
to be added (30)
to the foralcycle
ciclo to
percontrol the
controllare il tempo
brightness change di variazione della luminosità.
time.

void loop() {
for (int value = 0 ; value <= 255; value += 5) {
analogWrite(ledPin, value);
delay(30);
}
}

33
Phenomenon
Immagine Picture
Fenomenologica

34
1.4 Digital Read

Overview
Panoramica

You
È can use utilizzare
possibile the digitalRead() command
il comando to read the
digitalRead() perlevel statuslofrom
leggere a digital
stato pin. digitale.
di un pin The command is suitable
Il comando for digital
è adatto per
elementi di input
input elements digitale
such come
as Button, Pulsanti,
Touch sensori
sensor, Touch,
infrared sensori
motion sensor,dietc.
movimento
This articleadwill
infrarossi, ecc.as
take Button Questo articolo
an example to
prenderà
read come
the level esempio un Pulsante per leggere lo stato del livello del segnale.
state.

Questo esempio
This example alsomostra anche
shows you come
how monitorare
to monitor lo stato
the state of adello scambio
switch utilizzando
by using l'USB per
USB to establish stabilire
serial una
communication
comunicazione
between a controlseriale
boardtra
andlaa scheda di controllo e il computer.
computer.

Componenti
Components Richiesti
Required

1 * Pulsante
Button 1 *Resistore 1 * 10kΩ
10k ohm resistor Diversi
Several Jumper
Jumper Filari
Wires

1 * Mega 2560 Board 1 * Breadboard

Note: Refer
Nota: to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

35
Fritzing Circuit

In this example,
questo we read
esempio, the signal
leggiamo of the button
il segnale with thecon
del pulsante digital pin digitale
il pin 2. When2.the button is
Quando not pressed,
il pulsante nonthe
è digital
premuto,pin 2
il
pin digitale
(through the 2 (tramite la
drop-down resistenza
resistor) drop-down)
is connected è connessa
to ground allalow
to read the terra per
level (0);leggere il livello
when the buttonlow (0); quando
is pressed, il
the two
pulsante è premuto,
pins are connected andi when
due pin
thevengono connessi
pin is connected to e quando
the il pin
5V power è connesso
supply, the highai 5V,(1)
level viene letto il livello high (1).
is read.

NOTA : se
NOTE :If yousi disconnect
scollega ilthepin I/O
digital
digitale da tutto,
I/O pin from il LED
everything, thepotrebbe
LED may
lampeggiare
blink erratically.inThis
modo irregolare.
is because the
Questo perché- that
input is "floating" l'ingresso è
is, it doesn't
"fluttuante" - cioè non
have a solid connection ha una
to voltage or
connessione
ground, and itsolida alla tensione
will randomly o
return
alla
eithermessa
HIGH ora LOW.
terra,That's
e restituirà
why you
casualmente HIGH resistor
need a pull-down o LOW.in Ecco
the
perché
circuit. è necessario un resistore di
pull-down nel circuito.

36
Schematic Diagram
Diagramma Schematico

Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
int buttonState = digitalRead(2);
Serial.println(buttonState);
delay(1);
}

Dopo aver caricato


After uploading il codice
the code to thesulla Mega2560,
Mega2560 board,possiamo aprire
we can open the il monitor
serial della porta
port monitor seriale
to see per vedere
the reading il valore
value of the pin.
Whendal
letto youpin.
press Button,sithe
Quando serial ilport
preme monitorilwill
Pulsante, displaymostrerà
monitor 「1」 and when
[1], Buttonesso
e quando is released, 「0」 will mostrerà
verrà rilasciato, be displayed.
[0].

37
Code Analysis
Analisi del codice

Start the
Inizia serial communication
la comunicazione in setup()
seriale andeset
in setup() the datala
seleziona rate to 9600.
velocità dei dati a 9600.

Serial.begin(9600);

You
È also need
inoltre to set the
necessario status of lo
impostare thestato
digital
delpinpin
2 to INPUT 2
digitale tosu
read the output
INPUT status of
per leggere loButton.
stato di uscita del Pulsante.

pinMode(2, INPUT);

Use the digitalRead()


Utilizzare statement
il digitalRead() in loop()
in loop() per to read the
leggere level state
il livello del of
pinthe digital 2
digitale pin
e2 and declare
dichiarare a variable
una toin
variabile store
cui the state.
salvarlo.

int buttonState = digitalRead(2);

Print the value


Stampare storedmemorizzato
il valore by the variable on the
della serial port
variabile sul monitor.
monitor della porta seriale.

Serial.println(buttonState);

Use delay()
Utilizza statements
il comando to make
delay() perprinting
rendereresults easy
i valori to observe.
stampati più semplici da leggere.

delay(1);

How toattivare
※ Come turn on ilSerial Port Monitor
Monitor della Porta Seriale

Click the sull'icona


Cliccare magnifier icon
dellaatlente
the top right of the Arduino
di ingrandimento IDEa programming
in alto windowdi
destra della finestra to open the
Serial Monitor.
programmazione dell'IDE Arduino per aprire il monitor seriale.

38
Phenomenon
Immagine Picture
Fenomenologica

39
1.5 Analog Read

Overview
Panoramica

You
È can useusare
possibile the analogRead()
il comando command to read
analogRead() peranalog input
leggere from
l'input the physical
analogico world through
attraverso un pin an analog pin,
analogico, which
adatto is
per
elementi
suitable fordianalog
ingresso analogici
input elementscome potenziometri,
such as fotoresistenze,
potentiometers, sensori
photoresistance, water di rilevamento
level del livello
detection sensors, and dell'acqua
so on. This
e così will
article via.take
Questo articolo prenderà
the potentiometer as anilexample
potenziometro come
to read the esempio
analog per
value of its leggere
output. il valore analogico dell'uscita.

Componenti richiesti
Components Required

1 * potenziometro
potentiometer 11 ** Scheda Mega
Mega 2560 2560
Board

1 * Breadboard

Several
Diversi Jumper
JumperWires
Filari

40
Fritzing Circuit

In this example,
questo we use
esempio, the analog
useremo pin
il pin (A0) to read
analogico the
(A0) value
per of theil potentiometer.
leggere Connect the pins
valore del potenziometro. at both
Connetti ends
i pin adof the
entrambe le estremità
potentiometer to 5V anddel
GNDpotenziometro rispettivamente
respectively. Connect the middleapin
5Vtoe A0.
GND. Connetti il pin centrale ad A0.

Il
Thevoltaggio delthe
voltage of pinmiddle
centrale
pinsarà mandato
will be output alla scheda
to the Mega2560
Mega2560 boardcome
as anvalore
analoganalogico. Ruotando
value. By rotating the gli
axisassi del
of the
potentiometer, you
potenziometro, can change
si può thela
cambiare voltage on the
tensione delmiddle pin, thereby
pin centrale, changingcosì
modificando the analog value
il valore of the pin
analogico delobtained
pin A0. by
A0.

41
Schematic Diagram
Diagramma Schematico

Code
Codice

void setup() {
Serial.begin(9600);
}

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}

After the
Dopo code
aver is uploaded
caricato to the Mega2560
il codice board,
sulla scheda you can open
Mega2560, the serial aprire
è possibile port monitor to viewdella
il monitor the reading
porta value of per
seriale the
visualizzare
pin. When theil shaft
valoreof di
thelettura del pin.isQuando
potentiometer l'asta
turned, the delport
serial potenziometro viene
monitor will print theruotato, il monitor
value that della porta
changes between "0"
seriale stamperà il valore che cambia tra "0" e "1023".
and "1023".

42
Code Analysis
Analisi del Codice

To enable
Per Arduino
abilitare IDE to print
l'IDE Arduino the valueiltransmitted
a stampare from electronic
valore traspetto component
dal componente to the Mega2560
elettronico board,
alla scheda you needèto
Mega2560,
necessario avviare la comunicazione
start serial communication in setup() andseriale
set theindata
setup() e impostare
rate to 9600. la velocità dati su 9600.

Serial.begin(9600);

Utilizzare l'istruzionestatement
Use the analoglRead() analogRead() in loop()
in loop() per
to read theleggere lo stato
level state delby
acquired livello di tensione
analog pin A0 andacquisito
declare adal pin to store
variable
analogico A0 e dichiarare una variabile per memorizzare lo stato del livello.
the level state.

int sensorValue = analogRead(A0);


Print the value
Stampare storedmemorizzato
il valore in the variablenella
on the serial monitor.
variabile sul monitor seriale.

Serial.println(sensorValue);
Use delay()l'istruzione
Utilizzare statements to makeper
delay() printing results
rendere piùeasy to observe.
facilmente leggibili i risultati stampati.

delay(1);

※ Convertitore
Analog-to-Digital Converter
Analogico-Digitale

The Arduino
Aarduino ha have a circuit
all'interno uninside called
circuito an analog-to-digital
chiamato convertitore converter or ADC that
analogico-digitale readsche
o ADC thislegge
changing voltage
questa and
tensione
converts itetolaaconverte
variabile number between 0 and 1023.
in un numero tra 0When theQuando
e 1023. shaft is turned
l'astaall
è the way in
ruotata one direction, there
completamente are direzione,
in una 0 volts going
ci
to the0pin,
sono voltand
al the
pin,input value isdi0.input
e il valore Whenèthe shaft is turned
0. Quando l'astaall
è the way in
ruotata the opposite
nella direzionedirection,
opposta, there are 55volts
ci sono voltgoing
al pinto
e
the
il pin and
valore the input
di input valueNel
è 1023. is 1023. In between,
mezzzo, analogRead()
analogRead() returns
restituisce unanumero
number compreso
between 0 and
tra 01023 that proporzionale
e 1023, is proportional
to the
alla amountdi
quantità oftensione
voltage being applied
applicata al to the pin.
pin.

43
Phenomenon
Immagine Picture
Fenomenologica

44
1.6 Digital Input Control Output

Overview
Panoramica

With the capito


Avendo understanding of digitalWrite()
il digitalWrite() and digitalRead(),
e il digitalRead(), possiamowe costruire
can build a uncomplete
sistema II/O/ Ocompleto
system topercontrol the output
controllare un
dispositivo di output
device by obtaining theottenendo
data from thei dati dadevice.
input un dispositivo
We can usedi this
input. Possiamo
method usare
to enable questo
digital metodo
input per abilitare
components such as
componenti di input digitale come Pulsanti, sensori Touch, sensori di movimendo ad Infrarossi, per controllare
Button, Touch sensor, Infrared motion sensor to control digital output devices such as LED, active buzzer. This lesson will
dispositivi
take Buttondi output
and LED asdigitale
examples come LED, button
to realize active control
buzzer.LEDQuesta lezione
with the usa un
condition Pulsante ed un LED come esempi
(if-else).
per realizzare un LED conrollato da pulsante, con la condizione (if-else).
Components Required
Components Required
Button
1 * Pulsante 1 *1LED
* LED 1 * 10k ohm resistor
Resistore 10kΩ

Jumper filare
wire 1 * Resistore 220Ω
220ohm Resistor

1 * Mega 2560 Board 1 * Breadboard

45
Note: Refer
Nota: to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

Fritzing Circuit

In this example,
questo we use
esempio, pin 9 to drive
utilizzeremo LED.9 Use
il pin per digital pin 2iltoLED.
governare readUseremo
the signalilof Button.
pin When
digitale theleggere
2 per button is
il pressed,
segnale the
del
LEDPulsante.
lights up. Quando il pulsante è premuto, il LED si accende.

46
Schematic Diagram
Diagramma Schematico

Code
Codice

const int buttonPin = 2;


const int ledPin = 9;
int buttonState = 0;

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {

47
digitalWrite(ledPin, LOW);
}
}

After uploading
Dopo aver caricato
the code
il codice
to thealla
Mega2560
Mega2560,
board,
è possibile
you can hold
tenere
downpremuto
Button to
il pusante
lighten the
per
LED.
accendere il LED.

Code Analysis
Analisi del Codice
Declare the
Dichiara pinsdel
il pin of LED
LEDand Button
e del and declare
Pulsante a variable
e dichiara to store the
una variabile perstate of button. lo stato del pulsante.
memorizzare

const int
const int buttonPin = 2;
buttonPin = 2;
const int
const int ledPin = 9;
ledPin = 9;
int buttonState
int = 0;
buttonState = 0;

Initialize thelepin
inizializza mode indei
modalità setup().
pin in setup().

pinMode(ledPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(buttonPin, INPUT);

Read the
Leggi statusdel
lo stato of the Button in
pulsante in loop()
loop() ed
andassegnalo
assign it toalla
the variabile
variable buttonState.
buttonState.

buttonState = digitalRead(buttonPin);
buttonState = digitalRead(buttonPin);

Use if condition
Utilizza to judge:
la condizione if if
peryou get high level
giudicare: from aun
se ottieni button, light
livello updal
high thepulsante,
LED. accendi il LED.

if (buttonState
if (buttonState ==
== HIGH)
HIGH) {{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin, HIGH);

48
}

Otherwise, turn
Altrimenti, off the
spegni LED.
il LED.

else {
digitalWrite(ledPin, LOW);
}

Phenomenon
Immagine Picture
Fenomenologica

49
1.7 Analog Input Control Output

Overview
Panoramica

You
È can install
possibile an I/O system
installare by using
un sistema I/O an analoguninput/
usando output device.
dispositivo di I/O For example,Per
analogico. youesempio,
can use potentiometer,
si può usare
potenziometro,
photoresistor, fotoresistore,
water level sensor,sensore del livello
etc., to control the H 20, ecc., per
brightness controllare
of LED, la luminosità
the speed di un
of motor, and theLED, la this
like. In velocità di
lesson,
un motore e simili.
potentiometer In questa
and LED lezione,
are taken si cambierà
as examples la luminosità
to change del of
the brightness LEDthecon
LEDilwhen
ruotare
the del potenziometro.
potentiometer is turning.

Componenti Richiesti
Components Required

Potenziometro
1 * Potentiometer 11** LED
LED 11 **220
Resistore 220 Ω
ohm resistor

Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

Note:
Nota: Refer to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

50
Fritzing Circuit

In questa
this lesson,
lezione,
we use
useremo
PWM pin
il pin
9 to
PWMdrive
9 per
LED.guidare
The analog
il LED.
pinUseremo
(A0) is used
il pin
to analogico
read the value
(A0) of
perpotentiometer.
leggere il valore
Af-
del
ter uploading
potenziometro.
the code,
Caricato
you'll notice
il codice,
that the
noterai
brightness
che laof
luminosità
the LED changes
del LED
ascambia
the potentiometer
man manorotates.
che il potenz. ruota.

51
Schematic Diagram
Diagramma Schematico

Code
Codice

const int sensorPin = A0;


const int ledPin = 9;
void setup() {
pinMode(ledPin,OUTPUT);
}

void loop() {
int sensorValue=analogRead(sensorPin);
int brightness = map(sensorValue,0,1024,0,255);
analogWrite(ledPin,brightness);

52
}

When thei codici


Quando codes vengono
are uploaded to the
caricati Mega2560
sulla board, you è
scheda Mega2560, can see thatvedere
possibile the brightness of LED is changing
che la luminosità with the
del LED sta
cambiando
turning of thecon la of
knob rotazione della manopola del potenziometro.
potentiometer.

Analisi del Codice


Code Analysis

Dichiarare
Declare the ipins
pin of
del LED
LED e del
and Pulsante.
Button.

const int sensorPin = A0;


const int ledPin = 9;

In setup(), set
impostare la of
the mode modalità
ledPin todiOUTPUT.
ledPin OUTPUT.

pinMode(ledPin,OUTPUT);

Leggere le lettureofdel
Read the readings potenziometro
potentiometer in loop().
in loop().

int sensorValue=analogRead(sensorPin);

Mappare la lettura delreading


Map the potentiometer potenziometro
to the LEDalbrightness
valore di value
luminosità del
(0-1024 is LED (0-1024
mapped è mappato a 0-255).
to 0-255).

int brightness = map(sensorValue,0,1024,0,255);

Scrivere
Write theilbrightness
valore di value
luminosità
to LED.del LED.

analogWrite(ledPin,brightness);

53
Phenomenon
Immagine Picture
Fenomenologica

54
1.8 Serial Read

Overview
Panoramica

In addition
Oltre to reading
a leggere i datidata from the electronic
dai componenti components,
elettronici, theMega2560
la scheda Mega2560 board can read
può leggere the data input
l'ingresso in the
dati nel serial
monitor
dellamonitor,
port porta and
seriale
you ed possibile
can èuse utilizzare
Serial.read() Serial.read()
as the controller of thecome controller del
circuit experiment. Thencircuito di esperimento.
we use LED Poi
to experiment with
utilizzeremo
the il LED
Serial. Read() per sperimentare
statement con
to control LED tol'istruzione
turn on and Serial.Read()
off. il controllo acceso-spento del LED.

Componenti Required
Components Richiesti

1 * LED ResistoreResistor
1 * 220ohm 220Ω Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

Note: Refer
Nota: to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

55
Fritzing Circuit

In this example,
questo we use
esempio, digital pin 9iltopin
utilizzeremo drive LED. When
digitale 9 per1guidare
is entered in serial
il LED. monitor,
Quando the LED
viene lights1up.
inserito nelWhen
serial0monitor,
is entered,
il
LED si accende.
the LED turns off. Quando viene inserito 0, il LED si spegne.

56
Schematic Diagram
Diagramma Schematico

Code
Codice

const int ledPin = 9;


int incomingByte = 0;

void setup() {
pinMode(ledPin,OUTPUT);
Serial.begin(9600);
}

void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.read();
if(incomingByte=='1'){digitalWrite(ledPin,HIGH);}

57
else if(incomingByte=='0'){digitalWrite(ledPin,LOW);}
}
}

Dopo aver
After the caricato
codes i codici sulla
are uploaded to thescheda Mega2560,
Mega2560 si prega
board, please turnaccendere il monitor
on the serial dellaTyping
port monitor. porta in
seriale. Digitando
”1” can make LED
"1"
turnsion
può
andaccendere il LED
typing in ”0” e digitando
can make "0" è possibile spegnerlo.
it turn off.

Code Analysis
Analisi del Codice

Declare digital
Dichiara il pinpin 9 as ledPin.
9 come ledPin.

const int ledPin = 9;

Serial.read() reads
leggeaun
single byte of
singolo ASCII
byte comevalue, and therefore
valore you needètonecessario
ASCII e pertanto declare a int type variable,
dichiarare una incomingByte to store
variabile di tipo int,
incomingByte, per archiviare i dati acquisiti.
the acquired data.

58
int incomingByte = 0;

Run the serial


Esegue communication
la comunicazione in setup()
seriale and set
in setup() the data rate
e imposta to 9600.dati a 9600.
la velocità

Serial.begin(9600);

Imposta
Set ledPinilto
ledPin nella
OUTPUT modalità OUTPUT.
mode.

pinMode(ledPin,OUTPUT);

Lo
Thestato
state del monitor
of serial port della porta
monitor serialeinviene
is judged verificato
loop(), in loop() e processing
and the information l'eleaborazione
will bedelle informazioni
carried verrà
out only when the data
eseguita solo quando i dati saranno ricevuti.
are received.

if (Serial.available() > 0){}

Reads
Leggethe input value
il valore in the
di input nelserial port monitor
monitor and seriale
della porta stores iteto
lothe variable incomingByte.
memorizza nella variabile incomingByte.

incomingByte = Serial.read();

When thesicharacter
Quando ottiene '1' is obtained,
il carattere '1',the LEDsi
il LED is accende;
lit; when ’0’quando
is obtained, the LED
si ottiene '0',turns off.si spegne.
il LED

if(incomingByte=='1'){digitalWrite(ledPin,HIGH);}
else if(incomingByte=='0'){digitalWrite(ledPin,LOW);}
NOTE: Serial.read()
NOTA: Serial.read()takes the ASCII
prende valueASCII
il valore in single
nel character, which means
singolo carattere, that
il che when you
significa cheinput '1', the
quando si obtained
immette value
'1, il is not
the number
valore '1', but
ottenuto nontheècharacter
il numero'1''1',
whose
ma corresponding
il carattere '1' ASCII
il cui value
valoreis ASCII
49. corrispondente è 49.

59
ASCII chart
※ Tabella ASCII

Thecodifica
La ASCII (American StandardStandard
ASCII (American Code forCode
Information Interchange)
for Information encodingrisale
Interchange) dates agli
to the 1960's.
anni '60. It
È is
la the standard
modalità way that
standard
con is
text cui il testonumerically.
encoded viene codificato numericamente.

Si notithat
Note chethe
i primi
first 32
32 characters
characters (0-31)
(0-31)sono caratteri noncharacters,
are non-printing stampabili, spesso
often chiamati
called control caratteri di The
characters. controllo.
more Iuseful
caratteri più
characters utili
have beensono stati etichettati.
labeled.

ASCII Character ASCII Character ASCII Character ASCII Character ASCII Character ASCII Character

0 Null 23 46 . 69 EE 92
92 // 115
115 ss

1 24 47 / 70 FF 93
93 ]] 116
116 tt

2 25 48 0 71 G 94 ^ 117 u

3 26 49 1 72 H 95 __ 118
118 vv

4 27 50 2 73 I 96 、 119 w

5 28 51 3 74 J 97 aa 120
120 xx

6 29 52 4 75 K 98 b
b 121
121 yy

7 30 53 5 76 L 99 cc 122
122 zz

8 31 54 6 77
77 M
M 100
100 dd 123
123 {{

9 tab 32 space 55 77 78
78 N
N 101
101 ee 124
124 ||

60
10 line feed
avanzamento
33 ! 56 8 79 O 102 f 125 }
linea

11 34 " 57 9 80 P 103 g 126 `

12 35 # 58 : 81 Q 104 h 127

13 a
carriage 36 $ 59 ; 82 R 105 i
capo
return

14 37 % 60 < 83 S 106 j

15 38 & 61 = 84 T 107 k

16 39 , 62 > 85 U 108 l

17 40 ( 63 ? 86 V 109 m

18 41 ) 64 @ 87 W 110 n

19 42 * 65 A 88 X 111 o

20 43 + 66 B 89 Y 112 p

21 44 , 67 C 90 Z 113 q

22 45 - 68 D 91 [ 114 r

61
Phenomenon
Immagine Picture
Fenomenologica

62
1.9 Digital Input Pull-Up
Panoramica
Overview
Quando si utilizzano alcuni dispositivi di input switch, vengono spesso utilizzati alcuni resistori di pull-up o
pull-down
When usingper mantenere
some il livello
switch input dei pin
devices, corrispondenti
some ad un determinato
pull-up or pull-down resistors arevalore
often quando
used to ilkeep
dispositivo
the levelnon
of
funziona. Come
corresponding nell'
pins 1.4 Digital
at certain valueRead, uncondition
on the resistorethat
da the
10KΩ è utilizzato
device per mentenere
is not working. Such as inil 1.4
pinDigital
connesso
Read,a aterra
10k
quando il pulsante
resistor is used to makenon premuto.
è be
the pin Setoavessimo
connected GND underusato molti componenti
the condition that the buttondiis not
input switch
pressed e volessimo
down. If we have
semplificare il circuito,
used a lot of switch potremmo settare
input components and wantla to
modalità
simplify del pin a [INPUT_PULLUP]
the circuit, nel codice,
we can set the pin mode in modo che in
to「INPUT_PULLUP」 il pin
the
legga il that
code so livello
thealto
pin nello
reads stato sospeso.
the high level in the suspended state.

Componenti Richiesti
Components Required

1 * potenziometro
potentiometer DiversiJumper
Several JumperWires
Filari

1 * Breadboard
1 * Mega 2560 Board

63
Fritzing Circuit

In this example,
questo we use
esempio, pin 2 to read
utilizziamo the2signal
il pin of button.
per leggere The internal
il segnale del pull-up in pin
pulsante. 2 is valid,
Il pull-up sopin
nel if the
2 button isn’t
è valido, pressed,
quindi se
il pulsante
HIGH is readnon viene
in pin premuto,
2; when nel pin
the button 2 vieneLOW
is pressed, lettoisilread.
valore HIGH; quando si preme il pulsante, si legge LOW.

64
Schematic Diagram

Code

void setup() {
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
}

void loop() {
int buttonState = digitalRead(2);
Serial.println(buttonState);
delay(1);
}

After the
Dopo codes
aver are uploaded
caricato to the
i codici Mega2560
sulla scheda board,
Mega you canèopen
2560, the serial
possibile port monitor
aprire to view
il monitor theporta
della read values
serialeof per
the
visualizzare
pin. When thei valori
Buttondiislettura
pressed,del
thepin. Quando
serial si preme
port monitor willildisplay
pulsante, il monitor
"0", and the "1"della porta
will be seriale
displayed visualizzerà
when "0",
the button is
e "1" verrà visualizzato quando il pulsante sarà rilasciato.
released.

65
Analisi del Codice

Run thelaserial
Esegue communication
comunicazione in in
seriale setup() and
setup() set the data
e imposta rate todati
la velocità 9600.su 9600.

Serial.begin(9600);

Configure pin
Configura il 22
pin ascome
an input and
input edenable
abilita the internalinterno
il resistore pull-updiresistor.
pull-up.

pinMode(2, INPUT_PULLUP);

Read
Leggethe
lolevel
statostate
dal from the digital
pin digitale pin 2 by using
2 utilizzando digitalRead()instatement
digitalRead() in loop() and
loop() e dichiara una declare a variable
variabile to store it.
per memorizzarlo.

int buttonState = digitalRead(2);

Print
Stampathe ivalues
valoristored by variables
memorizzati nelleonvariabili
the serial port
sul monitor.
monitor della porta seriale.

Serial.println(buttonState);

66
Phenomenon
Immagine Picture
Fenomenologica

67
1.10 State Change Detection

Overview

When yousiuse
Quando button,
utilizza unyou can notnon
pulsante, onlysolo
pressè down the button,
possibile premerelight on the LED,accendere
il pulsante, release theilbutton, turn off the
LED, rilasciare LED, but
il pulsante,
also can switch
spegnere thema
il LED, working
anchestate of the lo
cambiare LED every
stato time
del LEDthe button
ogni is pressed.
volta che vieneIn premuto
order to achieve this effect,
il pulsante. you needciò,
Per ottenere to
know when thesapere
è necessario state ofquando
the button
lochanges from
stato del off to on,cambia
pulsante that is, "state changead
da spento detection".
acceso, In this lesson,
ovvero we will print the
il "rilevamento del
cambiamento
results di stato".
of state change In questa
detection lezione,
of the buttonstamperemo i risultati di tale rilevamento. nel monitor seriale.
in the serial monitor.

Componenti Richiesti
Components Required

Pulsante
1 * Button 11 **resistore
10k ohmda 10kΩ
resistor DiversiJumper
Several Jumper Filari
Wires

1 * Mega 2560 Board 1 * Breadboard

Note: Refer
Nota: to Part 2 to check
Fare riferimento details
alla Parte of hardware.
2 per controllare i dettagli dell'harware.

68
Fritzing Circuit

In this example,
questo we use
esempio, pin 2 to
usiamo read
il pin the signal
2 per leggereof the button.del pulsante.
il segnale

69
Schematic Diagram
Diagramma Schematico

Code
Codice

const int buttonPin = 2;


int detectionState = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {

70
if (buttonState == HIGH) {
detectionState=(detectionState+1)%2;
Serial.print("The detection state is:");
Serial.println(detectionState);
}
delay(50);
}
lastButtonState = buttonState;
}

Dopo checodes
After the i codici
are sono statiinto
uploaded caricati nella scheda
the Mega2560 Mega2560,
board, il numero
the output number di
willuscita
switchpasserà
betweentra
00 e 11 ogni
and everyvolta
time che
you
si preme
press il pulsante.
the button.

Analisi
Code del Codice
Analysis

Dichiaraa ilpin
Declare pin connesso
connected toalButton.
Pulsante.

const int buttonPin = 2;

Dichiaraa una
Declare variabile
variable called chiamata [detectionState]
「detectionState」to recordper memorizzare
every state of stateogni modifica
change dello stato.
detection.

int detectionState = 0;

Dichiaratwo
Declare due variabilitoper
variables leggere
read loof
the state stato del pulsante
the button for stateper il rilevamento
change detection. della modifica dello stato.

int buttonState = 0;

71
int lastButtonState = 0;

In setup(), initialize
inizializzathei pin
pinseand thenavvia
quindi start up the serialseriale.
il monitor monitor.

pinMode(buttonPin, INPUT);
Serial.begin(9600);

In loop(), legge il valore


read the value ofdigitale di buttonPin
buttonPin e lo assegna
and then assign alla variabile
to the variable ButtonState.
buttonState.

buttonState = digitalRead(buttonPin);

Compare buttonState
Compara buttonState with
con lastButtonState,
lastButtonState;if se
they
essiare notsono
non equal, it indicates
uguali, indica that thestato
che lo stateè is changed.Un
cambiato. A delay(50)
delay(50)is
è necessario
needed per debouncing
to realize realizzare ilduring
debouncing durante
the changing il rilevamento
detection. dello stato.
After comparison, Dopo
assign il buttonState
the confronto, assegna il
to lastButtonState
buttonState al lastButtonState
to make the next per effettuare il successivo giro di verifica.
round of judgment.

if (buttonState != lastButtonState) {
...
delay(50);
}
lastButtonState = buttonState;

Dopo
The state
la verifica
changedella
judgment
modifica
installed
dello (buttonState
stato (buttonState
!= lastButtonState),
!= lastButtonState),
the further
l'ulteriore
judgment
verifica
is made
vienetoeseguita
get the

condition「Press
per ottenere la condizione「pulsante
the button」. premuto」.

if (buttonState == HIGH) {
...

72
}

Under lo
Sotto thestato「pulsante
state「Press the premuto」,
button」, detectionState is being
detectionState operatedeand
è in funzione it switches
si alterna traabetween 1 and 0.
1 e 0. Nel

mentre, il valore
Meanwhile, di detectionState
the value viene
of detectionState stampato.
is printed.

detectionState=(detectionState+1)%2;
Serial.print("The detection state is:");
Serial.println(detectionState);

Immagine Fenomenologica
Phenomenon Picture

73
1.11 Interval

Overview
Panoramica

Sometimes
Alle volte èyou need to do
necessario two
fare things
due coseatcontemporaneamente.
once. For example you might want to blink
Per esempio an LED while
si potrebbe reading
volere a button press.
il lampeggio di un
LED
In thismentre viene
case, you can'tletta la pressione
use delay(), diArduino
because un pulsante.
pausesIn questo
your caso,
program non the
during si può usare
delay(). delay(),
If the buttonperché Arduino
is pressed while
mette inis paused
Arduino pausa ilwaiting
programma durante
for the delay() il delay().
to pass, Se il pulsante
your program viene
will miss the premuto
button press. mentre Arduino è in pausa
aspettando lo scorrere del delay(), il programma mancherà la pressione del pulsante.
This sketch demonstrates how to blink an LED without using delay(). It turns the LED on and then makes note of the time.
Questo
Then, sketch
each dimostra
time through come
loop(), lampeggiare
it checks to see ifun
theLED senza
desired blinkusare delay().
time has Accende
passed. If it has,ilitLED e poi
toggles the prende nota
LED on or off
dell'ora.
and makesQuindi,
note ofogni voltatime.
the new attraverso loop(),
In this way controlla
the LED se il tempo di
blinks continuously lampeggiamento
while desiderato
the sketch execution è passato.
never lags Se
on a single
è vero, accende e spegne il LED e prende nota del nuovo tempo. In questo modo il LED lampeggia
instruction.
continuamente mentre l'esecuzione dello sketch non perde mai una singola istruzione.
An analogy would be warming up a pizza in your microwave, and also waiting some important email. You put the pizza in
Un'analogia
the microwavesarebbe
and set itriscaldare una The
for 10 minutes. pizza nel tuo
analogy fornodelay()
to using a microonde (vergogna,
would be to sit in frontn.d.t.) e anche aspettare
of the microwave watching
un'importante
the email.from
timer count down Metterai la pizza
10 minutes nel timer
until the micronde e zero.
reaches imposterai quest'ultimo
If the important a 10 minuti.
email arrives L'analogia
during this time you per
will
delay()
miss it. sarebbe stare seduti di fronte al microonde guardando il timer scorrere per 10 minuti finchè esso
raggiunge 0. Se la email importante arrivasse durante questo tempo, la perderesti.
What you would do in real life would be to turn on the pizza, and then check your email, and then maybe do something
Quello che
else (that faresti
doesn't nella
take toovita reale
long!) and(oltre
everyaso
non cuocere
often la come
you will pizza back
nel microonde, n.d.t.),to
to the microwave sarebbe accendere
see if the timer hasla pizza,
reached
zero, indicating
quindi that l'email,
controllare your pizza is done.
e poi forse fare qualcos'altro (che non prenda troppo tempo!) e ogni tanto tornare al
microonde per vedere se il timer ha raggiunto zero, indicando che la pizza è pronta.

74
Components Richiesti
Componenti Required

1 * LED 220ohm Resistor


1 * Resistore 220Ω Several Jumper
Diversi Jumper Wires
Filari

1 * Mega 2560 Board 1 * Breadboard

Nota: Refer
Fare riferimento
to Part 2 toalla
check
Parte
details
2 per of
controllare
hardware.i dettagli dell'harware.

75
Fritzing Circuit

In this
questo
example,
esempio
we use
useremo
digital pin
il pin
9 todigitale
drive the
9 LED,
per guidare
and we attach
il LED,one
e attacchiamo
side of the resistor
un latoto the
del correspond-
resistore al
corrispondente
ing digital pins. pin
The digitale. Il pin
longer pin lungo
of LED del LED electrode,
(a positive (un elettrodo positivo,
referred to aschiamaato
anode) is anodo),
connectedè connesso all'altro
to the other side
capo
of thedel resistore.
resistor. The Ilshorter
pin corto
pin (elettrodo
(a negativenegativo,
electrode,catodo), deltoLED
referred è collegato
as cathode) a terra
of LED (GND). to GND.
is attached

76
Schematic
Diagramma Diagram
Schematico

Code
Codice

const int ledPin = 9;


int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;// save the last time you blinked the LED
if (ledState == LOW) {

77
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}

When you
Finito finish uploading
di caricare the codes
i codici sulla to the
scheda Mega2560
Mega2560, si board, you canilsee
potrà vedere LEDtheaccendersi.
LED uploading.

Code Analysis
Analisi del Codice
Dichiara il pin
Declare the digitale
digital 9 come
pin 9 as ledPin.ledPin.

const int ledPin = 9;

Set the state


Imposta of ledState
lo stato to LOW
di ledState a to
LOWturnper
off spegnere
the LED. il LED

int ledState = LOW;

Initial a variable
Inizializza named previousMillis
una variabile denominatatopreviousMillis
store previous per
operating time of microcontroller.
memorizzare il tempo di funzionamento precedente.

unsigned long previousMillis==0;0;


long previousMillis

Set the interval


Imposta time to
l'intervallo di1000ms
tempo (milliseconds).
a 1000 ms (millisecondi).

const
const long interval =
long interval = 1000;
1000;

78
Set ledPinilto
Imposta OUTPUT
ledPin mode. OUTPUT.
in modalità

pinMode(ledPin, OUTPUT);

declare currentMillis
In loop(), dichiara currentMillistoper
store the current time.
memorizzare il tempo corrente.

unsigned long currentMillis = millis();


When thel'intervallo
Quando interval between the current
tra il tempo operating time corrente
di funzionamento and last updating time
e l'ultimo is larger than 1000ms,
aggiornamento certain
è maggiore difunctions
1000ms, are
alcune funzioni
triggered. sono update
Meanwhile, attivate. Nel
the frattempo, aggiorna
previousMillis il previousMillis
to the current time for the all'ora correntethat
next triggering per isil to
prossimo
happen trigger
1 second
che
latter.deve verificarsi il secondo successivo.
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;// save the last time you blinked the LED
//...
}

Qui certe
Here, funzioni
certain vengono
functions eseguite
executed ad intervalli
at intervals per cambiare
are to change the state ofloLED.
stato del LED.

if (ledState == LOW)
{ledState = HIGH;}
else
{ledState = LOW;}
digitalWrite(ledPin, ledState);

79
Phenomenon
Immagine Picture
Fenomenologica

80
Part 2:2:Component
Parte Componenti
Componenti
2.1 Common Comuni
Component

Overview
Panoramica

This lesson
Questa introduces
lezioni somealcuni
introduce common components,
componenti including
comuni, breadboard,
inclusi jumpjump
breadboard, wires,wires,
resistor, capacitor,
resistori, transistor, diode,
capacitori,
transistori, diodi,and
Prototype Shield Prototype
so on. Shield e via dicendo.

Breadboard
Breadboard
Una breadbord
A breadboard una base dibase
is aè construction costruzione per la of
for prototyping prototipazione dell'elettronica.
electronics. It is È usata
used to build and per creare
test circuits e testare
quickly before
circuiti
finalizingvelocemente, primaAnd
any circuit design. di finalizzare
it has manyqualsiasi progetto
holes into di circuito. like
which components Ha molti buchi
ICs and in cui
resistors as iwell
componenti
as jumpercome
wires
IC e resistori, cosiccome i jumper citati sopra, possono essere inseriti. La breadboard permette di inserire e
mentioned above can be inserted. The breadboard allows you to easily plug in and remove components. So if there are
rimuovere velocemente i componenti. Perciò se ci saranno molti cambiamenti o se si vuole fare un circuito
going to be many changes or if you just want to make a circuit quickly, it will be much quicker than soldering up your
velocemente, è molto più veloce che saldare il circuito. Pertanto, in molti esperimenti, è spesso usata come un
circuit. Therefore in lots of experiments, it is often used as a hub to connect two or more devices.
hub per collegare due o più dispositivi.

81
This is the
Questa è internal structure
la struttura of a full+
interna breadboard.
di una Although
breadboard full+.there are holes
Sebbene on thefori
ci siano breadboard, internally internamente
sulla breadbord, some of them
alcuni
are di essi sono
connected collegati
with metal con
strips. strisce
Those di are
holes metallo. Questi
to insert foridevices
pins of servono ad inserire
or wires. There pin di dispositivi
are four long metalostrips
fili. Cion
sono
the
quattro
long lunghe
sides; strisce
the blue di metallo
and red lines aresui lati lunghi;
marked just forle linee
clear blu e rossa
observation. sono
But you contrassegnate
can take the blueper
linechiarezza
as the GNDgrafica.
and redÈ
comunque
one meglio
as VCC for prendere
convenience. la lina
Every blu come
five holes in theGND e quella
middle rossaconnected
are vertically come VCC permetal
with comodità. Nel mezzo,
trips internally which5don’t
fori
sono collegati
connect verticalmente
with each other. You cancon strisce
connect metalliche
them interne
horizontally che non
with wires si connettono
or components. le une
A groove is con
madeleinaltre. Possono
the middle on
essere
the connesse
breadboard forcon fili o componenti. Una scanalatura è realizzata nella mezzeria per connettere IC.
IC chips.

Jumper Wires
Ponticelli (Jumper Wires)

IWires thatcollegano
fili che connect two
dueterminals aresono
terminali calledchiamati
jumper wires. There are
fili jumper. various vari
Esistono kindstipi
of jumper wires.
di jumper. Here
Qui ci we focus on those
concentriamo su
quelliinusati
used nelle breadboard.
breadboard. Trathey
Among others, gli altri, vengono
are used utilizzati
to transfer per signals
electrical trasferire
fromsegnali elettrici
anywhere on the dabreadboard
qualsiasi punto
to the
della breadboard
input/output pins ofaiapin di ingresso / uscita del microcontrollore.
microcontroller.

Jump wires
I jumper are montati
sono fitted by inserendo
inserting their "end
i loro connectors"
"connettori into the nelle
terminali" slots fessure
provideddella
in the breadboard,albeneath
breadboard, whose
cui interno ci
surface thereset
sono alcuni are di
a few sets parallele
piastre of parallelche
plates that connect
collegano the slots
le fessure in groups
in gruppi di of
filerows
o o or columns
colonne depending
a seconda on the area.
dell'area.

82
IThe "end connectors"
"connettori terminali"are inserted
sono into
inseriti thebreadboard,
nella breadboard, senza
without soldering,
saldatura, in the
negli slot particular
particolarislots
che that need to di
necessitano be
essere connessi
connected nel prototipo
in the specific specifico.
prototype.

Ci sono
There trethree
are tipi divesri
types ofdi jumper
jumper:wire:
Femmina-Femmina, Maschio-Maschio,
Female-to-Female, Maschio-Femmina.
Male-to-Male, and La ragione
Male-to-Female. The percall
reason we cui it
li chiamiamo Maschio-Femmina
Male-to-Female è perché
is because it has the hanno
outstanding tipuna punta
in one end fuoriuscente in un'estremità
as well as a sunk cosiccome means both
female end. Male-to-Male
un'estremità femminile
side are male and infossata all'altra.
Female-to-Female means both ends are female.

Maschio-Femmina
Male-to-Female
Maschio-Maschio
Male-to-Male
Femmina-Femmina
Female-to-Female
Più
Moredithan
un tipo
onepotrebbe essere
type of them mayusato in un
be used in aprogetto. Il colore
project. The dei
color of filijump
the dei jumper diverso,but
wires is èdifferent mait ciò non mean
doesn’t significa
their
che la loro
function funzione
is different differisca;it's
accordingly; serve
just solamente
designed soper identificare
to better identifymeglio le connessioni
the connection betweentra ciascun
each circuit.circuito.

Resistore
Resistor o Resistenza

Un resistore
Resistor un elemento
is an èelectronic elettronico
element that canin grado
limit the di limitare
branch la corrente
current. A fixeddel ramo.
resistor is Un
oneresistore fisso ha una
whose resistance cannot be
resistenza non that
changed, when modificabile, mentre la
of a potentiometer orresistenza di uno
variable resistor canvariabile (es. potenziometro) può essere regolata.
be adjusted.

IThe
resistori in questo
resistors kitare
in this kit sono fissi.
fixed È essenziale
ones. nel in
It is essential circuito proteggere
the circuit i componenti
to protect collegati.
the connected L'immagine
components. The following
seguente mostra
pictures show a realun resistore
220Ω reale
resistor andda 220
two Ω e due
generally simboli
used circuitdisymbols
regola usati negli schemi.
for resistor. Ω is the Ω è l'unità
unit di resistenza
of resistance and the
e le più
larger grandiKΩ,
includes includono
MΩ, etc. KΩ,
TheirMΩ, ecc. La loro
relationship relazione
can be è la
shown as seguente
follows: 1MΩ = KΩ,
1 MΩ=1000 1000KΩ;
1 KΩ 1KΩ = 1000
= 1000 Ω, ilmeans
Ω, which che 1
significa che 1 MΩ
MΩ = 1000,000 Ω = = 10^6
1˙000Ω.
˙000 Ω = 106the
Normally, Ω. resistance
Normalmente la resistenza
is marked scritta
on it. So ifèyou seesu di esso.
these Se vedi
symbols questiit stands
in a circuit,
simboli in un circuito, indicano un resistore.
for a resistor.

83
Theresistenza
La resistance can
puòbeessere
markedcontrassegnata
directly, in color
direttamente, con un The
code, and by character. codice colore,
resistors e con
offered in
caratteri. I resistori
this kit are marked in questo
by different colors.kit sono
Namely,
segnati con on
the bands colori
thedifferenti:
resistor le bande the
indicate sul
resistore
resistance.indicano il valore Ω.

Quando si ausa
When using un resistore,
resistor, dobbiamo
we need to know its
prima conoscere
resistance la sua
first. Here are resistenza. Ci sono
two methods: you
dueobserve
can metodi: si possono
the bands guardare
on the resistor, or usele
a
bande, o to
multimeter utilizzare un resistance.
measure the multimetro
You per
are
misurare la resistenza.
recommended to use theSifirst
consiglia il primo
method as it is
perché
more più conveniente
convenient e If
and faster. veloce.
you areSenot
non si
sure
è sicuri,
about theutilizzare
value, useun multimetro.
the multimeter.

Come
As mostrato
shown nellaeach
in the card, scheda, ogni
color colore
stands for a
rappresenta un numero.
number.

84
Capacitor o Condensatore
Capacitore

The
Il capacitor is a ècomponent
condensatore that hasche
un componente theha
capacity to store
la capacità dienergy in the formenergia
immagazzinare of electrical
sottocharge
formaordi
tocarica
produce
elettrica o difference
a potential di produrre unaVoltage)
(Static differenza di potenziale
between its plates,(tensione
much like astatica) tra le sue piastre,
small rechargeable battery.proprio come
una piccola batteria ricaricabile.
Standard Units of Capacitance
Unità standard di capacità
Microfarad (μF) 1μF = 1/1,000,000 = 0.000001 = 10−6 F
Microfarad (μF) 1μF = 1/1,000,000 = 0.000001 = 10−6 F
Nanofarad (nF) 1nF = 1/1,000,000,000 = 0.000000001 = 10−9F
Nanofarad (nF) 1nF = 1/1,000,000,000 = 0.000000001 = 10−9F
Picofarad (pF) 1pF = 1/1,000,000,000,000 = 0.000000000001 = 10−12F
Picofarad (pF) 1pF = 1/1,000,000,000,000 = 0.000000000001 = 10−12F
Here we shown 104 capacitor(10 x 104PF). Just like the ring of resistors, the numbers on the capacitors help to read the
Qui
valuesmostriamo un condensatore
once assembled onto the board.104 (10×104PF).
The first Come glithe
two digits represent anelli
valuedeiandresistori, i numeri
the last digit sui condensatori
of the number means the
aiutano a leggere il valore una volta assemblati sulla scheda. Le prime due cifre rappresentano il valore e
multiplier. Thus 104 represents a power of 10 x 10 to 4 (in pF) equal to 100 nF.
l'ultima cifra indica il moltiplicatore. Pertanto 104 indica una potenza di 10×10 in 4 (in pF) equivalente a 100nF.
Transistor
Transistore
Transistor is a semiconductor device that controls current by current. It functions by amplifying
Il transistor è un dispositivo a semiconduttore che controlla la corrente tramite corrente.
weak signal to larger amplitude signal and is also used for non-contact switch. A transistor is a
Funziona come amplificatore per segnali deboli ed è anche utilizzato come interruttore
three-layer
senza structure
contatto. Un composed
transistor ha of P-type and N-type
una strattura semiconductors.
a 3 strati composti di They form the three
semiconduttori di
regions
tipo P edinternally.
N. Essi The thinnertre
formano in regioni
the middle is theLa
interne. base
piùregion;
sottilethe other two
al centro è laare both N-type
regione or
di base;
P-type
lea ones
latre due– sono
the smaller region
entrambe di with
tipo intense
N o dimajority
tipo P -carriers is the più
la regione emitter region,
piccola conwhen the
intense
majority
other onecarriers è la regione
is the collector dell'emettitore,
region. This l'altra del
composition enables thecollettore.
transistor toQuesta composizione
be an amplifier.
permette al transistor di essere un amplificatore.

85
Fromqueste
Da these three regions, three
tre regioni, poles rispettivamente
vengono are generated
generati trewhich
respectively, poli,areossia base
base (b), (b), (e),
emitter emettitore (e)(c).
and collector e
collettore
They (c). Essi
form two formano namely,
P-N junctions, due giunzioni P-N,junction
the emitter vale a
dire collection
and la giunzione dell'emettitore
junction. The directioneoflathe
giunzione del
arrow in the
collettore.circuit
transistor La direzione
symbol della freccia
indicates thatnel
of simbolo del
the emitter
transistorBased
junction. in onun
the circuito mostra
semiconductor type, la giunzione
transistors can
dell'emettitore.
be In groups,
divided into two base althe
tipo
NPNdiand
semiconduttore,
PNP ones. Fromi
transistor
the possono
abbreviation, essere
we can divisi
tell that thein due isgruppi,
former made ofquelli
two
NPN e semiconductors
N-type PNP. Dall'abbreviazione,
and one P-typepossiamo
and thatdire
the che
latteril
primo
is è fatto di
the opposite. due
See thesemiconduttori
figure below. di tipo N e uno di
tipo P e che il secondo è l'opposto. Confrontare la
When a High level signal goes through an NPN transistor, it
figura a fianco.
is energized. But a PNP one needs a Low level signal to
Quandoit.un segnale di livello high passa attraverso un
manage
transistor NPN, viene energizzato. Mentre un PNP
necessita un livello di segnale low per gestirlo.

86
Diode
Diodo

A diode
Un diodo is a
è two-terminal
un componente component in electronics
a due terminali with a unidirectional
in elettronica flow of
con un flusso current. It offers
unidirezionale low resistance
di corrente. Offreinuna
the
bassa resistenza
direction of currentnella
flow direzione del flusso
and offers high di corrente
resistance e offredirection.
in the opposite un'elevata resistenza
Diodes nella
are mostly direzione
used opposta.
to prevent damageI
diodi
to sono utilizzati
components, principalmente
especially per prevenire
due to electromotive danniwhich
force in circuits ai componenti, in particolare a causa della forza
are usually polarized.
elettromotrice nei circuiti che di solito sono polarizzati.

IThe
duetwo terminalsdiofun
terminali a diode
diodoare polarized,
sono with the
polarizzati, positive
con end called
l'estremità anode
positiva and the negative
chamata anodo eend called cathode.
la negativa The
chiamata
catodo. Il usually
cathode is catodomade
è solitamente
of silver orfatto
has adicolor
argento
band.oControlling
ha una banda colorata.of
the direction Il current
controllo della
flow direzione
is one delfeatures
of the key flusso
di corrente
of diodes una
— èthe delleincaratteristiche
current chiave
a diode flows from deltodei
anode diodi The
cathode. — la corrente
behavior of aindiode
un diodo fluisce
is similar to thedall'anodo
behavior ofal
a
catodo. Il comportamento
check valve. di un diodo
One of the most important è simile of
characteristics al acomportamento di una
diode is the non-linear valvola
current di ritegno.
voltage. If higherOna delle
voltage is
caratteristiche
connected to thepiù importanti
anode, del flows
then current diodofrom
è laanode
tensione non lineare.
to cathode, and the Se una istensione
process known aspiù elevata
forward applicata
bias.èHowever, if
all'anodo, allora lais corrente
the higher voltage connectedfluisce
to thedall'anodo al catodo,
cathode, then e does
the diode il processo è detto
not conduct polarizzazione
electricity, diretta (foward
and the process is called
bias).
reverseTuttavia,
bias. se la tensione più elveata è collegata al catodo, il diodo non conduce elettricità e il processo è
chiamato polarizzazione inversa (reverse bias).

87
Prototype Shield

The Prototype
La PrototypeShield makes
Shield it easy for
("Scudo you to design custom
Prototipale") circuits.
semplifica la
progettazione di circuiti
You can solder parts to the personalizzati.
prototyping areaSitopossono saldare
create your le
project,
parti
or usenell'area di prototipazione
it with a Tiny breadboard to per creare
quickly test il proprio
circuit ideasprogetto
without
e usarlo
having to con una
solder. It's breadboard Tiny perfor
got extra connections testare rapidamente
all of the Arduino I/Oi
circuiti
pins, anddiit's
prova senzato
got space dover saldare.
mount Ha connessioni
through-hole extra
and surface per
mount
tutti i pincircuits.
integrated I/O diIt'sArduino e haway
a convenient spazio peryour
to make montare
customcircuiti
circuit
integrati a into
and Arduino foroa passante e a montaggio superficiale. È un
single module.
modo conveniente per realizzare circuiti personalizzati e
Specifications
Arduino in un modulo singolo.
 It can be overlayed on the Sunfounder Mega2560 board directly.
Specifiche
A Tiny breadboard is provided, which you can use to do some
Può experiments.
 simple essere sovrapposto direttamente sulla scheda
Sunfounder Mega2560. Viene fornita anche una breadbord
 Provide a footprint for SOP28. Tiny, che può essere utilizzata per fare alcuni semplici
esperimenti.
 It's got extra connections for all of the Arduino I/O pins
 Fornisce una footprint per SOP28.
 We offer you pin22-pin53 bonding pad and you can use it to weld the component directly.
 Ha connessioni extra per tutti i pin I/O Arduino.

 Ti offriamo il bonding pad pin22-pin53 e puoi usarlo per saldare direttamente il componente.

88
2.2 LED

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai ad to use LED.i LED
utilizzare LED.isUn
a kind
LEDof
è common
una sortalight-emitting device that di
di comune dispositivo works according
emissioni to the
luminosa
che lavora
principle secondo
that il principioofche
the recombination la ricombinazione
electron degli
and hole releases elettroni
energy rilascia
to give energia
out light. e determina
This component emissione
is used widely di
in
luce.
the Questo
current componente
society, è molto utilizzato
such as illumination, nella società
panel display, medical attuale (illuminazione,
device and so on. display, disp. medici, ecc.).

Componenti Richiesti
Components Required

1 * LED ResistoreResistor
1 * 220ohm 220Ω Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

89
Component Introduction
Introduzione del Componente

Semiconductor
Il light-emitting
diodo semiconduttore diode is aluminosa
a emissione type of component
è un tipo diwhich can turn che
componente electric
puòenergy into light
trasformare energyelettrica
l'energia via PN
in energiaByluminosa
junctions. tramite
wavelength, it cangiunzioni PN. A into
be categorized seconda della lunghezza
laser diode, d'onda, può
infrared light-emitting essere
diode andclassificato in diodo
visible light-emitting
laser, which
diode diodoisad emissione
usually infrarossa
known as e diodo
light-emitting diodead emessione di luce visibile, noto come diodo a emissione
(LED).
luminosa (LED).

Il diodo
Diode haunidirectional
has una conduttività unidirezionale,
conductivity, quindiflow
so the current il flusso dias
will be corrente sarà
the arrow come indica
indicates la circuit
in figure frecciasymbol.
nel simbolo.
You can
È
possibile fornire
only provide all'anodo
the anode with asolo una power
positive tensione
andpositiva e al catodo
the cathode una negativa.
with a negative. Così
Thus the LEDilwill
LEDlight
si accenderà.
up.

Il
AnLED
LED ha
hasdue
two pin.
pins. IlThe
più lungo
longer l'anodo
è is
one e il and
the anode, più shorter
corto èone,
il catodo. Presta
the cathode. Payattenzione a to
attention not non connetterli
connect them
inversamente.
inversely. There C'è unaforward
is fixed caduta voltage
di tensione
drop (diretta) fissa
in the LED, so nel LED, per
it cannot cui non può
be connected withessere connesso
the circuit direttamente
directly because the
al circuito
supply poiché
voltage la tensione
can outweigh thisdidrop
alimentazione può
and cause the superare
LED questa
to be burnt. Thecaduta
forwardevoltage
causareof la
thebruciatura
red, yellow,del
andLED. La
green
tensione
LED is 1.8 diretta del of
V and that LEDtherosso,
white giallo
one is e2.6
verde è diLEDs
V. Most 1,8 can
V e withstand
di quello abianco di 2,6V.
maximum La of
current maggior
20 mA, parte
so we dei
needLED
to
possono
connect a sopportare unaresistor
current limiting corrente massima di 20mA, per cui è necessario collegare un resistore in serie.
in series.

La
Theformula
formulaper il valore
of the di resistenza
resistance la seguente:
value is as èfollows:

R = (Vsupply – VD)/I

90
sta per for
R stands il valore di resistenza
the resistance del
value ofresistore chelimiting
the current limita laresistor,
corrente, Vsupplyfor
Vsupply per tensione
voltage di alimentazione,
supply, VD for voltageVDdrop
per
and I for
caduta dithe working
tensione e I current of thediLED.
per corrente funzionamento del LED.

If
Sewe provide 55voltage
forniamo forilthe
Volt per LEDred LED, the
rosso, minimum
la minima resistanceper
resistenza of the current limiting
il resistore resistor should
di limitazione be: (5V-1.8v)/20mA
della corrente dovrebbe
essere
= 160Ω.(5V-1,8V)/20mA=160Ω. Si consiglia
Therefore, you need a 160Ω di utilizzare
or larger resistor i resistori
to protect da You
the LED. 220Ωareofferti nel kit. to use the 220Ω resistor
recommended
offered in the kit.
Diagramma Schematico
Schematic Diagram

Fritzing Circuit

In this example,
questo we use
esempio, pin 9 to
usiamo drive
il pin 9 LED. Insert one
per guidare side of
il LED. the resistor
Inserire in theestremità
una delle digital pindel
9 and connectnel
resistore thepin
longer pin (a
digitale 9
e connettere
positive il pin
electrode, più lungo
referred to as (un elettrodo
anode) positivo,
of the LED denominato
with the anodo)
other side of del LED
the resistor. con the
Extend l'altro latopin
shorter del(aresistore.
negative
Estendere il pin più
electrode, referred to corto (un elettrodo
as cathode) of the LEDnegativo,
to GND. denominato catodo) del LED a terra (GND).

91
Code
Codice

Example 1:
Esempio 1:

const int ledPin = 9;

void setup() {

92
pinMode(ledPin, OUTPUT);
}

void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin,LOW);
delay(1000);
}

Finito di uploading
Finished caricare i codici
the codes
sullatoscheda
the Mega2560
Mega 2560,
board,
si può
you can
osservare
see theilLED
LEDflashing.
lampeggiare.
Refer to
Fare
Part
riferimento
1-1.2 alla
Digital1-1.2
Parte Write to check
Digital theper
Write detail code explanation.
controllare la spiegazione in dettaglio del codice.

Example 2:
Esempio 2:

int ledPin =
=9;
9;
setup() {{
void setup()
}
void loop() {
for (int value = 0 ; value <= 255; value += 5) {
analogWrite(ledPin, value);
delay(30);
}

93
}

After uploading
Dopo the codes
aver caricato to the sulla
i codici Mega2560 board,
scheda you can see
Mega2560, si the
puòLED getting brighter,
osservare il LED then turningpiù
diventare off, getting brighter,
luminoso, poi
spegnersi,
then turningdiventare più luminoso,
off again...this quindi spegnersi
loop will continue ancora...
in this way. questo
About the ciclo
detail continueràà
code explanation,inplease
questo modo.
refer Per1-1.3
to Part una
spiegazione
Analog Write.nel dettaglio del codice, si prega di confrontare la Parte 1-1.3 Analog Write.

Immagine Fenomenologica
Phenomenon Picture

94
2.3 RGB LED

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imparerai how to
ad usare use RGB
il LED RGB.LED. A RGB
Un LED LED
RGB packagestre
racchiude three LEDs
LED, in red,
rosso, greene and
verdre blu, blue
in uninto one
unico
guscio di plastica
transparent traspadrente
or semitransparent o semitrasparente.
plastic shell. It displays aMostra una vasta
broad array gamma
of colors di colori
by changing themodificando
input voltagelaoftensione
three pins
di
andingresso
adding dei
the tre pincolors
three e unendo i tre in
together colori insieme
different in As
ways. modi diversi.
is said in a Ilstatistic,
LED RGB può
RGB creare
LED 16˙77716,777,216
can create ˙216 coloridifferent
differenti.
colors.

Componenti
Components Richiesti
Required

1 ** RGB
1 RGB LED
LED 3 ** 220
3 Resistore 220 Ω
ohm resistor Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

95
Component Introduction
Introduzione del Componente

IRGB
LEDLEDs can
RGB. be categorized
possono essere into commoncome:
classificati anodead
andanodo
common cathode
comune o ones. In thiscomune.
a catodo experiment, the latter
In questo is used. The
esperimento
common cathode,quest'ultimo.
viene utilizzato or CC, means to
Il connect
catodo the cathodes
comune, of the
o CC, three LEDs.
significa After you
collegare connect
insieme it with
i tre GNDdei
catodi andLED.
plug Dopo
in the
three pins,
averlo the LEDcon
collegato will GND
flash the corresponding
e collegato i 3 pincolor.
alla scheda, il LED lampeggerà con il colore corrispondente.

LED RGB
RGB LED Simbolo del circuito
Circuit Symbol

Un LED LED
An RGB RGBhas
ha 44pins:
pin: the
il più lungoone
longest è GND; glithe
is GND; altriothers
sonoare
Rosso,
Red, Verde e Blu.
Green and Tocca
Blue. il guscio
Touch di shell
its plastic plastica e troverai
and you will find
a cut.scalfitura.
una The pin closest
Il pinto the
più cut isèthe
vicino first pin,ed
il primo, marked as Red,
è il Rosso, then
poi GND, Green
in ordine GND,and BlueeinBlu.
Verde turn.

96
Or you can
Oppure distinguish
puoi themininun
distinguerli another way. AsPoiché
altro modo. GND isGND
the longest
è il piùone and e
lungo can be essere
può defineddefinito
directly, you just need to
direttamente, è
sufficiente
confirm the confermare gli altri
other three pins. You tre
can pin. Puoi
test it testarli
by giving dandogli
them a smalluna piccola
voltage. Thetensione. La caduta
forward voltage dropdi tensione
from diretta
the three pins
dai treGND
to the pin are
a terra sono rispettivamente
respectively 1.8V (rosso),
1.8V (red), 2.5V (blue), 2.5(blu)
and 2.3V (green).eThus,
2,3 (verde).
when youCosì, quando
connect si collega
the same lo limiting
current stesso
resistore con
resistor with i tre
the pinpins
three e siand
alimentano con
supply them lo stesso
with voltaggio,
the same il rosso
voltage, the è più
red one luminoso,
is the brightest,poi
andviene il verdethe
then comes e infine
green
il
andblu.
thePertanto
blue one.potresti dover
Therefore, youaggiungere
may need todei
addresistori
a currentdilimiting
limitazione con
resistor resistenze
with diverse per
different resistances toogni colore.
the three pins for
these colors.
Fritzing Circuit
Fritzing Circuit
Qui forniamo ai tre pin del LED RGBun valore
compreso tra 0
Here we input e 255between
a value per mostrare
0 and colori
255 todifferenti.
the three
Dopo
pins ofaver connesso
the RGB LED toi make
pin diit R, G e Bdifferent
display ai resistori di
colors.
limitazione
After connectingdella corrente,
the pins of R, G,connetterli rispet-
and B to a current
tivamente ai pin
limiting resistor, 9, 10 e
connect 11. to
them Il più
the lungo (GND)
pin 9, pin del
10, and
LED si respectively.
pin 11 collega al GND della Mega2560.
The longest pin (GND) ofQuando
the LEDi
tre pin sono
connects to theforniti
GND ofdi the
differenti valori
Mega 2560. PWM,
When theilthree
LED
RGB mostrerà
pins are colori differenti.
given different PWM values, the RGB LED will
display different colors.

97
Schematic Diagram
Diagramma Schematico

Code
Codice

NOTE: una
NOTA: A piccola
small porzione
portiondei codici
of the codesSi prega
è omessa. are di
omitted. Please
controllare i codicicheck
completithe complete codes
(sunfounder_vincent_kit_for_arduino\code\2.3rgbLed\2.3rgbLed.ino) in
nell'IDE Arduino.
Arduino IDE.

const int redPin = 11;


const int greenPin = 10;
const int bluePin = 9;
void setup()
{
pinMode(redPin, OUTPUT); // sets the redPin to be an output
pinMode(greenPin, OUTPUT); // sets the greenPin to be an output
pinMode(bluePin, OUTPUT); // sets the bluePin to be an output

98
}
void loop() // run over and over again
{
color(255, 0, 0); // turn the RGB LED red
delay(1000); // delay for 1 second
color(0,255, 0); // turn the RGB LED green
delay(1000); // delay for 1 second
color(0, 0, 255); // turn the RGB LED blue
delay(1000); // delay for 1 second
// ...
}
void color (unsigned char red, unsigned char green, unsigned char blue)// the color generating function
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

Caricati
Uploaded i codici nellainto
the codes scheda Mega2560,
the Mega2560 è possibile
board, you canosservare checolor
see that the il colore
of thedel
RGBLED RGB
LED varia una
changes oncevolta al
a second.
secondo.

99
Code Analysis
Analisi del Codice

In this example,
questo the function
esempio, usedusta
la funzione to assign values to the
per assegnare three
valori pinspin
ai tre of RGB is packaged in
è racchiusa in an
unaindependent subfunction
sottofunzione
indipendente
color(). color().

void color (unsigned char red, unsigned char green, unsigned char blue)// the color generating function
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

In loop(), iRGB
valori RGBworks
value funzionano come
as an input un argomento
argument perfunction
to call the chiamare la funzione
color() color()
to realize per RGB
that the far sìcan
cheemit
RGBdifferent
possa
emettere
colors. differenti colori.

void loop() // run over and over again


{
color(255, 0, 0); // turn the RGB LED red
delay(1000); // delay for 1 second
color(0,255, 0); // turn the RGB LED green
delay(1000); // delay for 1 second
color(0, 0, 255); // turn the RGB LED blue
delay(1000); // delay for 1 second
// ...

100
}

Phenomenon
Immagine Picture
Fenomenologica

101
2.4 LED Bar Graph

Overview
Panoramica
In questa lezione imparerai qualcosa riguardo i Grafici a Barre LED. Generalmente, il LED Bar Graph funziona
In this lesson, you will learn something about LED Bar Graph. Generally, LED Bar Graph works as a battery level indicator,
come indicatore del livello della batterial, apparecchiature Audio, pannelli di controllo industriale. Volendo si
Audio equipment, industrial control panel. If we want, we can also find its other application.
possono trovare altre applicazioni.

Components Required
Componenti Richiesti
1 * LED Bar Graph 1 * 220ohm
ResistoreResistor
220Ω SeveralJumper
Diversi Jumper Wires
Filari

1 * Mega 2560 Board 1 * Breadboard

102
Component Introduction
Introduzione del componente

LED
Il BarBar
LED Graph is an èLED
Graph unarray,
arraywhich is used
di LED, to connect
utilizzato with
per electronic circuit
connetersi or microcontroller.
con circuito elettronicoIt’soeasy to connect LED
microcontrollore.
Collegare
bar il LED
graph with the Bar Graph
circuit like ascon il circuito
connecting è facile LEDs
10 individual comewith
collegare 10pins.
10 output LED individuali con 10 pin di output.

Nota: L'anodo
Note: The il the
è is
anode latoside
conwith
la scritta
a label(1-10).
(1-10).

103
Fritzing Circuit

In this example,
questo we useuseremo
esempio digital pins
122~11
pin to drive the
digitali LEDper
2~11 Bar Graph.
guidareLED
il Bar
LEDGraph has ten separate
Bar Graph. Esso ha LEDs
dieciinside
LED and each
separati
all'interno
LED has twoed ogni
pins. LED
The leftha due
pins pin.ofI LED
1~10 pin Bar
sinistri
Graph1~10
are del LED Barwith
connected Graph sono collegati
the digital pins 2~11rispettivamente con iside
respectively; the right pin
digitali
pins 2~12;
11~20 areiseparately
pin sul lato destro to
extended 11~20
same sono estesi
side of theseciascuno allo stesso
220ohm resistors latoother
whose di questi
sides resistori da 220Ω
are identically le cui
connected
estremità
to GND. sono collegati identicamente a terra (GND).

104
Schematic Diagram
Diagramma Schematico

Code
Codice

void setup() {
for(int i=2;i<=11;i++)
{
pinMode(i,OUTPUT);
}
}

void loop() {

105
for(int i=2;i<=11;i++)
{
digitalWrite(i,HIGH);
delay(500);
digitalWrite(i,LOW);
delay(500);
}
}

Caricati i codici
Uploaded sulla to
the codes Mega2560, è possibile
the Mega2560 board,vedere chesee
you can i LED sul
that LED
the Baron
LEDs Graph lampeggiano
the LED Bar Graphinflash
sequenza.
in sequence.

Code Analysis
Analisi del Codice
The codes
I codici in setup()
in setup() use the
utilizzano il for loop
ciclo for to
perinitialize pins i2~11
inizializzare to output
pin 2~11 mode in output,
nella modalità turn. uno alla volta.

for(int
for(int i=2;i<=11;i++)
i=2;i<=11;i++)
{
pinMode(i,OUTPUT);
}

Il
Theciclo
forfor viene
loop utilizzato
is used into
in loop() loop()
makeper
thefar
LEDlampeggiare
flash(turn onil0.5s,
LEDthen
(attivare 0,5s,
turn off quindi
0.5s) disattivare 0,5s) in sequenza.
in sequence.

for(int i=2;i<=11;i++)
{
digitalWrite(i,HIGH);

106
delay(500);
digitalWrite(i,LOW);
delay(500);
}

Refer
Ci si riferisca
to Part 1-1.2
alla Digital
Parte 1-1.2
WriteDigital
for more
Write
details
per about
più dettagli
controlling
riguardo
the LED
il controllo
by using digital
dei LEDpins.
usando pin digitali.

Immagine Fenomenologica
Phenomenon Picture

107
2.5 7-Segment Display

Overview
Panoramica

In this lesson,
questa you will
lezione learn something
imparerai qualcosaabout 7-Segment
sul display a 7 Display.
segmenti.7-Segment
Esso haDisplay has so
così tanti many advantages
vantaggi that it is
che è largamente
usato in
widely strumenti
used elettrici,
in electrical specialmente
equipments, in inelettrodomestici
especially che mostrano
household appliances informazioni
that display numeriche,such
numerical information, come
as
display,air
display, condizionatori, scaldabagno,
conditioner, water frigoriferi
heater, refrigerator ande so
viaon.
dicendo.
LEDs onI the
LED7-Segment
sul display a 7 segmenti
Display emit light emettono luce
by the input of
all'ingresso
different di diversi
electrical segnali
signals to theelettrici
differentnei variofpin
pins presenti.
it. The Le informazioni
numerical information itnumeriche
can displayche può visualizzare
includes time, date,
includono ora,
temperature anddata, temperatura e così via.
so on.

Componenti Richiesti
Components Required

1 * 7-Segment
Display a 7Display
Segmenti 88 ** 220
Resistore 220 Ω
ohm resistor DiversiJumper
Several JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

108
Component Introduction
Introduzione del Componente

A 7-segment
Un display a display is an 8-shaped
7 segmenti component awhich
è un compornente formapackages 7
di 8 che
racchiude
LEDs. Each 7LED
LED.is Ogni
calledLED è chiamato
a segment – segmento – quando
when energized, one
ha energia,
segment esso
forms forma
part parte dito
of a numeral unbenumero da mostrare.
displayed.

Ci sono
There aredue
twotipi di of
types pinpin
di connection:
connessione: a Catodo
Common Comune
Cathode (CC)(CC)
and
o ad Anodo
Common Comune
Anode (CA). As (CA). Come
the name suggerisce
suggests, il nome,
a CC display has un
all
display CC ha
the cathodes oftutti
the 7i LEDs
catodi dei 7 LED
connected connessi,
when mentre
a CA display hasun CA
all the
ha tuttiof
anodes glithe
anodi connessi.
7 segments In questo
connected. In kit
thisusiamo il primo.
kit, we use the former.

Ad
Eachognuno dei LED
of the LEDs neldisplay
in the displayis viene
given aassegnato
positional un segmento
segment with
posizionale con uno dei
one of its connection pins suoi pin from
led out di connessione che plastic
the rectangular esche
dal pacchetto
package. These inLED
plastica rettangolare.
pins are labeled fromQuesti pin LEDtosono
"a" through "g"
contrassegnati
representing dalla
each "a" fino
individual alla
LED. The"g", rappresentando
other ogni singolo
LED pins are connected LED.forming
together Gli altria LED sono pin.
common collegati
So by fra loro
forward
biasing
formandothe appropriate pins ofQuindi,
un pin comune. the LEDalimentando
segments in a iparticular order, some
pin appropriati dei segments
segmentiwill
LED brighten
in un and others
ordine stay dim,
particolare,
thus showing
alcuni the corresponding
segmenti character
si illumineranno onrimarranno
ed altri the display. affievoliti, mostrando così il carattere corrispondente sul

display.

109
Fritzing Circuit

Connect eachciascun
Connettere of pin a-g
pinofa-g
thedel
7-Segment
Display
a 7 segmenti
Display to one con una current
220ohm resistenza da
limiting
220Ω erespectively
resistor poi ai pinand 4-11.
then toIl pin
GND è
4–11.
connesso
GND con to
connects il GND.
GND.

Il cablaggio
The tra il display
wiring between a 7 segmenti
the 7-segment e
display
la scheda
and Mega2560
the Mega2560 mostrato
è as
board sotto::
shown below

7-Segment Mega2560 Board


a 7
b 6
c 5
d 11
e 10
f 8
g 9
dp 4
“- “ GND

110
Schematic Diagram
Diagramma Schematico

111
Code
Codice

NOTE: AUna
NOTA: small portion
piccola of the codes
porzione are omitted.
dei codici PleaseSicheck
è omessa. pregathe
dicomplete codes
controllare by opening
i codici 2.5_7segment.ino
completi aprendo in path of
2.5_7segment.ino presente nel percorso sunfounder_vincent_kit_for_arduino\code\2.5_7segment
sunfounder_vincent_kit_for_arduino\code\2.5_7segment in Arduino IDE. nell'IDE Arduino.

const int
int a=7;
a=7;//a
//aof
of7-segment
7-segmentattach
attachtoto digital
digital pin
pin 7 7
const int b=6;
b=6; //b
//bof
of7-segment
7-segmentattach
attachtotodigital
digitalpin
pin
66
const int
int c=5;
c=5;//c
//cofof7-segment
7-segmentattach
attachtoto digital
digital pinpin
5 5
const int d=11;//d of 7-segment attach to digital pin 11
const int e=10;//e of 7-segment attach to digital pin 10
const int f=8;//f of 7-segment attach to digital pin 8
const int g=9;//g of 7-segment attach to digital pin 9
const int dp=4;//dp of 7-segment attach to digital pin 4

void setup()
{
//loop over thisPin from 4 to 11 and set them all to output
for(int thisPin = 4;thisPin <= 11;thisPin++)
{
pinMode(thisPin,OUTPUT);
}
digitalWrite(dp,LOW);//turn the dp of the 7-segment off

112
}

void loop()
{
digital_1();//diaplay 1 to the 7-segment
delay(1000);//wait for a second
digital_2();//diaplay 2 to the 7-segment
delay(1000); //wait for a second
digital_3();//diaplay 3 to the 7-segment
delay(1000); //wait for a second
//...
}

void digital_1(void) //diaplay 1 to the 7-segment


{
digitalWrite(c,HIGH);//turn the c of the 7-segment on
digitalWrite(b,HIGH);//turn the b of the 7-segment on
for(int j = 7;j <= 11;j++)//turn off the others
digitalWrite(j,LOW);
}
void digital_2(void) //diaplay 2 to the 7-segment
{

113
//...
}
void digital_3(void) //diaplay 3 to the 7-segment
{
//...
}
//...

Oncevolta
Una upload the codes,
caricati you si
i codici, can seevedere
può the 7-segment display
il display 7-seg.displaying
mostrare1,1,2,3,4,5,6,7,8,9,A,b,C,d,E,F
2, 3, 4, 5, 6, 7, 8, 9, A, b, C, d, E,
in Fsequenza.
in sequence.

Code Analysis
Analisi del Codice

Takeai
Dai the pin numbers
numeri dei pinon 7-segment
dei as names,
7 segmenti andedeclare
dei nomi, the pins
dichiarali sullaon the Mega2560
scheda board.
Mega2560.

const int a=7; //a of 7-segment attach to digital pin 7


const int b=6; //b of 7-segment attach to digital pin 6
const int c=5; //c of 7-segment attach to digital pin 5
const int d=11;//d of 7-segment attach to digital pin 11
const int e=10;//e of 7-segment attach to digital pin 10
const int f=8;//f of 7-segment attach to digital pin 8
const int g=9;//g of 7-segment attach to digital pin 9
const int dp=4;//dp of 7-segment attach to digital pin 4

114
Install a series
Installa of subfunctions
una serie to package
di sottofunzioni the level state
per racchiudere at each
lo stato di block during the
ogni blocco pernumber display of the
la visualizzazione del7-segment.
numero sulFor
7-seg. Per
example, esempio,
when quando「2」
the character il [2] is mostrato,the
è displayed, il blocco
block Ffand
e il the
blocco c csono
block spenti.
are turn Gli altri
off; the othersono illuminati.
blocks are lit up.

First we need to
Innanzitutto know howsapere
dobbiamo it looks like
come when displayil the
appare 2 2sul
numeral
numero on display
the 7-Segment display. It'sInactually
a 7 segmenti. realtà the segments
sono accesia,i
b, d, e anda,
segmenti g are
b, d,power
e, g, generando il 2. Nella
on, which generates display of 2. In programming,
theprogrammazione pinsaconnected
i pin connessi to thesesono
questi segmenti segments are set
impostati a
High level
livello whenmentre
High, c and f are
c eLow level. Here
f sono a livello a for()Qui
we useLow. statement
usiamoto set these pins asfor()
un'istruzione Highper
levelimpostare
respectivelyquesti
(the braces
pin
after for() are deleted
rispettivamente a livello High
as there (le parentesi
is only graffe dopo
one line). Connect for()
pin dp sono
to pin eliminate
4; it's in quanto
already defined in setup()
è presente
as LOW una. sola riga).
Connetti il pin dp al pin 4; è già definito come LOW in setup().
After running this part, the 7-segment will display 2. Similarly, the display of other characters are the same. Since the
Eseguendo
letters b andildcodice, il 7case,
in upper seg.namely
mostrerà 2. La
B and D,visualizzazione degli altri
would look the same with caratteri è lathe
8 and 0 on stessa. Poichè
display, le lettere
they are b e in
displayed d
in maiuscolo,
lower ossia B e D, sarebbero uguali a 8 e 0 sul display, sono invece mostrate in minuscolo.
case instead.

...
void digital_2(void) //diaplay 2 to the 7-segment
{

115
digitalWrite(b,HIGH);
digitalWrite(a,HIGH);
for(int j = 9;j <= 11;j++)
digitalWrite(j,LOW);
digitalWrite(c,LOW);
digitalWrite(f,LOW);
}
...

In loop(),
loop(), call the function
chiama that displays
la funzione the number.
che mostra il numero.

void loop()
loop()
{
digital_1();//diaplay 1 to the 7-segment
delay(1000);//wait for a second
digital_2();//diaplay 2 to the 7-segment
delay(1000); //wait for a second
digital_3();//diaplay 3 to the 7-segment
//...
}

116
Phenomenon
Immagine Picture
Fenomenologica

117
2.6 74HC595

Overview
Panoramica
In questa
In this lezione
lesson, imparerai
you will ad to
learn how usare
use il 74HC595.
74HC595. Esso è consists
74HC595 costituito
of da un registro
an 8−bit di spostamento
shift register a 8 register
and a storage bit e dawith
un
registro di memoria con uscite parallele a 3 stati. Converte l'ingresso seriale in parallelo in modo da ridurre il
three−state parallel outputs. It converts serial input into parallel output so you can save IO ports of an MCU.
numero di porte necessarie dell'MCU.
Components Required
Componenti Richiesti
1 * 74HC595 8 * LED 8 * Resistore 220 Ω
220 ohm resistor Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

118
Component Introduction
Introduzione del Componente

When
Quando MR MR (pin10)
(pin10)isèhigh levelhigh
a livello andeOE OE(pin13)
(pin13) is low
è low,
level,
il datodata is inputnel
è immesso in inthe rising
bordo edge of SHcp
ascendente di SHcp and e
goes
va alto registro
the memory di register
memoriathrough the rising
attraverso edge
il bordo
of
ascendente
SHcp. If the di SHcp.
two clocks
Se i due are clock
connected
sono together,
connessi
the
insieme,
shift register
il registrois always
di spostamento
one pulse earlier
è sempre
than the un
memory
impulso in register.
anticipo Theredel isregistro
a serialdishift
memoria.
input pin C'è(Ds),
un
a
pinserial
per l'input
outputseriale
pin (Q) (Ds),and
unoan perasynchronous
l'output seriale reset
(Q)
button
e un pulsante
(low level)per inil the
resetmemory
asincronoregister.
(livello
Thelow)
mem- nel
ory register
registro outputs aQuest'ultimo
di memoria. Bus with a parallel
emette8-bit
un Busand conin
three
un parallelo
states. Whena 8-bit OE eis inenabled
tre stati.
(low Quando
level), theOE data è
in memory
abilitato register
(livello low),isiloutput
dato nel to registro
the bus. di memoria è
Pin del f 74HC595 e rispettive funzioni: emesso dal bus.
Pins of 74HC595 and their functions:
Q0-Q7: pin per l'output parallelo a 8-bit, in grado di controllare direttamente 8 LEDs o 8 pin di un display 7-seg.
Q0-Q7: 8-bit parallel data output pins, able to control 8 LEDs or 8 pins of 7-segment display directly.
Q7’: pin per l'output seriale, connesso al DS di un altro 74HC595, per connettere molteplici 74HC595s in serie.
Q7’: Series output pin, connected to DS of another 74HC595 to connect multiple 74HC595s in series
MR: pin di reset, attivo a livello low;
MR: Reset pin, active at low level;
SHcp: sequenza temporale per il registro di spostamento. Al bordo ascendente, il dato nel registro di
SHcp: Time sequence
spostamento si muoveinput of shift di
traslando register.
un bit,On
es.the risinginedge,
il dato the data
Q1 passa in shift
in Q2, register
e così moves successively
via. Mentre sul bordo one bit, i.e.
data in Q1imoves
discendente, to registro
dati nel Q2, and sodi forth. While onrimangono
spostamento the falling edge, the data in shift register remain unchanged.
immutati.

STcp: Time sequence


Sequenza input
temp. perofil storage register. OnAl
reg. di memoria. the risingasc.,
bordo edge,i dati
datanel
in the shift
reg. di register movesnel
spost. vanno intoreg.
memory register.
di memoria.

OE: pin
Output enable pin, active
di abilitazione at low level.
dell'output, attivo a livello low.

119
DS: pin didata
Serial input seriale.
input pin

VCC: tensione di alimentazione


Positive supply voltage positiva.

GND: terra.
Ground

Fritzing Circuit

In this
questo esempio
example, usiamo to
we use 74HC595 il
74HC595 per
control LED. controllare
Give each datai output
LED. Dare
pin
a ogni pin
( Q0-Q7 ) a (Q0-Q7)
220 ohm un resistore
resistor then
220Ω e them
connect connetterlo
to LED. alTheLED. La
wiring
tabella diis cablaggio
diagram as follows: è la seguente:

74HC595 Mega Board


MR(10) 5V
SHcp(11) 8
STcp(12) 12
OE(13) GND
DS(14) 11
VCC(16) 5V

GND(8) GND

120
Schematic Diagram
Diagramma Schematico

121
Code
Codice

const int STcp = 12;//Pin connected to ST_CP of 74HC595


const int SHcp = 8;//Pin connected to SH_CP of 74HC595
const int DS = 11; //Pin connected to DS of 74HC595
int datArray[] = {B00000000, B00000001, B00000011, B00000111, B00001111, B00011111, B00111111, B01111111,
B11111111};

void setup()
{
//set pins to output
pinMode(STcp,OUTPUT);
pinMode(SHcp,OUTPUT);
pinMode(DS,OUTPUT);
}
void loop()
{
for(int num = 0; num <=8; num++)
{
digitalWrite(STcp,LOW); //ground ST_CP and hold low for as long as you are transmitting
shiftOut(DS,SHcp,MSBFIRST,datArray[num]);
//return the latch pin high to signal chip that it

122
//no longer needs to listen for information
digitalWrite(STcp,HIGH); //pull the ST_CPST_CP to save the data
delay(500); //wait for a second
}
}

Finito di caricare
When you i codici sulla
finish uploading scheda
the codes Mega2560,
to the si possono
Mega2560 vedere
board, you i LED
can see accendersi
the LEDs turninguno dopo
on one l'altro.
after another.

Analisi del Codice


Code Analysis

Dichiara
Declare anun array,
array, memorizza
store diversi
several 8 bit numeri
binary binari
numbers thataare
8 bit utilizzati
used to changeperthe
cambiare
workinglo stato
state di funzionamento
of the eight LEDs controlled
degli otto LED controllati dal 74HC595.
by 74HC595.

int datArray[] = {B00000000, B00000001, B00000011, B00000111, B00001111, B00011111, B00111111, B01111111,
B11111111};

Imposta il STcp
Set STcp to prima
low level a and
first livello low
then e poi
high a livello
level. high. Ciòa genererà
It will generate rising edgeun impulso
pulse di bordo ascendente di STcp.
of STcp.

digitalWrite(STcp,LOW);

shiftOut() is usatotoper
è used spostare
shift un of
out a byte byte dione
data dati,bitun
atbit alla which
a time, volta, means
il che significa
to shift aspostare un in
byte of data byte di dati in to the
datArray[num]
datArray[num] nel registro
shifting register with di spostamento
the DS pin. contoilmove
MSBFIRST means pin DS. MSBFIRST
from high bits.significa spostarsi da bit alti.

shiftOut(DS,SHcp,MSBFIRST,datArray[num]);

After digitalWrite(STcp,HIGH)
Dopol'esecuzione is run, the STcp will
di digitalWrite(STcp,HIGH), be at
l'STcp thealrising
sarà bordoedge. At this time,
ascendente. the datapunto,
A questo in the ilshift
dato register will be
nel registro
di spostamento
moved si sposterà
to the memory nel registro di memoria.
register.

123
digitalWrite(STcp,HIGH);

Unbyte
A byteofdidata
datiwill
saràbe
trasferito al registro
transferred into thedimemory
memoriaregister
dopo 8after
volte. Poi il dato
8 times. Thendel
theregistro
data ofdi memoria
memory sarà
register
emesso
are sul to
output bus (Q0-Q7).
the Ad esempio,
bus (Q0-Q7). shiftOut「B00000001」illuminerà
For example, shiftout「B00000001」will il LED
lightcontrollato
up the LEDdacontrolled
Q0 e spegne i LED
by Q0
controllati
and turn offdathe
Q1~Q7.
LED controlled by Q1~Q7.

Immagine Fenomenologica
Phenomenon Picture

124
2.7 4-Digital 7-Segment Display

Overview
Panoramica

this lesson,
In questa youimparearai
lezione will learn about the 4-Digital
a conosce 7-Segment
il Display Display. It consists
4-Digital 7-Segmenti. of fourdi7-segment
Si compone displays
4 display a working
7 segmenti
che lavorano
together so as insieme
to displayin4modo da visualizzare numeri a 4 cifre.
digit numbers.

Componenti
Components Richiesti
Required

1 * 4-Digital 7-Segment Display 8 * Resistore 220 Ω


220 ohm resistor Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

125
Component Introduction
Introduzione del Componente

IThe 4-digtaldigitali
4 display 7-segment display works
a 7 segmenti independently.
lavorano It uses the principle
indipendentemente. of human
Essi sfruttano visual persistence
il principio to quicklyvisiva
della persistenza display
umana per visualizzare
the characters velocemente
of each 7-segment i caratteri
in a loop to form di ogni 7-seg.
continuous in un ciclo per formare stringhe continue.
strings.

Ad
For esempio, quando
example, when "1234"
"1234" viene mostrato
is displayed sul display,
on the display, "1" vieneonmostrato
"1" is displayed sul primo 7-seg.,
the first 7-segment, e "234"
and "234" is not non sono
displayed.
mostrati. Dopo
After a period of un periodo
time, di tempo,
the second il secondo
7-segment 7-seg.
shows "2", themostra il "2",
1st 3th 4th il 1°, 3° e 4°
of 7-segment 7-seg.
does not non
show,mostrano
and so on,niente, e
the four
così
digitalvia, i 4 display
display digitali
show in turn. Thissono mostrati
process a turno.
is very short Il processo
(typically molto breve
è because
5ms), and of the(tipicamente 5ms)
optical afterglow e aand
effect causa
the
dell'effetto di postluminescenza
principle of visual e ilfour
residue, we can see prencipio delatresiduo
characters visivo,
the same time.possiamo vedere 4 caratteri allo stesso tempo.

126
Diagramma Schematico

127
Fritzing Circuit

The
Il wiring between
cablaggio the 4-digit
tra il display 7-segment
4-digit display
7-segment e la and the Mega
Scheda Mega2560
2560Board board isdiasseguito:
è mostrato shown below:

4-Digit Display Mega 2560 Board

A(11) 2

B(7) 3

C(4) 4

D(2) 5

E(1) 6

F(10) 7

G(5) 8

dp(3) 9

D1(12) 13

D2(9) 12

D3(8) 11

D4(6) 10

128
Schematic
Diagramma Diagram
Schematico

129
Codice
Code

Nota: Open
Note: aprire2.7_4digitalSegment
2.7_4digitalSegmentin
nell'IDE
Arduinoarduino per controllare
IDE to check the codes. il codice.

Il
Thecodice
code usa
usesla libreria TimerOne.h.
TimerOne.h Confrontare
library. Refer Parte
to Part 4 - 4.1 Add4Libraries
- 4.1 Aggiungere Librerie per importare librerie.
to import library.

Analisi del Codice


Code Analysis
START

Inizializza e innesca
il timer

Il timer conta
secondo in silenzio

N umero+ 1
Resetta il conto del timer

Il numero raggiunge
10000

Resetta il numero

Mostra il numero

130
Mostra Numero

Pulisci il 7-seg. Pulisci il 7-seg.

Prendi 1° cifra del 7- Mostra la 3° cifra del 7-


seg. seg.

Mostra la cifra delle Mostra la cifra delle


migliaia del numero. decine del numero.

Pulisci il 7-seg.
Pulisci il 7-seg.

Prendi 2° cifra del 7- Prendi la 4° cifra del 7-


seg. seg.

Mostra la cifra delle Mostra la cifra delle


centinaia del numero. unità del numero

Ritorna

131
There
Ci aredue
sono twopunti
pointsche
needing your attention:
richiedono attenzione:

① Because
Siccome every segment
nel 4-Dig. display
7-Seg. works
Display ogni independently
schermo lavorainda
thesolo,
4-Digital 7-Segment
è applicato Display,
il principio thepersistenza
della principle ofvisiva
visual
per mostrare
persistence rapidamente
is applied ogni
to quickly carattere
display everya7 7segment
segmenti a turno,
character per formare
in turn to form auna stringa character
continuous di caratteri continua.
string.

Confrontare
Refer to Part 2Parte 2 - 2.5 7-Segment
- 2.5 7-Segment Display Display
to checkper
theidetails
dettagli di visualizzazione
of the number display di
of un
thenumero
4-Digital 4-Dig. 7-Seg.
7-Segment Display.
Display.

②In this
questo esempio,
example, unaTimerOne.h
a library libreria TimerOne.h utilizzata
is used to èrealize per realizzare
the function la funzione di conteggio.
of counting.

#include "TimerOne.h"

Funzioni della Libreria:


Library Functions:

void initialize(long microsenconds=1000000)


Bisogna
You mustchiamare questofirst
call this method metodo per of
to use any poter usaremethods.
the other gli altri. A scelta
You si può quispecify
can optionally indicare
theiltimer's
periodo del here
period timer,
(indi
default è impostato
microseconds), su 1itsecondo.
by default is set at 1 Nota che
second. questo
Note that rompe analogWrite()
this breaks perfor
analogWrite() i pin digitali
digital pins 99 e10 di Arduino.
and 10 on Arduino.

void attachInterrupt(void (*isr)(), long microseconds=-1);

Calls a function
Chiama at the specified
una funzione interval
all'intervallo in microseconds.
specificato Be careful about
in microsecondi. trying to
Attenzione a execute
cercare too complicated
di eseguire of an
un interrupt
troppo
interruptcomplicato adauna
at too high of frequenza
frequency, troppo
or the elevata,
CPU may neveroenter
la CPU
the non
mainentrerà mai
loop and nelprogram
your loop principale e il Note that
will 'lock up'.
programma si "bloccherà".
you can optionally Nota
set the period che
with si function
this può a scelta
if youimpostare il periodo
include a value con questa
in microseconds as funzione se si include
the last parameter whenun
you
valore
call it. in microsecondi come ultimo parametro nella chiamata.

void detachInterrupte();

Disables the
Disabilita attached interrupt.
l'interrupt abilitato.

132
Phenomenon
Immagine Picture
Fenomenologica

133
2.8 LED Matrix Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imperarai LED Matrixil Module.
a conoscere ModuloLED Matrix Module
a Matrice usesutilizza
LED. Essso the MAX7219
il diverdriver to drive
MAX7219 perthe 8 x 8 LED
pilotare la
Matrice
Matrix. LED 8×8.

Componenti
Components Richiesti
Required

1 * MAX7219 LED Matrix Module 1 * Mega 2560 Board

Several Jumper
Diversi JumperWires
Filari

134
Component Introduction
Introduzione del componente

IThe
6464LED
LEDssono
are driven by 16
azionati daoutput
16 pinpinsdiofuscita
the IC. del
The circuito
maximumintegrato
number of(IC).
LEDsIl light up at the
massimo same time
numero is actually
di LED attivi
contemporaneamente è in as
eight. The LEDs are arranged realtà
8×8 otto.
set ofIrows
LED and
sono disposti
columns. Sointhe
unMAX7219
set di righe e colonne
activates pari a for
each column 8×8. Perciò
a very il
short
MAX7219 attiva
period of time andogni colonna
at the per un
same time periodo
it also drivesdi tempo
each row.molto breve eswitching
So by rapidly allo stesso tempo
through theguida anche
columns andogni
rowsriga.
the
Quindi,eye
human alternando rapidamente
will only notice tra righe
a continuous light.e colonne, l'occhio umano noterà solo una luce continua.

MAX7219

Questiintegrated
These circuiti integrati
circuits della
from
Maxim are
Maxim sono per either
for driving la con-
64
duzione diLED's,
individual 64 LEDor singoli,
up to o 8
fino a of
digits 8 cifre di un display
7-segment a
displays.
7 segmenti.
The I dirvera im-
drivers implement SPI
plementano
compatible unainterface
slave interfaccia
that
slavebecompatibile
can con the
controlled from SPI
che puòusing
Arduino essere
onlycontrollata
3 of the
da Arduino
digital outpututilizzando
pins. solo
3 dei pin di uscita digitale.

135
Fritzing Circuit

In this example,
questo we get
esempio, the VCC pin ilofpin
connettiamo MAX7219 connected
VCC del MAX7219toal
5V, GND
pin 12,to ground,
GND DINDIN
a terra, to digital
al pinpin 12, CS 12
digitale to digital pin
CS al pin
digitale 10,
10, CLK to CLK pin
digital al pin
11.digitale 11.

Schematic Diagram
Diagramma Schematico

136
Code
Codice
I codici usano la libreria LedControl.h, si prega di confrontare Parte 4 - 4.1 Aggiungere Librerie per
The codes use the library LedControl.h, and please refer to Part 4 - 4.1 Add Libraries to add in the library to Arduino IDE.
aggiungere la libreria all'IDE arduino.
#include
#include "LedControl.h"
"LedControl.h"
LedControl lc =
LedControl lc = LedControl(12,
LedControl(12, 11,
11, 10,
10, 1);
1);
void setup() {{
void setup()
lc.shutdown(0,
lc.shutdown(0, false);
false);
lc.setIntensity(0,
lc.setIntensity(0, 5);
5);
lc.clearDisplay(0);
lc.clearDisplay(0);
}
void loop() {
displayDot(); displayCol();
displayRow(); displayPic();
}
void displayDot() {
lc.clearDisplay(0);
delay(100);
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
lc.setLed(0, row, col, true);
delay(50);}

137
}
}
void displayCol() {
lc.clearDisplay(0);
delay(100);
byte data = B01100110;
for (int col = 0; col < 8; col++) {
lc.setColumn(0, col, data);
delay(100);
}
}
void displayRow() {
lc.clearDisplay(0);
delay(100);
byte data = B10011001;
for (int row = 0; row < 8; row++) {
lc.setRow(0, row, data);
delay(100);
}
}
void displayPic() {
lc.clearDisplay(0);

138
delay(100);
byte pic[8] = {
B00000000,
B01100110,
B11111111,
B11111111,
B01111110,
B00111100,
B00011000,
B00000000};
for (int col = 0; col < 8; col++)
{lc.setColumn(0, col, pic[col]);}
delay(2000);
}

After the
Dopo codes
aver are uploaded,
caricato i codici, you canosservare
si può see that the LEDs
che turnsion
il LED in the sequence
accendono nella of a column,
sequenza diauna
rowcolonna,
or a dot or there
una is a
riga
o un punto
picture oppure
appearing on c'è
the un'immagine
LED matrix. che appare sulla matrice LED.

139
Code Analysis
Analisi del Codice

By calling thela
Chiamando library LedControl.h,
libreria you can
LedControl.h,è easily use
possibile the LED matrix.
controllare facilmente la matrice LED.

#include "LedControl.h"

Library
FunzioniFunctions:
della Libreria:

LedControl(int dataPin,int clockPin,int csPin,int numDevices)

Create
Crea an instance
un'istanza diof type
tipo LedControlattraverso
LedControl through which we talk
la quale to the MAX7219
parliamo devices.
ai dispositivi The initialization
MAX7219. of an LedControl
L'inizializzazione di un
Led
takesControl richiede 4 argomenti.
4 arguments.

dataPin,clockPin,csPin: The
i primi
first33argomenti sono
arguments are thei numeri dei pin
pin-numbers onsu
theArduino
Arduino connessi al MAX7219.
that are connected Puoi
to the MAX7219.
scegliere liberamente
You are free qualunque
to choose any degli
of the digital altri pin
IO-pins digitali
on the I/O di
arduino, butArduino, maof
since some poiché alcuni
the pins di essi
are also usedsono anche
for serial
usati per comunicazioni
communication seriali
or have a led o hanno
attached un led
to them attaccato
its best adpin
to avoid esso, meglio
0,1 èand 13. evitare i pin 0, 1 e 13.

numDevices: The
il quarto
fourthargomenti il numero
argument isè the numberdi
ofdispositivi MX7219 devices
cascaded MAX7219 in cascate cheusing
you're stai utilizzando con questo
with this LedControl. The
LedControl. La libreria
library can address up topuò indirizzare
8 devices from afino a8
single dispositivi con una singola variabile LedControl.
LedControl-variable.

void shutdown(int addr, bool b)

The addressdel
addr: l'indirizzo of display
the display
da to control.
controllare.

If true
b: se the
vero il device goes into
dispositivo va inpower-down mode. If false device
modalità spegnimento. goes
Se falso into normalentra
il dispositivo operation.
in funzione normalmente.

140
void setIntensity(int addr, int intensity)

The
Il metodo
methodconsenti
lets youdi
control
controllare
brightness
la luminosità
in 16 discrete
in 16steps.
passaggi
Larger
discreti.
values make
Valorithe
piùdisplay
grandibrighter
rendono upil to
display
the maxi-
più
mum
luminoso
of 15.
fino ad un massimo di 15.

addr: The
l'indirizzo
addressdel
of display
the display
da to
controllare.
control.

intensity: the
la luminosità
brightness del
of the
display.
display.
Sono
Onlyvalidi
valuessolo
between
valori0(darkest)
tra 0 (piùand
scuro)
15(brightest)
e 15 (piùare
luminoso).
valid.

void clearDisplay(int addr)

All LEDs
Dopo off after
questo thisi one.
tutti LED vengono spenti.

The addressdel
addr: l'indirizzo of display
the display
da to control.
controllare.

void setLed(int addr, int row, int col, boolean state)

Set the status


Imposta of a single
lo stato Led. LED.
del singolo

addr: The addressdel


l'indirizzo of display
the display
da to control.
controllare.

row: The rowdel


la riga of the
LEDLed (0..7).
(0..7).

The
col: la columndel
colonna of the
LEDLed (0..7).
(0..7).

If true
state: se verothe
il led
LEDisèswitched
acceso, on, if falseil itLED
se falso is switched off.
è spento.

141
void setRow(int addr, int row, byte value)

Imposta tuttiingli
Set all 8 LEDs 8 LED
a row dinew
to a unastate.
riga ad un nuovo stato.

The addressdel
addr: l'indirizzo of display
the display
da to control.
controllare.

row: Row which


la riga is to be set(0..7).
da impostare (0..7).

ogni bit
value: Each bitset
impostato su 1up
to 1 will light illuminerà il LED corrispondente
the corresponding (es. B01000000
Led.(e.g. B01000000 will light upilluminerà
the 2nd). solo il 2°).

void setColumn(int addr, int col, byte value)

Set all 8 LEDs


Imposta tuttiingli
a column
8 LED ditouna
a new state. ad un nuovo stato.
colonna

The addressdel
addr: l'indirizzo of display
the display
da to control.
controllare.

col: Column which


la colonna da is to be set (0..7).
impostare (0..7).

value: Each
ogni bit
bitset to 1 will light
impostato su 1up the corresponding
illuminerà Led.(e.g. B01000000
il LED corrispondente will light upilluminerà
(es. B01000000 the 2nd). solo il 2°).

142
Phenomenon
Immagine Picture
Fenomenologica

143
2.9 I2C LCD1602 Module

Overview
Panoramica

In this lesson,
questa you will
lezione, learn about
imparerai LCD1602.l'LCD1602.
a conoscere LCD1602, or 1602
È un character-type
display a cristallyliquid crystal
liquidi 1602display, a kind of dot
character-type, unamatrix
sorta
moduledi to
modulo a matrice
show letters, di punti
numbers, per mostare
characters and so lettere,
on. numeri, caratteri e così via.

Componenti
Components Richiesti
Required

1 * I2C LCD1602 Module 1 * Mega 2560 Board

Several Jumper
Diversi JumperWires
Filari

144
Component Introduction
Introduzione del Componente

It'scomposto
È composedda
ofuna
5x7 matrice
or 5x11 dot matrix
di punti dipositions;
posizioneeach
5×7position
o 5×11;can display
ogni one character.
posizione There'sun
può mostrare a dot pitch between
carattere. C'è un
passo
two di un punto
characters and a tra due
space caratteri
between edthus
lines, unoseparating
spazio tra le linee, and
characters separando
lines. Thecosì i caratteri
number e le linee.
1602 means on theIl display,
numero 2
1602can
rows significa che sul
be showed anddisplay possono
16 characters essere mostrate 2 righe e 16 caratteri su ciascuna di esse.
in each.

Come
As sappiano,
we all sebbene
know, though LCD LCD ed alcuni
and some otheraltri display
displays arricchiscano
greatly notevolmenteinteraction,
enrich the man-machine l'interazione
theyuomo-macchina,
share a common
condividono
weakness. una
When debolezza
they comune.
are connected Quando multiple
to a controller, sono collegati ad occupied
IOs will be un controller, più I/O saranno
of the controller which hasoccupati sul
no so many
controller,
outer il quale
ports. Also non other
it restricts avrà functions
più molte of porte esterne.
the controller. Inoltre LCD1602
Therefore, limita altre
withfunzioni del
an I2C bus controller.toPertanto,
is developed solve the
l'LCD1602
problem. è sviluppato con un bus I2C per risolvere il problema.

I2C communication
Comunicazione I2C

I2C(Inter-Integrated
Il Circuit) Circuit)
bus I2C(Inter-Integrated bus is aè very popular
un bus moltoand powerfule bus
popolare for communication
potente, between atra
per la comunicazione master device (or
un dispositivo
master devices)
master (o più and
d'uno) e unorsingolo
a single multipleoslave
più devices.
dispositivi
I2C slave. Il controllo
main controller can principale
be used to I2C puòIOessere
control usato
expander, per
various
controllare
sensors, espansori
EEPROM, I/O, diversi
ADC/DAC and sosensori,
on. All ofEEPROM,
these areADC/DAC
controlledeonly
via dicendo. Tutti
by the two pinsquesti
of host,sono controllati
the serial solo line
data (SDA) dai
due the
and pinserial
dell'host,
clock la linea del dato seriale (SDA) e la linead del clock seriale (SCL).
line(SCL).

145
Fritzing Circuit

In this example,
questo we will
esempio, get the first pin
connetteremo GND ofpin
il primo LCD1602 connected to GND,
GND dell'LCD1602 theilsecond
al GND, pin pin
secondo VCCVCC
to 5V,
al the
5V,third pin pin
il terzo SDA
SDA
to thealpin
pinSDA
SDA2020 e the
and il quarto pinSCL
forth pin SCLtoalthe
pinpin
SCL 21.
SCL 21.

146
Schematic Diagram
Diagramma Schematico

Nota: l'SDA
Note: The e l'SCL
SDA dellaofscheda
and SCL Mega2560
the Mega2560 board
board aresono i pin
the pins 2020 e 21.
and 21.

Codice
Code

In
Thequesto codice
libraries Wire.hvengono usate le librerieare
and LiquidCrystal_I2C.h Wire.h
usedeinLiquidCrystal_I2C.h;
these codes, Wire.hWire.h è integrata
is built in Arduino,
in Arduino, ma la
but LiquidCrystal_I2C.h
LiquidCrystal_I2C.h deveAdd
needs adding manually. essere aggiunta
Method: Refermanualmente. Metodo
to Part 4 - 4.1 Add d'aggiunta: rif. Parte 4 - 4.1 Aggiungere Librerie.
Libraries.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{

147
lcd.init(); // initialize the lcd
lcd.backlight();
Serial.begin(9600);
}
void loop()
{
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters
while (Serial.available() > 0) {
char incomingByte=Serial.read();
// skip the line-feed(ASCII 10) character
if(incomingByte==10){break;}
// display each character to the LCD
lcd.print(incomingByte);
}
}
}

148
Upload the
Caricati codessulla
i codici to the Mega2560ilboard,
Mega2560, the content
contenuto that del
dell'input youmonitor
input in the serialsarà
seriale monitor will besul
stampato printed on the
display LCD.LCD.
Nota:

Riguardo il codice
Note: About ASCII
the ASCII e and
code l'input
thedal serial moniitor,
character siserial
input in the prega di riferirsi
monitor, allarefer
please Parte
to 1-1.8 SerialSerial
Part 1-1.8 Read. Read.

Analisi del Codice


Code Analysis

Chiamando
By calling thela libreria
library LiquidCrystal_I2C.h,
LiquidCrystal_I2C.h, yousican
può facilmente
easily drive thegovernare
LCD. l'LCD.
#include "LiquidCrystal_I2C.h"

Funzioni della Libreria:


Library Functions:

LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows)

Crea una
Creates nuova
a new istanza
instance della
of the classe LiquidCrystal_I2C
LiquidCrystal_I2C class that che rappresenta
represents un determinato
a particular LCD attachedLCD collegato
to your alla
Arduino scheda.
board.

lcd_AddR: The
lcd_AddR: l'indirizzo
addressdella scheda
of the LCD; ilto
LCD defaults valore
0x27. predefinito è 0x27.

lcd_cols: The
lcd_cols: l'LCD1602 ha has
LCD1602 16 colonne.
16 columns.

lcd_rows: The
lcd_rows: l'LCD1602 ha has
LCD1602 2 righe.
2 rows.

void init()

Initialize thel'LCD.
Inizializza lcd.

void backlight()

Turn the (optional)


Accende backlight on.
(facoltativamente) la luce dell'LDC.

149
void nobacklight()

Spegne (facoltativamente)
Turn the (optional) la luce dell'LDC.
backlight off.

void display()

Accende l'LCD.
Turn the LCD display on.

void nodisplay()

Turn the LCD


Spegne display offl'LCD.
velocemente quickly.

void clear()

Pulisce il display,
Clear display, imposta
set cursor il cursore
position to zero.a zero.

void setCursor(uint8_t
setCursor(uint8_t col,uint8_t
col,uint8_trow)
row)

Imposta la posizione
Set the cursor position del cursore a col, row.
to col,row.

void print(data,BASE)

Prints textil to
Stampa the LCD.
testo sull'LCD.

il dato
data: The datada
tostampare
print (char,(char, byte,
byte, int, int,orlong
long, o string)
string).

(optional): The
BASE (optional): la base
basein
in cui stampare
which i numeri: BIN
to print numbers: BINfor
perbinary
binario (base
(base 2), DEC
2), DEC per decimale
for decimal (base
(base 10), 10),
OCT forOCT
octalper
(base
ottale
8), HEX(base 8), HEX per(base
for hexadecimal esadecimale
16). (base 16).

150
Phenomenon
Immagine Picture
Fenomenologica

151
2.10 Active Buzzer

Overview
Panoramica

In this lesson,
questa you will
lezione get to know
imparerai about active
a conoscere un buzzer. Asattivo.
cicalino a type come
of electronic
tipo dibuzzer
buzzerwith an integrated
elettronico constructure, active
una struttura
integrata,
buzzer è alimentato
is supplied dalla corrente
by DC power, DC,
widely used ampiamente
in computer, utilizzata
alarm, in toy,
electronic computer, allarmi,
telephone, giochi
timer and otherelettronici,
electronic
telefoni, timer
products or eddevices.
voice altri prodotti elettronici o dispositivi vocali.

Componenti Richiesti
Components Required

1 * Active Buzzer 1 * Mega 2560 Board

1 * Breadboard

Several Jumper
Diversi JumperWires
Filari

152
Component Introduction
Introduzione del componente

IBuzzers
buzzercan be categorized
possono as active come
essere classificati and passive ones
attivi e (see(cfr.
passivi the immagine
following picture). TurnRuota
seguente). the buzzer so that
il buzzer its pinsche
in modo arei
pin siano
facing rivolti
up, and theverso
buzzerl'alto:
with ailgreen
buzzer conboard
circuit un circuito verde
is a passive è unwhile
buzzer, buzzer
the passivo, mentre
one enclosed withquello
a blackchiuso
tape is da
an
copertura
active one. nera è quello attivo.

La differenza
The difference tra un buzzer
between attivo
an active e unand
buzzer buzzer passivo:
a passive buzzer:

La
Thedifferenza tra un buzzer
difference between attivo
an active e and
buzzer unoapassivo è che is:
passive buzzer il An
primo habuzzer
active una sorgente oscillante
has a built-in integrata,
oscillating quindi
source, so it will
emetterà suoni
make sounds quando
when alimentato.
electrified. Il secondo
But a passive buzzer non
doesha
nottale
havefonte, quindi so
such source, non emetterà
it will suono
not beep if DCcon segnali
signals DC;
are used;
invece,
instead, è necessario
you utilizzare
need to use square onde
waves quadrate con frequenza
whose frequency è compresa
is between 2K and 5Ktra 2K e it.
to drive 5KThe
peractive
gui-
darlo.
buzzer Ilis buzzer attivo
often more è spesso
expensive più
than thecostoso
passive dell'altro
one becausea causa di più
of multiple circuiti
built-in oscillanti
oscillating integrati.
circuits.

A fianco
The è riportato
following il simbolo
is the electrical elettrico
symbol di un buzzer.
of a buzzer. It has two Hapins
duewith
conpositive
con poli + negative
and e -. Sullapoles.
sua With
superficie
a l'anodo
+ in the surface è indicato
represents thecon un +,
anode andmentre l'altro
the other is the il catodo.
è cathode.

153
You can
Puoi check thei pins
controllare of the
pin del buzzer,
buzzer, the longer
quello one is
più lungo the anode
è l'anodo, and the
quello piùshorter
corto èone is the cathode.
il catodo. Si pregaPlease don’t mix
di non
confonderli
them up whendurante la connessione,
connecting, altrimenti
otherwise the il buzzer
buzzer will non
not make farà suoni.
sound.

Fritzing Circuit

In this
questo esempio,
example, usiamo
we use il pinpin
the digital digitale 9 per
9 to drive guidare
the buzzer iland
buzzer; estendiamo
extend the cathodeilof
catodo del buzzer
the Buzzer to GNDaand
GND itseanode
l'anodo
to
al
thepin digitale
digital pin 9.9.

Diagramma Schematico
Schematic Diagram

154
Code
Codice

const int buzzerPin = 9;

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

void loop() {
digitalWrite(buzzerPin, HIGH);
delay(300);
digitalWrite(buzzerPin,LOW);
delay(300);
}

Finito di caricare
When you i codici sulla
finish uploading scheda
the codes to Mega2560, si potrà
the Mega2560 board,udire il bip—bip
you can hear theemesso dal buzzer.
beep—beep emittedPer una
from the buzzer. If
spiegazione dettagliata
you want to know del codice,
more about si prega
the detail di confrontare
code explanation, la refer
please Parte1to 1-1.2 Digital
Part 1-1.2 Write.
Digital Write.

155
Phenomenon
Immagine Picture
Fenomenologica

156
2.11 Passive Buzzer

Overview
Panoramica

In this lesson,
questa you will
lezione get to know
impearerai about passive
a conoscere buzzer.
il cicalino As a type
passivo. Comeof tipo
electronic buzzer
di buzzer with an integrated
elettronico con una structure,
struttura
integrata,
passive il buzzer
buzzer passivo
is supplied alimentato
by èDC da corrente
power, widely DC, ampiamente
used in computer, utilizzatatoy,
alarm, electronic in telephone,
computer,timer
allarmi,
andgiochi
other
elettronici,
electronic telefoni,
products ortimer
voice ed altri prodotti elettronici o dispositivi vocali.
devices.

Componenti Richiesti
Components Required

1 * Passive Buzzer 1 * Mega 2560 Board

1 * Breadboard

Several Jumper
Diversi JumperWires
Filari

157
Component Introduction
Introduzione del Componente

IBuzzers
buzzercan be categorized
possono as active come
essere classificati and passive ones
attivi e (see(cfr.
passivi the immagine
following picture). TurnRuota
seguente). the buzzer so that
il buzzer its pinsche
in modo arei
pin siano
facing rivolti
up, and theverso
buzzerl'alto:
with ailgreen
buzzer conboard
circuit un circuito verde
is a passive è unwhile
buzzer, buzzer
the passivo, mentre
one enclosed withquello
a blackchiuso
tape is da
an
copertura
active one. nera è quello attivo.

La differenza
The difference tra un buzzer
between attivo
an active e unand
buzzer buzzer passivo:
a passive buzzer:

La
Thedifferenza tra un buzzer
difference between attivo
an active e and
buzzer unoapassivo è che is:
passive buzzer il An
primo habuzzer
active una sorgente oscillante
has a built-in integrata,
oscillating quindi
source, so it will
emetterà suoni
make sounds quando
when alimentato.
electrified. Il secondo
But a passive buzzer non
doesha
nottale
havefonte, quindi so
such source, non emetterà
it will suono
not beep if DCcon segnali
signals DC;
are used;
invece, è necessario
instead, you utilizzare
need to use onde whose
square waves quadrate con frequenza
frequency compresa
is betweenè2K and 5K totra 2Kit.e The
drive 5K active
per governarlo. Il buzzer
buzzer is often more
attivo spesso
expensiveèthan piùonecostoso
the passive because of dell'altro a oscillating
multiple built-in causa di molteplici
circuits. circuiti oscillanti integrati.

A
Thefianco è riportato
following il simbolo
is the electrical elettrico
symbol di un buzzer.
of a buzzer. It has two Hapins
due conpositive
with con poli +negative
and e -. Sullapoles.
sua With a +
superficie l'anodo
in the surface è indicato
represents con and
the anode un +,thementre
other isl'altro è il catodo.
the cathode.

Puoi controllare
You can check thei pin
pinsdel
of buzzer, quello
the buzzer, the più lungo
longer oneèisl'anodo, quello
the anode and più
the corto è ilone
shorter catodo.
is theSi prega
cathode.
Please
di nondon’t mix them
confonderli up when
durante la connecting, otherwise
connessione, the buzzer
altrimenti willnon
il buzzer not farà
makesuoni.
sound.

158
Fritzing Circuit

In this
questo esempio,
example, whatusiamo il pin
we use to digitale
drive 9 perisguidare
the buzzer il buzzer;
the pin 9. estendiamo
We get the il catodo
cathode of delto
the Buzzer buzzer
GND, a GND
and theeanode to
l'anodo alpin
the digital pin9.digitale 9.

Diagramma Schematico
Schematic Diagram

159
Code
Codice

#include "pitches.h"
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(9, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(9);
}
}
void loop() {
// no need to repeat the melody.
}

At the time
Finito when you
di caricare finishsulla
i codici uploading the
scheda codes to the
Mega2560 Mega2560
board, si potràboard, you
sentire canmelodia
una hear a melody containing
contenente setteseven
note.notes.

160
Code Analysis
Analisi del Codice

There
Ci aredue
sono twopunti
pointsche
needing your attention:
richiedono attenzione:

noTone(): questa
①tone() & noTone(): This function is used
funzione to control
è utilizzata perthe sound ofdirettamente
controllare the passive buzzer directly
il suono and its passivo
del buzzer prototype
e ilis as
suo prototipo è il seguente:
follows:

void tone(int pin, unsigned int frequency)


void tone(int pin, unsigned int frequency, unsigned long duration)

Genera un'onda
Generates quadra
a square wave della
of thefrequenza specificata
specified frequency (e del
(and 50%50%
dutydel dutyoncycle)
cycle) a pinsu
(sounaspin (in modo
to make da far vibrare
the passive buzzer
il cicalino
vibrate passivo
to make per Aemettere
sound). suoni).
duration can È possibile
be specified, specificare
otherwise unacontinues
the wave durata, altrimenti l'onda
until a call to continua
noTone(). fino
The pin canalla
be
chiamata del
connected to anoTone(). Il pin
piezo buzzer può essere
or other speakercollegato ad un buzzer piezoelettrico o ad altri altoparlanti.
to play tones.

È possibile
Only one tonegenerare un solo tono
can be generated at a alla
time.volta. Se un
If a tone tono èplaying
is already già in on
riproduzione su un
a different pin, thepin
call diverso,
to tone() la chiamata
will have no a
tone() Ifnon
effect. the avrà
tone effetto.
is playingSeonil the
tono viene
same pin,riprodotto
the call willsullo
set itsstesso pin, la chiamata ne imposterà la frequenza.
frequency.

L'uso
Use ofdella funzione
the tone() tone()
function will interferirà con
interfere with l'uscita
PWM PWM
output on sui
pinspin 3 e11
3 and 11(on
(suboards
schedeother
diverse
thandal
theMega).
Mega).

Non
It è possibile
is not generare
possible to generatetoni più
tones bassi
lower di 31Hz.
than 31Hz.

pin: The
pin: il pinArduino
di Arduino col
pin on quale
which to generare il tono.
generate the tone.

frequency: The
frequency: la frequenza
frequencydel tono
of the in in
tone Hertz.
hertz.

duration: The
duration: La durata deloftono
duration in millisecondi
the tone (facoltativa)
in milliseconds (optional)

161
void noTone(int pin)

Ferma la generation
Stops the generazione dell'onda
of a quadra
square wave innescata
triggered da tone().
by tone(). Has noNon haif effetto
effect no tonese non ègenerated.
is being stato creato alcun suono.

il pinArduino
pin: The Arduinopinsu
oncui generare
which il tono.
to generate the tone.

Conoscendo
Having knownlethe
due
twofunzioni, possibile
functions,è you intuire
may grasp the i codes
codici
——the l'installazione dell'array
installation of the melody[]and
array melody[] e dell'array
the array
noteDurations[] is la preparazione
è the preparation ofdelle diverse successive
the subsequently chiamate
several times dellaoffunzione
of calling tone()
the function e del
tone() cambio
and del tono
the changing of
e della
tone anddurata nelinciclo
duration per un
the loop formigliore effetto
better effect di riproduzione
of music play. musicale.

②pitches.h: The
Il codice
code usa
usesun
anfile extra,
extra file, pitches.h. Questo
This file file contiene
contains tutte
all the le values
pitch intonazioni per le
for typical noteFor
notes. tipiche. Ad
example,
esempio,
NOTE_C4 isNOTE_C4 un C medio.
middle C.èNOTE_FS4 NOTE_FS4
is F sharp, è un
and so F acuto,
forth. e così
This note via.
table wasQuesta tabella
originally di by
written note è stata
Brett scritta
Hagman, on in ori-
whose
gine
work da
theBrett
tone()Hagman,
commandsulwas
cuibased.
lavoroYou
si basava il comando
may find tone(). Potrebbe
it useful whenever essere
you want to makeutile pernotes.
musical lavorare sulle note.

#include "pitches.h"

Nota: c'è giàisun


Note: There file pitches.h
already nelfile
a pitches.h programma di esempio.
in this sample program.Se lo si
If we putmette in unawith
it together cartella insieme
the main codealincodice
one folder, the
successive steps
principale, of installing
i passaggi pitches.h
successivi percan be omitted. di pitches.h possono essere omessi.
l'installazione

After you
Dopo open
aver the code
aperto 2.11passiveBuzzer,
il codice if you
2.11passiveBuzzer, secannot openad
non riesci the pitches.h
aprire code,pitches.h,
il codice you can just install
puoi one manually.
installarne uno The
steps are as follows:
manualmente. I passaggi sono i seguenti:

162
Permake
To creare il pitches.h
the file pitches.h,
file, fai click
either sulon
click pulsante appena
the button just sotto
belowl'icona delmonitor
the serial monitoricon
seriale
andechoose
scegli “New
"Nuova
Tab”, or use
Scheda" Ctrl+Shift+N.
oppure utilizza Ctrl+Shift+N.

Then paste
Quindi in the
incolla following
il questo code and
codice save itcome
e salvalo as pitches.h:
pitches.h:

/*****************
Public Constants
Constants
*****************/
#define NOTE_B0
NOTE_B031 31
#define NOTE_C1
NOTE_C133 33
NOTE_CS1
#define NOTE_CS1 35 35
NOTE_D137 37
#define NOTE_D1
#define NOTE_DS1
NOTE_DS139 39
#define NOTE_E1
NOTE_E141 41
#define NOTE_F1
NOTE_F144 44
#define NOTE_FS1
NOTE_FS146 46

163
#define NOTE_G1 49 #define NOTE_F3 175 #define NOTE_DS5 622 #define NOTE_CS7 2217
#define NOTE_GS1 52 #define NOTE_FS3 185 #define NOTE_E5 659 #define NOTE_D7 2349
#define NOTE_A1 55 #define NOTE_G3 196 #define NOTE_F5 698 #define NOTE_DS7 2489
#define NOTE_AS1 58 #define NOTE_GS3 208 #define NOTE_FS5 740 #define NOTE_E7 2637
#define NOTE_B1 62 #define NOTE_A3 220 #define NOTE_G5 784 #define NOTE_F7 2794
#define NOTE_C2 65 #define NOTE_AS3 233 #define NOTE_GS5 831 #define NOTE_FS7 2960
#define NOTE_CS2 69 #define NOTE_B3 247 #define NOTE_A5 880 #define NOTE_G7 3136
#define NOTE_D2 73 #define NOTE_C4 262 #define NOTE_AS5 932 #define NOTE_GS7 3322
#define NOTE_DS2 78 #define NOTE_CS4 277 #define NOTE_B5 988 #define NOTE_A7 3520
#define NOTE_E2 82 #define NOTE_D4 294 #define NOTE_C6 1047 #define NOTE_AS7 3729
#define NOTE_F2 87 #define NOTE_DS4 311 #define NOTE_CS6 1109 #define NOTE_B7 3951
#define NOTE_FS2 93 #define NOTE_E4 330 #define NOTE_D6 1175 #define NOTE_C8 4186
#define NOTE_G2 98 #define NOTE_F4 349 #define NOTE_DS6 1245 #define NOTE_CS8 4435
#define NOTE_GS2 104 #define NOTE_FS4 370 #define NOTE_E6 1319 #define NOTE_D8 4699
#define NOTE_A2 110 #define NOTE_G4 392 #define NOTE_F6 1397 #define NOTE_DS8 49
#define NOTE_AS2 117 #define NOTE_GS4 415 #define NOTE_FS6 1480
#define NOTE_B2 123 #define NOTE_A4 440 #define NOTE_G6 1568
#define NOTE_C3 131 #define NOTE_AS4 466 #define NOTE_GS6 1661
#define NOTE_CS3 139 #define NOTE_B4 494 #define NOTE_A6 1760
#define NOTE_D3 147 #define NOTE_C5 523 #define NOTE_AS6 1865
#define NOTE_DS3 156 #define NOTE_CS5 554 #define NOTE_B6 1976
#define NOTE_E3 165 #define NOTE_D5 587 #define NOTE_C7 2093

164
Phenomenon
Immagine Picture
Fenomenologica

165
2.12 Servo

Overview
Panoramica
In questa lezione imparerai qualcosa sul Servomotore. Si tratta di un tipo di drivere la cui posizione (angolare)
In this lesson, you will learn something about Servo. Servo is a kind of driver whose position (angular) can be adjustable
può essere regolata e manutenuta, un attuatore rotante che permette un controllo preciso della posizione
and kept or a rotary actuator that allows for precise control of angular position. Currently, it is widely used in upscale
angolare. Ad oggi è largamente utilizzato in giocattoli a controllo remoto di alto livello, come aerei,
remote control toys, such as airplane, submarine, telerobot and so on.
sottomarini, robot e via dicendo.

Components Required

1 * Servo 1 * Mega 2560 Board

Diversi JumperWires
Several Jumper Filari

166
Component Introduction
Introduzione del Componente

A
Unservo is generally
servomotore composed ofcomposto
è generalmente the following
dalle parts: case,
seguenti shaft,
parti: gear
case, system,
albero,
sistema di ingranaggi,
potentiometer, DC motor,potenziometro,
and embedded motore
board. DC e scheda incorporata.

Funziona
It works likeinthis:
questo modo: il microcontrollore
The microcontroller sends out PWMemette deithe
signals to segnali PWM
servo, and al
then
servomotore,
the embedded quindi la the
board in scheda
servoincorporata
receives the nel servomotore
signals riceve
through the signali pin
segnali
and
tramite
controls ilthe
pinmotor
e controlla il motore
inside to turn. Asrotativo
a result, all'interno. Comethe
the motor drives risultato, il motore
gear system and
guida un sistema
then motivates di ingranaggi
the shaft e quindi
after deceleration. Thecontrolla
shaft andl'albero. Quest'ultimo
potentiometer e il
of the servo
potenziometro sono When
are connected together. collegati insieme.
the shaft Quando
rotates, it drivesl'albero ruota, guida
the potentiometer, il
so the
potenziometro, quindi
potentiometer outputs quest'ultimo
a voltage signal toemette una tensione
the embedded allathescheda
board. Then board
determines the direction and speedincorporata. Poi on
of rotation based la the
scheda
currentdetermina
position, sodirezione e velocità
it can stop exactly at thedella rotazione
right position as
in funzione
defined dellathere.
and hold posizione, in modo che possa fermarsi proprio alla posizione richiesta e fermarsi lì.

L'angolo
The angle èis determinato
determined bydalla durata diofun
the duration impulso
a pulse that applicato al
is applied to
filo control
the di controllo.
wire. ThisÈ ischiamato Modulazione
called Pulse della The
width Modulation. larghezza
servo
d'Impulso.
expects Il servomotore
to see si 20
a pulse every aspetta di avere
ms. The lengthun
of impulso
the pulseogni
will
20ms. La lunghezza
determine how far thedell'impulso
motor turns.determinerà
For example,quando
a 1.5msapulse
lungo il
will
motore
make thegirerà. Ad to
motor turn esempio un impulso
the 90 degree positiondi(neutral
1,5msposition).
causerà una
rotazione fino alla posizione a 90° (posizione neutrale). Quando
When a pulse is sent to a servo that is less than 1.5 ms, the servo
l'impulso inviato è minore di 1,5ms, il servomotore ruota in una
rotates to a position and holds its output shaft some number of
posizione e mantiene l'albero ad un certo numero di gradi in
degrees counterclockwise from the neutral point.
senso antiorario dalla posizione neutrale.

167
When thel'impulso
Quando pulse is wider
è piùthan 1.5dims
largo the opposite
1,4ms occurs.
si verifica The minimal
il contrario. width andminima
La larghezza the maximum widthdell'impulso
e massima of pulse that che
will
comenderà
command theal servomotore
servo di ruotare
to turn to a valid in functions
position are una posizione valida
of each servo. sono the
Generally funzione di pulse
minimum ogniwill
servomotore.
be about 0.5
Generalmente
ms wide and thel'impulso
maximumminimo è be
pulse will di 0,5
2.5 ms wide.
e quello massimo di 2,5 ms.

168
Fritzing Circuit

In this example,
questo we use
esempio PWMilpin
usiamo pin9 PWM
to drive
9 the
perServo, andil get
guidare the orangeconnettendo
Servomotre, wire of the servo connected
il suo to the PWM
filo arancione a talepin
pin,9,
il
therosso ai 5V
red one to e5V,
il and
marrone a terra
the brown one(GND).
to GND.

Schematic Diagram
Diagramma Schematico

169
Code
Codice
#include <Servo.h>
Servo myservo;//create servo object to control a servo
void setup()
{
myservo.attach(9);//attachs the servo on pin 9 to servo object
myservo.write(0);//back to 0 degrees
delay(1000);//wait for a second
}
void loop()
{
for (int i = 0; i <= 180; i++){
myservo.write(i); //write the i angle to the servo
delay(15); //delay 15ms
}
for (int i = 180; i >= 0; i--)
{
myservo.write(i); //write the i angle to the servo
delay(15); //delay 15ms
}
}

170
Once you
Finito finish uploading
di caricare i codici the codes
sulla to the
scheda Mega2560
Mega2560, si board,
vede ilyou can see
braccio delthe servo arm rotating
servomotore ruotareinnel
therange
range 0°~180°.

Analisi del Codice


Code Analysis
Richiamando la libreria
By calling the library Servo.h,
Servo.h, è possibile
you can drive thecomandare
servo easily. facilmente il servomotore.

#include
#include <Servo.h>
<Servo.h>
Funzioni
Library della Libreria:
Functions:

Servo
Servo
Crea
Createun oggetto
Servo Servo
object per controllare
to control a servo. il servomotore.

uint8_t attach(int pin);

Trasforma un apin
Turn a pin into in un
servo driver
driver. per
Calls il servomotore.
pinMode. Returns 0Chiama pinMode. Ritorna 0 in caso di errore.
on failure.

void detach();

Release ailpin
Rilascia pinfrom servo
per la driving.
guida del servomotore.

void write(int value);

Set the angle


Imposta of thedel
l'angolo servo in degrees, 0
servomotore into 180. da 0 a 180°.
gradi,

171
int read();

Return that value


Restituisce set with
il valore the lastcon
impostato write().
l'ultimo write().

bool attached();

Restituisce 1 se
Return 1 if the il servomotore
servo è attualmente collegato.
is currently attached.

Immagine Fenomenologica
Phenomenon Picture

172
2.13 Motor

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai adtousare
use Motor, the working
il motore, principle di
il cui principio of funzionamento
which is that the energized coil is forced
è che la bobina to rotate
energizzata è
costretta a ruotare
in the magnetic field nel
thencampo magnetico,
the rotor quindi
of the motor il rotore
rotates del motore
accordingly ruota
on which the conformemente
pinion gear drivesall'ingranaggio del
the engine flywheel
pignone
to rotate. che governa il volano del motore per ruotare.

Componenti
Components Richiesti
Required

1 * Motore
Motor 11**Mod.
Powerdi Alimentazione
Supply Module 11 ** Mega
Mega 2560
2560 Board
Board

1 * Breadboard
1 * L293D

Several Jumper
Diversi JumperWires
Filari

173
Component Introduction
Introduzione dei componenti

This is a è
Questo 5Vun
DCmotore
motor. aIt 5V
willDC.
rotate when you
Ruoterà give the
quando two ai
si darà terminals of the copper
due terminali sheet one
della lamella high and
di rame one low level.un
rispettivamente For
convenience,
livello high eyou
un can weld
livello thePer
low. pinscomodità
to it. è possibile saldare dei pin ad esso.

Size: 25*20*15MM
Dimensione: 25*20*15MM Operation Voltage:
Tensione 1-6V
di funzionamento: 1-6V
Free-run currentdi(3V):
Corrente 70m
corsa A Free-run
libera: (3V): 70mA speed
Velocità (3V): 13000RPM
di corsa libera (3V): 13000RPM
Corrente
Stall current di800mA
(3V): stallo: (3V): 800mA ShaftDiametro dell'albero: 2mm
diameter: 2mm

L293D
L293D isè aun driver a motor
4-channel 4 canali perintegrated
driver motori, integrato da
by chip with
chip voltage
high ad altoandvoltaggio ed alta
high current. It'scorrente.
designed Ètoprogettato
connect to
per connettersi
standard DTL, TTLa logic
standard
level,DTL,
and livello logico TTL,
drive inductive e
loads
guidare
(such as carichi induttivi
relay coils, (come bobine
DC, Stepper Motors) diandrelè, DC,
power
motori passo-passo) e transistor di commutazione di
switching transistors etc. DC Motors are devices that turn
potenza, ecc. I motori DC sono dispositivi che tra-
DC electrical energy into mechanical energy. They are
sformano l'energia eletrica DC in energia meccanica.
widely used in electrical drive for their superior speed
Sono ampiamente utilizzati nel drive elettrico per le
regulation
loro performance.
performance superiori di velocità di regolazione.

174
L293D has two pins
ha due (Vcc1(Vcc1 andper
e Vcc2) Vcc2) for power supply.
l'alimentazione. Vcc2Vcc2 is usedper
è usato to supply power for
dare energia al the motor,mentre
motore, while Vcc1
Vcc1toper
supply for
alimentare
the chip. il chip.

Di
Theseguito la is
following struttura interna
the internal del L293D.
structure Il pin
of L293D. PinEN
ENèisdi
anattivazione e lavora
enable pin and solo con
only works withlivello High;A A
high level; sta per
stands for input
input
and Y for
Y per output.
output. You
Puoi can see
vedere lethe relationship
relazioni among
fra essi themaatdestra.
in basso the right bottom.
Quando il When
pin ENpin
è aEN is High
livello level,seif A
High, Aèis High, Y
outputs
emette high level; High;
un livello if A is Low,
se AYèoutputs Low level.
Low, Y emette unWhen pin
livello EN is
Low. Low level,
Quando theEN
il pin L293D does not
è a livello work.
Low, il L293D non lavora.

175
Power Supply
Modulo Module
di Alimentazione

In this experiment,
questo it needs
esperimento large
si ha currents
bisogno di to drivecorrente
molta the motor especially
per guidarewhen it starts
il motore, and stops, quando
soprattutto which will severely
parte e si
ferma,
interferee with
questo
the può interferire
normal work ofseriamente con
Raspberry Pi. il normale
Therefore, we lavore della
separately scheda
supply Mega
power for2560. Pertanto,
the motor separeremo
by this module to
l'alimentazione
make it run safelydel
andmotore
steadily.con questo modulo per farlo lavorare in sicurezza e stabilmente.

È sufficiente
You collegare
can just plug it in thelabreadboard
breadbordtoalsupply
modulo di alimentazione.
power. Fornisce
It provides a voltage unaand
of 3.3V alimentazione di 3.3V
5V, and you can o 5V
connect ed èvia
either
possibile erogare
a jumper cap uno o l'altro tramite il cappuggio jumper incluso.
included.

176
Fritzing Circuit

In this example,
questo we use
esempio PowerilSupply
usiamo Power Module to powerper
Supply Module theenergizzare
anode and cathode of ebreadboard.
gli anodi GND
i catodi della of Mega 2560
breadboard. Board
Il GND
della SchedatoMega
is connected 2560 è connesso al catodo.
the cathode.

177
Schematic Diagram
Diagramma Schematico

Code
Codice

const int motor1A=10;


const int motor2A=9;

void setup() {
pinMode(motor1A,OUTPUT);
pinMode(motor2A,OUTPUT);
Serial.begin(9600);

178
Serial.println("Please input 'A' or 'B' to select the motor rotate direction.");
}

void loop() {
if (Serial.available() > 0) {
int incomingByte = Serial.read();
switch(incomingByte){
case 'A':
clockwise(255);
Serial.println("The motor rotate clockwise.");
break;
case 'B':
anticlockwise(255);
Serial.println("The motor rotate anticlockwise.");
break;
}
}
delay(3000);
stopMotor();
}
void clockwise(int Speed)
{

179
analogWrite(motor1A,0);
analogWrite(motor2A,Speed);
}

void anticlockwise(int Speed)


{
analogWrite(motor1A,Speed);
analogWrite(motor2A,0);
}
void stopMotor()
{
analogWrite(motor1A,0);
analogWrite(motor2A,0);
}

Dopo il caricamento
After uploading dei to
the codes codici sulla scheda
the Mega2560 Mega2560,
board, si può
you can select selezionare
the la direzione
rotating direction di by
of motor rotazione
typing 「A」 or 「B」
digitando「A」o「B」nel
in the serial monitor. monitor seriale.

Analisi del Codice


Code Analysis

Il
Themotore
motorpuò
can essere azionato
be driven fornendo
by providing una differenz
a voltage adibetween
difference tensionethe
tracopper
le lamelle di rame
sheets su sides
at both entrambi i lati
of the del
motor.
Therefore,Pertanto,
motore. you only need to write 0scrivere
è sufficiente for the voltage
0V peroflaone side of the
tensione copper
di un latosheet
e 5Vand
per5V for theModifica
l'altro. other side.
il Modify
valore the
del

180
written analog
segnale signalscritto
analogico value to adjust
per the direction
regolare and speed.
la direzione e la velocità.

void clockwise(int
clockwise(int Speed)
Speed)
{
analogWrite(motor1A,0);
analogWrite(motor2A,Speed);
}

void anticlockwise(int Speed)


{
analogWrite(motor1A,Speed);
analogWrite(motor2A,0);
}

In this
questo esempio,
example, Serial.Read()
Serial.Read() è utilizzato
is used to control per controllare
the direction la direzione del motore.
of motor.

When youscrivi
Quando type ’’A’
A’ in
nelserial monitor,
monitor thereviene
seriale, calls the clockwise
chiamata (255) function
la funzione to make the per
clockwise(255) motor
farrotate with
ruotare il the speed
motore of 255.
con la
velocità
Input 'B', 255. Scrivi
and the 'B', ewill
motor il motore
rotate inruoterà nella direzione opposta.
reverse direction.

void loop() {
if (Serial.available() > 0) {
int incomingByte = Serial.read();
switch(incomingByte){
case 'A':

181
clockwise(255);
Serial.println("The motor rotate clockwise.");
break;
case 'B':
anticlockwise(255);
Serial.println("The motor rotate anticlockwise.");
break;
}
}
delay(3000);
stopMotor();
}

182
Phenomenon
Immagine Picture
Fenomenologica

183
2.14 Stepper Motor

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imparerai Stepper Motor.
a conoscere il Motore Passo-Passo.

Components Richiesti
Componenti Required

1 * Motore
Stepper Passo-Passo
Motor 11**Modulo
Power Supply Module
di alimentazione 11**Mega
Mega2560
2560Board
Board

1 * Breadboard
1 * ULN2003

Several Jumper
Diversi JumperWires
Filari

184
Component Introduction
Introduzione del componente

Il motore
Stepper passo-passo
motor è un motore
is an open-loop controldi controllo
motor ad anellothe
by converting aperto che
electric converte
pulse signal ilinto
segnale dell'impulso
angular elettrico
displacement or line
in spostamento
displacement. It isangolare o spostamento
the main executing lineare.
component È ilmodern
in the principale componente
digital di esecuzione
program control nei the
system. When moderni sistemi
stepper driver
dei programmi
receives di controllo
a pulse signal, it drivesdigitale. Quando
the stepper motor iltodriver
rotate del passo-passo
a fixed riceve
angle in a set un segnale
direction. ad impulsi,
The rotation spinge
of stepper il
driver
motore
runs stepaby
ruotare
step atad un angolo
a fixed fisso
angle. The in unadisplacement
angular direzione prestabilita. La rotazione
can be controlled è eseguita
by changing dal driver
the number passo
of pulses, dopo
thereby
passo in una
achieving direzione
the purpose of prestabilita. Lo spostamento
accurate positioning. angolare
At the same time, thepuò essere
speed controllato of
and acceleration modificando
the rotation ilofnumero di
the motor
impulsi,
can ottenendo
be controlled così i valori
by adjusting desiderati.
the pulse Ugualmente,
frequency la velocità
so as to achieve e l'accelerazione
the purpose della rotazione del motore
of speed regulation.
possono essere controllate regolando la frequenza d'impulso in modo da raggiungere i valori desiderati.
There are two types of steppers, unipolars and bipolars, and it is very important to know which type you are working with.
Esistono
In due tipi di
this experiment, wepasso-passo, unipolari
will use a unipolar e bipolari, ed è molto importante sapere con quale tipo si sta
stepper.
lavorando. In questo esperimento useremo passo-passo unipolari.
The stepper motor is a four-phase one, which uses a unipolarity DC power supply. As long as you electrify all phase
Il motoreofpasso-passo
windings a appropriate
the motor byèan quattro fasitiming
ed utilizza un'alimentazione
sequence, DC
you can make it unipolare.
rotate step byFinché si elettrificano
step. The tutti gli
schematic diagram of
avvolgimenti di fase del motore con una sequenza di temporizzazione appropriata, è possibile farlo ruotare

185
a four-phase
passo dopo reactive
passo. Ilstepper motor:schematico di un motore passo-passo reattivo a quattro fasi:
diagramma

In the figure,
figura, al incentro
the middle of the motor
del motore is a rotore
c'è un rotor – –a un
gear-shaped
magnetepermanent
permanente magnet. Around
a forma the rotor, 0 to 5Intorno
di ingranaggio. are teeth.
al
rotore
Then moreci sono i denti,
outside, there da
are 0 a 5. All'esterno,
8 magnetic poles, withci each
sonotwo
8 poli magnetici,
opposite ciascuno by
ones connected concoildue opposti
winding. collegati
So they form
all'avvolgimento
four pairs from A to della bobina.
D, which Essi formano
is called a phase. Itquattro
has fourcoppie da A
lead wires toabeD,connected
chiamati with
fase.switches
Ha quattro fili SC,
SA, SB, conduttori
and SD.
da collegare
Therefore, the con
four gli interruttori
phases SA, SB,
are in parallel SC circuit,
in the ed SD.and Pertanto,
the twolemagnetic
quattropoles
fasi sono
in oneinphase
parallelo
are innel circuito e i due
series.
poli magnetici in una fase sono in serie.
Here's how a 4-phase stepper motor works:
Ecco come funziona un motore p-p a 4 fasi:
When switch SB is power on, switch SA, SC, and SD is
Quando l'interruttore SB è acceso, gli interruttori
power off, and B-phase magnetic poles align with
SA, SC e SD sono spenti, e i poli della fase B si
tooth 0 and 3 of the rotor. At the same time, tooth 1
allineano con i denti 0 e 3 del rotore. Allo stesso
and 4 generate staggered teeth with C- and D-phase
tempo, i denti 1 e 4 generano denti salsati con i
poles. Tooth 2 and 5 generate staggered teeth with
poli delle fasi D ed A. Quando l'interruttore SC è
D- and A-phase poles. When switch SC is power on,
acceso, SB, SA e SD sono spenti, il rotore ruota
switch SB, SA, and SD is power off, the rotor rotates
sotto il campo magnetico dell'avvolgimento della
under magnetic field of C-phase winding and that
fase C, tra i denti 1 e 4. Quindi i denti 1 e 4 si
between tooth 1 and 4. Then tooth 1 and 4 align with
allineano con i poli magnetici dell'avvolgimento
the magnetic poles of C-phase winding. While tooth 0
della fase C. Mentre i denti 0 e 3 generano denti
and 3 generate staggered teeth with A- and B-phase
sfalsati con i poli di fase A e B e i denti 2 e 5
poles, and tooth 2 and 5 generate staggered teeth
generano denti sfalsati con i poli magnetici delle
with the magnetic poles of A- and D-phase poles. The similar situation goes on and on. Energize the A, B, C and D phases
fasi A e D. Tale situazione prosegue di continuo. Energizzando le fasi A, B, C e D a turno, il rotore ruoterà
in turn, and the rotor will rotate in the order of A, B, C and D.
nell'ordine A, B, C e D.

186
Thestatore
Lo stator of Stepper
del MotoreMotor we use has
Passo-Passo 32usiamo
che magnetic
hapoles, so a
32 poli circle needs
magnetici, 32 steps.
quindi The output
un anello shaft of di
ha bisogno the32
Stepper
passi.
L'albero
Motor di uscita del
is connected motore
with passo-passo
a reduction collegato
gear set,èand con unratio
the reduction set is
di 1/64.
riduttori e ilfinal
So the rapporto
outputdishaft
riduzione
rotates èa 1/64.
circle
Perciò l'albero
requiring di uscitastep.
a 32*64=2048 finale ruota in un anello che necessita di 32×64=2048 passi.

ULN2003

Per apply
To applicare
the ilmotor
motore
in nel
the circuito,
circuit, aserve una
driver scheda
board driver.
needs L'ULN2003
to be per un Motor
used. Stepper Mo-
tore P-P è un circuito
Driver-ULN2003 inverter
is a 7-channel a 7 canali.
inverter circuit.

Quindi,
That quando
is, when il pin
the input pin di
is atingresso a
high level,èthe
livello high,
output pin of ilULN2003
pin di output
is at lowdell'ULN2003
level, and vice
è a livello
versa. If welow, e viceversa.
supply high levelSe
to forniamo un
IN1, and low
livello
level to high a IN1
IN2, IN3 and eIN4,
unthen
livello
the low a IN2,
output end
IN3 e IN4,
OUT1 allora
is at low l'ouput
level, OUT1
and all è a livello
the other output
low, eare
ends tutti gli altri
at high output sono a livello high.
level.

La struttura
The interna del
internal structure chip
of the è mostrata
chip dibelow.
is shown as seguito.

Il driver
The delmotor
stepper motore passo-passo
driver constituted costituito
by ULN2003 dal chip
chip andULN2003
4 LEDs iseshown
da 4
LEDfollows.
as è così On
realizzato. Sulla
the board, scheda, IN1,IN2,IN3
IN1,IN2,IN3 e IN4
and IN4 work as lavorano
input andcome in-
the four
put e A,
LEDs, i 4B,led LEDs,
C, D A, B,
are the C, D sono
indicators gli indicatori
of input pin. dei pin di input.

Inoltre,
In OUT1,OUT2,
addition, OUT3
OUT1,OUT2, e OUT4
OUT3 sono connessi
and OUT4 a SA, to
are connected SB,SA,
SCSB,
e SD
SCsul
anddriver
SD on del
themotore
stepperpasso-passo.
motor driver.Quando il
When the
valoreofdiIN1
value IN1
is è impostato
set a livello
to a high level, alto,up;
A lights A si accende;

187
switch SA is power
l'interruttore SA èon, and the
acceso, e ilstepper
motoremotor
ruotarotates
di un one step.
passo. LoThe similar
stesso case
caso repeats
viene on and
ripetuto on.
all'infinito.

Fritzing Circuit

Power
Il Supply
Modulo Module is useddà
di Alimentazione toenergia
power the stepper motor.
al motore. CollegaGet the GND
il GND dellaof Mega Mega
Scheda 2560 Board and GND
2560 Board of ULN2003
e il GND
dell'ULN2003 concathode
connected to the il catodo della
of the breadboard
breadboard, andeconnect
connetti la VCC
the VCCof
dell'ULN2003 al 5V
ULN2003 to 5V OUTPUT
OUTPUT del Mod.
of Power di Alim.
Supply.

Il
Thecablaggio
wiring of dell'ULN2003
ULN2003 and eMega2560
della Mega2560 mostrato
è as
is shown follows: di seguito:

188
Schematic Diagram
Diagramma Schematico

Code
Codice

#include <Stepper.h>
const int stepsPerRevolution = 2048; // change this to fit the number of steps per revolution
const int rolePerMinute = 16; // Adjustable range of 28BYJ-48 stepper is 0~17 rpm

//set steps and the connection with MCU


Stepper stepper(stepsPerRevolution, 2, 3, 4, 5);

189
void setup()
{
stepper.setSpeed(rolePerMinute);
}

void loop()
{
int val = 2048;
stepper.step(val); //Turn the motor in val steps
delay(1000);
}

Dopo il caricamento
After uploading dei codici
the codes sulla scheda
to the Mega2560 Mega2560,
board, you willsibepotrà vedere
able to ruotare
see that il motore
the stepper in un
motor cerchio
rotates one con
circleun
with
intervallo
an interval di unsecond
of a secondo
andeeach
ognicircle
cerchio
takesrichiede
3.75s. 3.75s.

Analisi del Codice


Code Analysis

Richiamando la libreria
By calling the library Stepper.h,
Stepper.h, saràeasily
you can più facile gestire
drive the il motore
stepper motor. passo-passo.

#include <Stepper.h>

Funzioni della Libreria:


Library Functions:

Stepper(steps, pin1, pin2, pin3, pin4)

190
Creates
Crea unaa new instance
nuova of the
instanza Stepper
della class
classe that represents
Stepper a particular
che rappresenta stepper motor
lo specifico attached
motore to your
collegato Arduino
alla board.
scheda.

steps: the
il numero
numberdiofpassi
stepsininun giro
one del motore.
revolution Se motor.
of your il tuo motore fornisce
If your motor ul numero
gives di gradi
the number per passo,
of degrees dividi
per step, divide
quel numerointo
that number con360
360toper
get ottenere il numero
the number di passi
of steps (e.g. 360 /(es.
3.6360 / 100
gives 3,6 dà 100passi).
steps). (int) (int)

Nota: ogni ciclo


Note: every circle del motore
of the passo-passo
stepper motor takesrichiede 2048 steps.
2048 steps.

setSpeed(rpm)

Imposta la velocità
Sets the motor speeddel motore in
in rotations rotazioni
per minute. al minuto.
This Questa
function funzione
doesn't non
make the fa girare
motor il motore,
turn, just sets thema imposta
speed soloit
at which
la
willvelocità
when youallacall
quale girerà quando chiamerai step().
step().

rpm: the
la velocità
speed atalla quale
which the ilmotor
motore dovrebbe
should girare in per
turn in rotations rotazioni
minuteal- aminuto
positive- number.
un numero positivo. (long)
(long)

Nota: il motore
Note: The passo-passo
stepper che
motor we use usiamo
here rotatesqui
17 ruota
circles al massimo
a minute di 17 giri al minuto.
at most.

step(steps)

Turns the
Ruota motor a specific
il motore number
di un certo of steps,
numero di at a speed
passi, ad determined bydata
una velocità the most
dallarecent call topiù
chiamata setSpeed().
recente di setSpeed().
Questa funzione è di blocco; cioè, attenderà fino a quando il motore non avrà finito di muoversi per passare
This function is blocking; that is, it will wait until the motor has finished moving to pass control to the next line in your
il controllo alla linea successiva dello sketch. Ad esempio, impostando la velocità di 1 RPM e chiamando
sketch. For example,
step(2048) if you a
su un motore set2048
the speed to, say, funzione
step, questa 1 RPM and called step(2048)
richiederà on aintero
un minuto 2048-step
per motor,
girare.this
Perfunction would
un controllo
take a full minute
migliore, to run.
mantieni alta For better control,
la velocità keeppochi
e fai solo the speed high con
passaggi and only
ognigo a few steps
chiamata with each call to step().
di step().

steps: the numberdiofstep


il numero stepsper
to turn the motor
far girare - positive
il motore to turnin
- positivo one direction,
una negative
direzione, to turn
negativo the other.
nell'altra. (int)
(int)

191
Phenomenon
Immagine Picture
Fenomenologica

192
2.15 Button

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imparerai Button. Button
a conoscere is a common
il Pulsante. component used
È un componente to control
comune electronic
utilizzato devices. It is usually
per controllare
dispositivi elettronici.
used as a switch Di solito
to connect viene
or break utilizzato come interruttore per collegare o interrompere i circuiti.
circuits.

Componenti
Components Richiesti
Required

Pulsante
1 * Button 1 * Resistore 10 kΩ
10k ohm resistor Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

193
Component Introduction
Introduzione del Componente

ITwo
duepins
pinon thesinistra
sulla left are connected, and the
sono collegati, one onper
lo stesso the right
quelliisasimilar
destra,tocome
the left, which is shown
mostrato below:
di seguito:

The
Il symbolmostrato
simbolo shown asdi
below is usually
seguito viene used to represent
solitamente a button
utilizzato neiin circuits.
circuiti per rappresentare un pulsante.

When theilbutton
Quando is pressed,
pulsante the i44pins
è prenuto, pin are
sonoconnected,
connessithus closing
fra loro, the circuit.
chiudendo il circuito.

194
Fritzing Circuit
In
In this example,
questo we read
esempio, the signal
leggiamo of the button
il segnale with thecon
del pulsante digital pin digitale
il pin 2. When2.the button is
Quando not pressed,
il pulsante non the
è digital
premuto,pin 2
il
(through the 2
pin digitale drop-down resistor)
(tramite la is connected
resistenza to ground
drop-down) to read the
è connessa allalow level
terra per(0);leggere
when the buttonlow
il livello is pressed, the two
(0); quando il
pins are connected
pulsante andi when
è premuto, thevengono
due pin pin is connected to e
connessi the 5V power
quando supply,
il pin the highai
è connesso level
5V,(1) is read.
viene letto il livello high (1).

NOTA :
NOTE : If
se you
si scollega il pinthe
disconnect I/
O digitale
digital I/O pinda from tutto, il LED
anything, the
potrebbe
LED may blink lampeggiare in
erratically. The
modo irregolare. Questo
input is "floating" or it doesn't
perché l'ingresso è
have a solid connection to
"fluttuante" - cioè non ha una
voltage or ground, so it will
connessione solida alla ten-
randomly
sione o alla return eithera HIGH
messa terra, ore
LOW. That's why there
restituirà casualmente HIGH o needs a
pull-down
LOW. resistor inperché
Ecco the circuit. è
necessario un resistore di
pull-down nel circuito.

195
Schematic Diagram
Diagramma Schematico

Code
Codice

Example
Esempio1:
1:

setup() {{
void setup()
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
int buttonState = digitalRead(2);
Serial.println(buttonState);
delay(1);
}

Uploadedi codici
Caricati the codes to scheda
sulla the Mega2560 board,siyou
Mega2560, can see the
vedranno readings
le letture deiofpin
the sul
pinsmonitor
on the serial monitor.
seriale. QuandoWhen
si you press
preme il
pulsante, sul monitor
down the Button, seriale
there will verrà visualizzato「1」e
display「1」 on the serial monitor,una
andvolta rilasciato,
once you release verrà visualizzato「0」.
it, there will display「0」.As Per quando
for the detail
riguarda la spiegazione
code explanation, del codice
please refer nel dettaglio,
to Part 1-1.4 si prega di fare riferimento alla Parte 1-1.4 Digital Read.
Digital Read.

196
Example 2:
Esempio 2:

const int buttonPin = 2;


int detectionState = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
detectionState=(detectionState+1)%2;
Serial.print("The detection state is:");
Serial.println(detectionState);
}
delay(50);
}

197
lastButtonState = buttonState;
}

Caricato
Uploadedilthe
codice
codessulla scheda
to the Mega2560,
Mega2560 ogni volta
board, every chepress
time you si preme il pulsante,
the button, il valore
the output diwill
value uscita passerà
switch da 00 and
between a
1. IfPer
yousaperne
want todi più more
know sulla spiegazione delexplanation,
about the code codice, passare alla
you can Parte
turn 1-1.10
to Part State
1-1.10 Change
State Detection.
Change Detection.

Immagine Fenomenologica
Phenomenon Picture

198
2.16 Slide Switch

Overview
Panoramica

In this lesson,
questa you will
lezione get to know
imperarai something
qualcosa su unabout Switch. A
Interruttore slide switch, just
a Scorrimento. as itsdice
Come name il implies,
nome, fa is to slide the
scorrere la switch
barra
dell'interruttore
bar per collegare
to connect or break o interrompere
the circuit, and il circuito
further switch circuits. e ulteriori
The slide circuiti diused
switch is commonly commutazione. Esso It
in low-voltage circuit. è
comunemente usato
has the features of nei circuiti
flexibility a bassa
and stability, tensione.
and flessibile
applies inÈ electric e stabile and
instruments e si electric
applicatoys
a strumenti
widely. e giochi elettrici.

Componenti
Components Richiesti
Required

1 * Switch 1 * 104 Condensatore


Capacitor Diversi Jumper
Several JumperWires
Filari

1 * 10k ohm resistor


Resistore 10kΩ

1 * Mega 2560 Board 1 * Breadboard

199
Component Introduction
Introduzione del Componente

How it funziona:
Come works: Setconsiderare
the middle pin as centrale
il pin the fixed come
one. When
quelloyou pullQuando
fisso. the slide sitotira
thelo
left, the two
switch pins oni the
a sinistra, dueleft
pinare
a
sinistra sono
connected; collegati;
when you pullquando
it to thelo si tira
right, theatwo
destra, sono
pins on thecollegati i due pin aThus,
right are connected. destra. Pertanto,
it works funziona
as a switch come un
connecting or
interruttore che
disconnecting collega
circuits. Seeothe
disconnette i circuiti. Vedere figura qui sotto:
figure below:

The
Il circuit symbol
simbolo of thedell'interruttore
del circuito slide switch is shown as below. The
a scorrimento pin2 in thedifigure
è mostrato refers
seguito. Il to
pinthe middle
2 nella pin. è il pin centrale.
figura

200
Fritzing Circuit

In this example,
questo digital
esempio pin digitale
il pin 2 is used2toè read the
usato signal
per of Switch.
leggere In addition,
il segnale you need
di Switch. to connect
Inoltre, collega a
un10resistore
kΩ resistor
da and
10kΩa
e uncapacitor
104 condensatore 104toinform
in parallel parallelo per formare
a RC circuit (Resistorun circuito RC circuit)
- Capacitance (Resistore-Capacitore) tra pin
which is set between il pin 2 e GND
2 and GND to
per rea-
realize
lizzare il debounce
debounce che potrebbe
that may arise from your verificarsi.
toggle of switch.

Diagramma
Schematic Schematico
Diagram

201
Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
int switchState = digitalRead(2);
Serial.println(switchState);
delay(1);
}

After the
Dopo codes
aver are uploaded
caricato i codicitosulla
the Mega2560 board, you è
scheda Mega2560, can open theaprire
possibile serial monitor to check
il monitor the readings
seriale of the pin.
per controllare le
letturethe
When delSwitch
pin. Quando
toggles tol'interruttore si sposta
the left, the serial a displays
monitor sinistra 「1」
il monitor
; whenseriale
togglesvisualizza 「1」;
to the right, quando
the serial si sposta
monitor a
displays
destra, visualizza
「0」. Refer to Part「0」. Ci si riferisca
1-1.4 Digital Read toalla Parte
check the 1-1.4 Digital Read per verificare la spiegazione del codice.
code explanation.

202
Phenomenon
Immagine Picture
Fenomenologica

203
2.17 Tilt Switch

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imparerai tilt switch. Tilt
a conoscere switch can be
l'Interruttore diused to detect whether
Inclinazione. objects
È utilizzato pertilt, which isseofgli
rilevare great value in
oggetti si
inclinano, il che è diItgrande
practical applications. valore
can be used to nelle
judgeapplicazioni pratiche.
the tilt of bridges, Può essere
buildings, usatoline
transmission pertower
verificare
and sol'inclinazione di
on, so it has an
ponti, edifici,
important torrifunction
guiding di lineeindicarrying
trasmissione e via dicendo,
out maintenance work.fungendo da guida nei lavori di manutenzione.

Components Required

1 * Tilt Switch Resistore


1 * 10k 10 kΩ
ohm Resistor Diversi Jumper
Several JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

204
Component Introduction
Introduzione del Componente

The
Il principleèismolto
principio very simple. When
semplice. the switch
Quando is tiltedè in
lo switch a certaindiangle,
inclinato the ball
un certo insidelarolls
angolo, down
sfera and touches
all'interno thegiù
rotola twoe
tocca i due
contacts contattitoconnessi
connected the pins con i pinthus
outside, all'esterno,
triggeringinnescando così il circuito.
circuits. Otherwise Viceversa
the ball will la palla
stay away from starà lontanathus
the contacts, dai
contatti, interrompendo
breaking the circuits. così i circuiti.

205
Fritzing Circuit

In this example,
questo digital
esempio pin 2usato
viene is used to read
il pin the signal
digitale 2 per of Tilt Switch.
leggere il segnale del Tilt Switch.

206
Schematic Diagram
Diagramma Schematico

Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
int tiltState = digitalRead(2);
Serial.println(tiltState);

207
delay(1);
}

Dopo aver
After the caricato
codes i codici sulla
are uploaded to thescheda Mega2560,
Mega2560 è possibile
board, you can openaprire il monitor
the serial monitor seriale perreadings
to see the vedere of
le pins,
letture dei
which
pin, visualizzate
displays 「1」 orcome「1」o「0」quando il Tilt Switch
「0」 when Tilt Switch is vertical è verticale
(bringing (portando
the internal metal balllainto
sfera metallica
contacting interna
with a contatto
the Wire Pins) or
con i Pin
tilted. Filari) o explanation
For detailed inclinato. Per una spiegazione
of codes, you can turndettagliata del
to Part 1-1.4 codice,
Digital confrontare la Parte 1-1.4 Digital Read.
Read.

Immagine Fenomenologica
Phenomenon Picture

208
2.18 Touch Switch Module

Panoramica
In questa lezione imparerai a conoscere il Modulo Interruttore Touch. Può sostituire le tipologie di switch
tradizionali con questi vantaggi: funzionamento conveniente, sensibilità elevata al tocco, controllo preciso e
minima usura meccanica.

Components Required

1 * Modulo Touch Switch 1 * Mega 2560 Board

Several Jumper
Diversi JumperWires
Filari

209
Component Introduction
Introduzione del componente

Touch
Il switch
modulo module works
interruttore byfunziona
touch detectingrilevando
a changeun
in cambiamento
capacitance duedito influence
capacità of an
dovuto
all'influenza di The
external object. un oggetto esterno.
touch plate La piastra
is covered touch è coperta
with insulating material,con
andmateriale isolante
the user does not
e l'utente
come non viene
in contact a contatto
with the electricalcon il circuito elettrico.
circuit.

A capacitive touch
L'interruttore switch
touch has different
capacitivo ha layers—top insulating piastra
diversi strati—una face plate followed by
superiore touch
isolante
plate, another
seguita da unainsulating
piastra layer and
touch, unthen ground
altro stratoplate.
isolante e infine la piastra a terra.

In practice,
pratica, aun
capacitive
sensoresensor can bepuò
capacitivo made on a fatto
essere double-sided PCB abydoppia
su un PCB regarding one usando
faccia, side as the
untouch sensor sensore
lato come and the
opposite
tattile side ascome
e l'altro ground plate di
piastra of the capacitor.
terra When power
del condensatore. is applied
Quando across
si dà these plates,
corrente the two
tra queste platesesse
piastre, get vengono
charged. In
equilibrium
caricate. state, di
In stato theequilibrio,
plates have the same
le piastre voltage
hanno as the
la stessa
power source.
tensione della fonte di alimentazione.

The
Il touch detector
circuito circuit has
di rilevamento an oscillator
tattile whose frequency
ha un oscillatore la cui
frequenza dipende
is dependent dalla capacità
on capacitance del touchpad.
of the touchpad. WhenQuando
a finger
un dito viene
is moved closespostato vicino al touchpad,
to the touchpad, la capacità
additional capacitance
aggiuntiva fa cambiare
causes frequency la oscillator
of this internal frequenza di questo
to change. The
oscillatore interno.
detector circuit tracksIloscillator
circuito frequency
del rilevatore monitora
at timed la
intervals,
frequenza delshift
and when the rilevatore
crossesathe
intervalli di change,
threshold tempo ethe
quando
circuit
lo spostamento
triggers a key-presssupera
event. la soglia di cambiamento, il
circuito innesca un evento di pressione del pulsante.

210
Fritzing Circuit

In this example,
questo pin 2
esempio is used
viene to readilthe
utilizzato pinsignal
2 perof Touch Switch
leggere il
segnale
Module. del Modulo Touch Switch.

Diagramma Schematico
Schematic Diagram

211
Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
int touchState = digitalRead(2);
Serial.println(touchState);
delay(1);
}

Caricato
Uploadedilthe
codice
codessulla scheda
to the Mega2560,
Mega2560 si può
board, you canvedere
see thele lettureof
readings del pindisplaying
pins mostrateon
sul monitor
the seriale.
serial monitor.

When your
Quando la finger
puntatip
deltouches the Touch
dito tocca switchtouch
il modulo module, 「1」will
switch, sul be displayed
monitor on the
seriale serial
verrà monitor;un「1」
mostrato and when you remove
; quando
verrà rimosso,
your finger, 「0」verrà
will mostrato uno 「0」
be be displayed. . Per
As for the una spiegazione
detailed dettagliata
code explanation, youdel
needcodice, necessario consultare
to turnèto
la Parte 1-1.4 Digital Read.
Part 1-1.4 Digital Read.

212
Phenomenon
Immagine Picture
Fenomenologica

213
2.19 Keypad

Panoramica

In questa lezione imparerai ad usare la Tastiera. Può essere applicata a vari tipi di dispositivi, tra cui telefoni
cellulari, fax, forni a microonde e via dicendo. È comunemente usata per l'input dell'utente.

Componeni Richiesti

1 * Modulo Tastiera a Matrice 4x4 1 * Mega 2560 Board

Several Jumper
Diversi JumperWires
Filari

214
IntroduzioneIntroduction
Component del Componente

A
Unkeypad
keypadis èa un
rectangular
array rettangolare
array of 12dior12
16 oOFF-(ON)
16 pulsanti
buttons.
OFF-(ON).
Their Icontacts
loro contatti
are accessed
sono accessibili
via a header
tramite
suitable
un
header
for connection
per il collegamento
with a ribboncon
cable
un or
cavo
insertion
a nastro
into
o per
a printed
l'inserimento
circuit board.
in un circuito
In somestampato.
keypads, In
each
alcune
button
tastiere,
con-
ogni
nectspulsante
with a separate
si connette
contact
con in
unthe
contatto
header,separato
while allnell'header,
the buttonsmentre
share atutti
common
i contatti
ground.
condividono la terra.

Più
More spesso, i pulsanti
often, the buttonssono codificati
are matrix a matrice,
encoded, il che
meaning significa
that each of che
themognuno
bridges di essi collega
a unique pair ofuna coppia univoca
conductors di
in a matrix.
conduttori.
This Questa
configuration configurazione
is suitable è adatta
for polling per la guida which
by a microcontroller, tramite microcontrollore,
can be programmed to che puòan
send essere
outputprogrammato
pulse to each
perthe
of inviare un impulso
four horizontal di output
wires in turn. ad ognuno
During eachdei caviit orizzontali,
pulse, checks the a turno. Durante
remaining ogni wires
four vertical impulso, controllatoi
in sequence,
rimanenti
determine quattro
which one,caviif verticali in sequenza,
any, is carrying perPullup
a signal. determinare se e quale
or pulldown stia
resistors trasportando
should be addedil to
segnale. Resistori
the input di
wires to
pull-up o pull-down dovrebbero essere aggiunti ai cavi di input per preservare l'input del microcontroller da
prevent the inputs of the microcontroller from behaving unpredictably when no signal is present.
comportamenti imprevedibili quando nessun segnale è presente.

215
Fritzing Circuit

In this example,
questo we extend
esempio the del
i pin 1~8 pinsKeypad
1~8 of sono
Keypad to connect
connessi to the
ai pin digital
digitali pins 2~9.
2~9.

216
Schematic Diagram
Diagramma Schematico

217
Code
Codice

IThe codes
codici use the
usano library Keypad.h.
la libreria Keypad.h.Please refer
Riferirsi to Parte
alla Part 44- -4.1
4.1Add
AddLibraries toper
Libraries import the library.
importarla.

#include <Keypad.h>
<Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] =
{
{ '1','2','3','A' },
{ '4','5','6','B' },
{ '7','8','9','C' },
{ '*','0','#','D' }
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
Serial.begin(9600);
}

218
void loop(){
char customKey = customKeypad.getKey();
if (customKey){
Serial.println(customKey);
}
}

After uploading
Dopo the codes
aver caricato to the
il codice Mega2560
sulla scheda board, on theè serial
Mega2560 monitor,
possibile you can
vedere, sul see the value
monitor of the
seriale, key currently
il valore del
pulsante attualmente
pressed on the Keypad. premuto sul Keypad.

Analisi del Codice


Code Analysis

Richiamando la libreria
By calling the Keypad.h Keypad.h,
library, è possibile
you can easily useutilizzare
Keypad. più semplicemente il Keypad.

#include <Keypad.h>

Funzioni della Libreria:


Library Functions:

Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols)
Inizializzathe
Initializes la internal
keymapkeymap
internatoper
be essere
equal touguale alla userKeymap.
userKeymap.
i simboli
userKeymap: The sui on
symbols pulsanti del keypad.
the buttons of the keypads.
configurazione
row, col: Pin configuration.dei pin.
dimensioni
numRows, numCols: Keypad sizes.del keypad.

219
char getKey()
Returns the key
Restituisce, that is pressed,
se premuto, if any. This
il pulsante function is non-blocking.
corrispondente. Quasta funzione non è bloccante (non-blocking).

Phenomenon
Immagine Picture
Fenomenologica

220
2.20 IR Receiver Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn to use
imparerai adIRusare
Receiver Module. Ricevitore
il Modulo IR Receiver is
IR.a component with photocell
È un componente that is tunedtarato
con fotocellula to receive
per
ricevere lalight.
to infrared luce Itinfrarossa. È quasi
is almost always sempre
used usatocontrol
for remote per il rilevamento di un
detection - every TVtelecomando - ogni
and DVD player TV of
has one e player
these inDVD
the
ha uno
front di questi
to receive nella
for the parte from
IR signal frontale, per ricevere
the clicker. il segnale
Inside the IR dalistelecomando.
remote control All'interno
a matching IR LED, di quest'ultimo
which emits IR pulses to
c'è the
tell un LED
TV toIR, che
turn emette
on, pulsazioni
off or change IR per dire alla TV di accendersi, spegnersi o cambiare canale.
channels.

Componenti Richiesti
Components Required

Modulo
1 * IR Ricevitore
Receiver Module IR 11 ** Telecomando IR
IR Remote Controller

1 * Mega 2560 Board Diversi Jumper Filari

221
Component Introduction
Introduzione del Componente

An infrared-receiver
Un is a component
ricevitore ad infrarossi è un which receives infrared
componente signals
che riceve and can
segnali IR independently receive
e può ricevere infrared ray and output
indipendentemente raggi
infrarossi
signals e segnali
compatible withdiTTL
output compatibili
level. It's similar withcon il livello
a normal TTL. È simile
plastic-packaged ad un in
transistor normale
size andtransistor racchiuso
is suitable for in
all kinds of
plastica remote
infrared ed è adatto a and
control tuttiinfrared
i tipi ditransmission.
telecomando a infrarossi ed ogni trasmissione ad infrarossi.

Schematic Diagram
Diagramma Schematico

222
Fritzing Circuit

In this example,
questo we wire
esempio up the leftilpin
colleghiamo pin(-)sinistro
of IR Receiver
(-) del Module
ModulotoRicevitore
GND, the middle pin to
IR a GND, 5V, centrale
il pin and the right
a 5Vpin
e il(S)
pinto pin
destro
11. (S)al pin 11.

223
Code
Codice

IThe codes
codici use the
usano library IRremote.h,
la libreria IRremote.h;about how to import
per importare library, please
la libreria, Parte 4refer
- 4.1toAggiungere
Part 4 - 4.1 Add Libraries.
Librerie.

#include <IRremote.h>
<IRremote.h>
const int recvPin = 11;
IRrecv irrecv(recvPin);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
//Serial.println(results.value,HEX);
if (decodeKeyValue(results.value)!="ERROR"){
Serial.println(decodeKeyValue(results.value));
}
irrecv.resume(); // Receive the next value
}
}

224
After uploading
Dopo the codes
aver caricato to the
i codici Mega2560
sulla board, you can
scheda Mega2560, see that vedere
è possibile the current
chevalue of the
il valore presseddel
corrente button of IR Remote
pulsante
premuto
Controller del telecomando
displays IR monitor.
on the serial viene visualizzato sul monitor seriale.

Analisi del Codice


Code Analysis

Ci sono
There aredue
twoparti importanti
important danotice
parts to osservare
in thisin questo programma.
program.

①Il
①Thecodice
code usa
usesun
an file
extraextra decodeKeyValue.inoto
file decodeKeyValue.ino per decodificare
decode i valori
the values in classdella classe decode_result
decode_result in valori
into key value.The filechiave.
will be
Il file verrà
opened aperto
together insieme
with al file
the main file. principale.

②La funzione
②IR Remote IR Remote
function si ottiene
is achieved chiamando
by calling le funzioni
IRremote.h relativefunctions.
library related alla libreria IRremote.h.

#include <IRremote.h>

Funzioni della Libreria:


Library Functions:

IRrecv(int recvpin)

Crea
Createun oggetto
IRrecv IRrecv
object per controllare
to control a IR Receiverun Modulo Ricevitore IR.
module.

decode_result

In this kit, results


questo are usually
kit i risultati sono8-digit hexadecimal
di solito numbers starting
numeri esadecimali with che
a 8 cifre 00FF.iniziano
You cancon
check decodeKeyValue.ino
00FF. file in the
È possibile controllare il
file decodeKeyValue.ino
sample file. nel file di esempio.

225
void enableIRIn()

Inizializza
Initialize theil IR
modulo
receiverricevitore
module. IR.

int decode(decode_results *results);

Decodifica
Decodes theilreceived
messaggio IR ricevuto.
IR message. 0 → 0dati
Returns non
if no pronti;
data ready,11→ dati pronti.
if data I risultati
ready. Results sono memorizzati
of decoding are stored in results.

void resume()

Restart
Riavviafor
perreceiving
riceverean
unother
altrovalue.
valore.

Immagine Fenomenologica
Phenomenon Picture

226
2.21 Relay Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn about
imparerai Relay Module.
a conoscere il Modulo Relè.

Components Richiesti
Componenti Required

11**Modulo
Relay Module
Relè 11 ** LED
LED Breadboard
Modulo power module
di Alimentazione 11 * 220 ohm resistor
Resistore 220Ω

Several Jumper
Diversi JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

227
Component Introduction
Introduzione del Componente

As we may
Come know,
forse relay
saprai, is a device
il relè which is used
è un dispositivo to provide
utilizzato connection
per fornire labetween two or
connesione tramore
due points
o più or devices
punti in response
o dispositivi in
risposta
to ad signal
the input un segnale diIninput.
applied. otherIn altrerelays
words, parole, i relèisolation
provide permettono un isolamento
between the controllertra il controller
and e idevices
the device as dispositivi,
may
in quanto
work on ACquesti
as wellultimi possono
as on DC. funzionare
However, sia signals
they receive in AC che
fromina microcontroller
DC. Tuttavia, essi devono
which ricevere
works on segnali
DC hence da un
requiring a
microcontrollore,
relay che Relay
to bridge the gap. lavora
is in CC, quindi
extremely richiedono
useful when you un relè
need to per colmare
control a largeilamount
divario.ofIl current
relè è estremamente utile
or voltage with small
quando èsignal.
electrical necessario controllare una grande quantità di corrente o tensione con un piccolo segnale elettrico.

Ci sono
There are55parti
partsin
inogni
everyrelè:
relay:

228
1. Electromagnet
Elettromagnete–– Itconsiste
consistsin
ofun
an nucleo
iron core
diwounded by coil
ferro avvolto daofuna
wires. Whendielectricity
bobina is passed
fili. Quando through,
la corrente lo it becomes
attraversa,Therefore,
magnetic. diventa magnetico. Pertanto, viene chiamato elettromagnete.
it is called electromagnet.

2. Armatura
Armature ––è The
la striscia
movablemagnetica
magneticmobile.
strip is Quando
known aslaarmature.
corrente When
scorre current
attraverso di through
flows essa, la bobina è energiz-
them, the coil is it
zata, producendo
energized così una campo
thus producing magnetico,
magnetic field whichusato pertochiudere
is used make or o aprire
break thei contatti
normally normalmente
open (N/O) oraperti (N/O)
normally o
close
norm. chiusiAnd
(N/C) points. (N/C).
theL'armatura può
armature can be essere
movedmossa sia da
with direct corrente
current continua
(DC) as (DC) che da
well as alternating corrente
current (AC).alternata (AC).

Molla –– When
3. Spring quando nessunaflow
no currents corrente scorre
through attraverso
the coil la bobina sull'elettromagnete,
on the electromagnet, la mollaaway
the spring pulls the armature allontana
so the
l'armatura in be
circuit cannot modo che il circuito non sia chiuso.
completed.

of contatti
4. Set di contacts––ciThere
electrical elettrici sonoare
due tipi
two di contatto:
contact points:

. Normalmente
Normally open -aperto - chiuso
connected whencon
therelè
relayattivo, aperto
is activated, quando
and inattivo.
disconnected when it is inactive.

. Normalmente
Normally close chiuso – apertowhen
– not connected con relè attivo,
the relay is chiuso quando
activated, inattivo.when it is inactive.
and connected

5. Telaio
Moldedstampato – i relè
frame – Relays aresono coperti
covered with con plastica,
plastic per protezione.
for protection.

Funzionamento
Working of Relaydel Relè

Il
Theprincipio
workingdiprinciple
funzionamento
of relay isdel relè When
simple. è semplice.
power Quando viene
is supplied fornita
to the relay,alimentazione, la corrente
currents start flowing throughinizia
the acontrol
fluire
nella
coil; asbobina
a result,di
thecontrollo; di conseguenza,
electromagnet l'elettromagnete
starts energizing. Then the armature inizia ad energizzarsi.
is attracted to the coil,Quindi l'armatura
pulling down viene
the moving
attratta dalla bobina,
contact together chiudendo
thus connecting withil the
contatto mobile,
normally collegando
open contacts. So thecosì il contatto
circuit normalmente
with the load is energized.aperto. Così il
Then breaking
circuito col carico viene energizzato. L'apertura del circuito è simile, poiché il contatto mobile verrà aperto
the circuit would a similar case, as the moving contact will be pulled up to the normally closed contacts under the force of
tramite la forza della molla. In questo modo, l'accensione e lo spegnimento del relè permette di controllare lo
the spring. In this way, the switching on and off of the relay can control the state of a load circuit.
stato di un circuito con un carico elettrico.

229
Fritzing Circuit

In this example,
questo we use
esempio Power Supply
useremo Module
un Modulo di to power the load,use
Alimentazione LED
per dare as an example.
energia al carico, ad esempio un LED.

230
Diagramma
Schematic Schematico
Diagram

Code
Codice

const int relayPin = 9;

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

void loop() {
digitalWrite(relayPin, HIGH);
delay(1000);
digitalWrite(relayPin,LOW);
delay(1000);
}

231
Una
Oncevolta caricati
the codes arei uploaded
codici sulla scheda
to the Mega2560,
Mega2560 board,siyou
potrà
canvedere
see thatil the
modulo
Relay relè che controls
Module controllathe
la closing
chiusura e
and
l'apertura
breaking ofdel
the circuito esterno,
external circuit, cambiando
which il suo
will change stato di
its working funzionamento
state ogni secondo.
a second. For detailed Per una spiegazione
code explanation, refer to Part
dettagliata
1-1.2 Digital del codice, fare riferimento alla Parte 1-1.2 Digital Write.
Write.

Immagine Fenomenologica
Phenomenon Picture

232
2.22 Potentiometer

Overview

In this lesson,
questa you will
lezione learn about
imparerai Potentiometer.
a conoscere Potentiometer
il Poteziometro. Si is a resistor
tratta di uncomponent withresistore
componente 3 terminals
conand its resistance
3 terminali e
il suocan
value valore di resistenza
be adjusted può to
according essere
someregolato in base a qualche variazione regolare.
regular variation.

Componenti
Components Richiesti
Required

1 * potenziometro
potentiometer 1 * Mega 2560 Board

1 * Breadboard

Several Jumper
Diversi JumperWires
Filari

233
Component Introduction
Introduzione del Componente

Il potenziometro
Potentiometer di solito
usually è costituito
consists daand
of resistor un movable
resistore brush.
e una spazzola
When themobile.
brush isQuando
moving
la spazzola
along si muove
the resistor, lungo
there is ila resistore, si generaor
certain resistance unavoltage
certa resistenza o tensione
output depending onin the
uscita, a seconda della posizione.
displacement.

Le
Thefunzioni
functionsdel
of potenziometro nel
the potentiometer incircuito sono
the circuit le follows:
are as seguenti:

1. Fungere
Serving asda partitore
a voltage di tensione
divider

Il potenziometro
Potentiometer un resistoreadjustable
is a ècontinuously regolabile in maniera
resistor. Whencontinua.
you adjustQuando
the shaftsiorregola
slidingilhandle
suo albero
of theopotentiometer,
la sua maniglia a
the
scorrimento,
movable il contatto
contact mobile
will slide on scorrerà
the resistor. sul resistore.
At this A questo
point, a voltage punto,
can be una
output tensioneonverrà
depending emessaapplied
the voltage a seconda
onto
della tensione applicata
the potentiometer and thead esso
angle e movable
the dell'angolo
armin cui
has il braccio
rotated to ormobile ha ruotato
the distance o della distanza a cui si muove.
it moves.

2. Fungere
Serving asda reostato
a rheostat

Per
Whenusare il potenziometro
the potentiometer come
is used as a reostato, si collega
rheostat, connect the ilmiddle
pin centrale ed uno
pin and one degli
of the altri
other 2 pin
2 pins al circuito.
in the Così
circuit. Thus è
you
possibile
can ottenereand
get a smoothly un continuously
valore di resistenza modificato
changed resistance in modo
value fluido
cused by e continuo
moving contact. dal contatto di movimento.

3. Fungere
Serving ascome regolatore
a current di corrente
controller

Quando
When theilpotentiometer
potenziometroacts funge da regolatore
as a current di sliding
controller, the corrente, il terminale
contact di contatto
terminal must scorrevole
be connected deve
as one of essere
the output
collegato
terminals. come uno dei due terminali di uscita.

234
Fritzing Circuit

In this example,
questo we use
esempio the analog
useremo il pin
analogico (A0) per
(A0) to read theleggere
value ilofvalore
the
del potenziometro.
potentiometer. Ruotando
By rotating l'asse
the axis of
del potenziometro,
the potentiometer, possibile
è change
you can the
cambiare la resistance
distribution of distribuzione della
among these
resistenza fra
three pins, changing questi 3 onpin,
the voltage the
cambiando
middle pin. ilWhen
voltaggio del pin
the resistance
centrale. Quando
between the middlelaand
resistenza
a outsidetra
pini
pin centrale
connected to ed
5V esterno connesso
is close to zero (anda
5V vicina a 0Ω
the èresistance (e la resistenza
between the middletra
andil
pin centrale
the other e l'altro
outside pin esterno
pin is close to 10kΩ),è
vicina a 10kΩ),
the voltage la tensione
at the middle al pin
pin is close to
centrale
5 V. The è vicina a 5V.
reverse L'operazione
operation (the
inversa
resistance(la resistenza
between tra ilandpin
the middle a
centrale e ilconnected
outside pin pin esterno connesso
to 5V a
is close to
5V
10kèΩvicina
) will amake
10kΩ) farà
the s' che at
voltage al pin
the
centrale labe
middle pin tensione
close tosarà
0V. vicina a 0V.

235
Schematic Diagram
Diagramma Schematico

Code
Codice

void setup() {
Serial.begin(9600);
}

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}

236
After uploading the codes to the Mega2560 board, you can open the serial monitor to see the reading value of the pin.
Dopo aver caricato i codici sulla scheda Mega2560, si potrà aprire il monitor seriale per vedere i valori letti sul
When rotating the axis of the potentiometer, the serial port monitor will print the value 「0」~「1023」. For the detailed
pin. Quando si ruota l'asse del potenziometro, il monitor della porta seriale stamperà un valore「0」~「1023」.
explanation of code, turn to check Part 1-1.5 Analog Read.
Per la spiegazione dettagliata del codice, controllare la parte Parte 1-1.5 Analog Read.

Phenomenon
Immagine Picture
Fenomenologica

237
2.23 Joystick Module

Overview
Panoramica

In this lesson,
questa you will
lezione, learn something
imparerai qualcosaabout Joystick. L'idea
sul Joystick. The basic idea
base di of
unajoystick
joystick è
is quella
to translate the movement
di tradurre of a stick
il movimento di
un bastoncino
into in una informazione
electronic information elettronica
that a computer cheItilcan
can process. computer può
be applied processare,
to work Può essere
as the controller applicato
of devices, suchper
as
funzionare come controllo di dispositivi, come i robot.
robot.

Componenti Richiesti
Components Required

ModuloModule
1 * Joystick Joystick 11**Mega
Mega2560
2560Board
Board

Several Jumper
Diversi JumperWires
Filari

238
Component Introduction
Introduzione del componente

In order
Per to communicate
comunicare a full range
una gamma of motion
completa to the computer,
di movimenti a joystick
al computer, un needs to measure
joystick the stick's
deve misurare position ondello
la posizione two
stick --
axes suthe
due assi.(left
X-axis -- l'asse X (da
to right) andsinistra a destra)
the Y-axis (up andedown).
l'asse Just
Y (su
aseingiù).
basicProprio come
geometry, the nella geometriapinpoint
X-Y coordinates di base,the
le
coordinate X-Y
stick's position individuano esattamente la posizione del joystick.
exactly.

Per stabilire lathe


To determine posizione
locationdella levetta,
of the stick, ilthe
sistema di control
joystick controllo del joystick
system monitora the
simply monitors semplicemente la posizione
position of each shaft. The
di ogni albero.
conventional Il design
analog convenzionale
joystick delwith
design does this joystick analogico è fatto
two potentiometers, da due resistors.
or variable potenziometri o resistori variabili.

Il
Thejoystick
joystickha anche
also has aun input
digital digitale
input che
that is viene azionato
actuated quandoislo
when the joystick stessodown.
pressed viene premuto verso il basso.

239
Fritzing Circuit

In this example,
questo we getconnetteremo
esempio the GND of theilJoystick
GND del extended to connect
Joystick al GND,with GND,con
il VCC VCCi with
5V, 5V,
VRX VRX with
con il pin
pinA0.
A0.After that,
Succes-
sivamente,
we make VRYfacciamo in modo
connect with che
pin A1, VRY
SW si colleghi
connect con
with pin 8. il pin A1, SW si connetta con il pin 8.

240
Schematic Diagram
Diagramma Schematico

Code
Codice

const int xPin = A0; //the VRX attach to


const int yPin = A1; //the VRY attach to
const int swPin =
= 8;
8; //the
//theSW
SWattach
attachto
to

void setup()
{
pinMode(swPin, INPUT); //set the SW pin to INPUT

241
digitalWrite(swPin, HIGH); //And initial value is HIGH
Serial.begin(9600);
}

void loop()
{
Serial.print("X: ");
Serial.print(analogRead(xPin), DEC); // print the value of VRX in DEC
Serial.print("|Y: ");
Serial.print(analogRead(yPin), DEC); // print the value of VRX in DEC
Serial.print("|Z: ");
Serial.println(digitalRead(swPin)); // print the value of SW
delay(500);
}

Uploadedi the
Caricati codes
codici to the
sulla Mega2560
scheda board, you
Mega2560, can open
si può aprirethe
il serial
monitormonitor to see
seriale perreadings
vedereon
lethe X-axisdell'asse
letture and Y-axis
X of
e
dell'asseasY well
Joystick, del as
Joystick, come
the button lo stato
status del pulsante
of Z-axis. The valuesdell'asse Z. I valori
of the X-axis degliare
and Y-axis assi
theXanalog
e Y sono analogici,
values, variando
which vary within
nell'intervallo「0」
the ~「1023」
range「0」~「1023」 . L'asse
. The Z-axis Z mostra
shows un valore
numerical numerico
value and e is
the state il either
suo stato 「1」
「1」èor o. Refer
「0」 「0」.toRiferirsi alla
Part 1-1.5 Parte
Analog
1-1.5 and
Read Analog Read eRead
1.4 Digital 1.4 Digital
to checkRead
theper
codecontrollare la spiegazione del codice.
explanation.

242
Phenomenon
Immagine Picture
Fenomenologica

243
2.24 MPR121 Module

Overview
Panoramica
In questa
In this lezione
lesson, you willimparerai
learn howcome
to use usare
MPR121.la It's
MPR121. È una when
a good option buona youopzione quando
want to add vuoi
a lot of aggiungere
touch switches tomolti
your
interruttori touch al tuo progetto. L'elettrodo dell'MPR121 può essere esteso con un conduttore. Se colleghi
project. The electrode of MPR121 can be extended with a conductor. If you connect a wire to a banana, you can turn the un
un filo ad una banana, puoi trasformare la banana in uno switch touch, realizzando progetti come un
banana into a touch switch, thus realizing projects such as fruit piano.
pianoforte di frutta.
Components Richiesti
Componenti Required

1 * MPR121 1 * Mega 2560 Board

1 * Breadboard

Several Jumper
Diversi Wires
Jmper Filari

244
Component Introduction
Introduzione del Componente

Add lots ofmolti


Aggiungi touch sensori
sensors to youral
tattili next
tuoproject with this
prossimo easy-to-use
progetto con
questa scheda
12-channel breakout
capacitive a 12sensor
touch canalibreakout
per sensori tattilistarring
board, capacitivi,
the
con protagonista
MPR121. l'MPR121.
This chip can Questo
handle up to 12 chip può touch
individual gestirne fino a 12.
pads.

L'MPR121 supporta
The MPR121 solo for
has support I2C,only
che I2C,
puòwhich
esserecan
implementato con
be implemented
quasi tutti iany
with nearly microcontrollori.
microcontroller.Puoi
Youselezionare unoofdei
can select one 3 indiriz-
4 addresses
zi con
with il ADDR
the pin ADDR, per
pin, for un totale
a total of 48 di 48 touchpad
capacitive capacitivi
touch pads on onein I2C
un
bus 2-cavi
2-wire bus. I2C. Usare
Using questo
this chip is achip è molto
lot easier più
than semplice
doing che fare
the capacitive
il rilevamento
sensing capacitivo
with analog inputs: di input analogici:
it handles gestisce
all the filtering tutti
for you andi filtri
can
per te e può essere
be configured configurato
for more/less per più / meno sensibilità
sensitivity.

Quando
When thel'MPR121 rileva a
MPR121 senses unchange,
cambiamento,
it pulls antira un pinpin
interrupt diLOW.
interrupt a LOW.board
The control La scheda
goingdi
tocontrollo
check thatva
pina to
verificare
see if it is
quel
LOW pin perthe
during vedere
loop. se LOW
Toèdo this, durante
this sensoril ciclo. Per fare
also needs ciò,toil another
access sensoredigital
ha bisogno
pin. di un altro pin digitale.

Elettrodi
Electrodes

Un elettrodo
Electrode è un sensor.
is a touch sensore touch. electrodes
Typically, In genere,canessijust
possono
be someessere
piece ofpezzi di or
metal, metallo
a wire. oBut
unsome
filo. times
Ma alcune volte,on
depending a
seconda
the lengthdella lunghezza
of our delmaterial
wire, or the nostro the
filoelectrode
o del materiale su cui
is on, it can si trova
make l'elettrodo,
triggering puòdifficult.
the sensor essere For
difficile innescare
this reason, the
il sensore.
MPR121 Peryou
allows tale ragione, what
to configure l'MPR121 permette
is needed to triggerdiand
configurare
untrigger anciò che è nececessario per innescare e
electrode.
disinnescare un elettrodo.

245
Fritzing Circuit

In this
in example,
questo we insert
esempio, MPR121l'MPR121
inseriamo into the breadboard. Get the GND
nella breadboard. of MPR121
Connettere connected
il GND to GND, al
dell'MPR121 3.3V to 3V3,
GND, IRQ to
il 3.3V al
3V3, IRQ alpin
the digital pin2,digitale 2, SCL
SCL to the pin al pin SCL(21)
SCL(21), e SDA
and SDA al pin SDA(20).
to the Ci sono
SDA(20). There are12
12elettrodi per
electrodes forsensore touch. Nota:
touch sensing. Note:
l'MPR121 alimentato
MPR121 is èpowered da 3.3V,
by 3.3V, non 5V.
not 5V.

Schematic Diagram

246
Code
Codice

The
Il codesusa
codice usela
the MPR121_JM.
libreria h library.
MPR121_JM. Turnalla
h. Vai to Part 4 -44.1
Parte Add
- 4.1 Libraries
Add for per
Libraries information on how
informazioni sutocome
import Libraries.
importarla.

#include <MPR121_JM.h>
<MPR121_JM.h>
MPR121 mpr121(2, 0x2A, 0x1F);
boolean touchStates[12];
void setup() {
mpr121.mpr121_setup();
Serial.begin(9600);
}
void loop() {
if (!mpr121.checkInterrupt())
{
int touched = mpr121.readTouchInputs();
for (int i = 0; i < 12; i++) {
if (touched & (1 << i)) {touchStates[i] = 1;}
else {touchStates[i] = 0;}
}
for (int i = 0; i < 12; i++)
{Serial.print(touchStates[i]);}
Serial.println();

247
}
}

Dopo aver caricato


After uploading i codici
the codes sulla
to the scheda Mega2560,
Mega2560 lo stato
board, the touch statetouch dei
of pins ofpin dell'MPR121
MPR121 「1」e「0」sarà
「1」and「0」will be registra-

to in un array
recorded in a 12a -12
bitbit di tipotype
boolean boolean che
of array sarà
that willstampato
be printedsul
onmonitor
the serialseriale.
monitor.

Analisi
Code del Codice
Analysis

La funzione
The delthe
function of modulo
moduleè isinclusa nella
included libreria
in the MPR121_JM.h.
library MPR121_JM.h.

#include <MPR121_JM.h>

Funzioni
Library della Libreria:
Functions:

MPR121(int irqpin,uint8_t touThresh,uint8_t relThresh)

Crea una
Creates nuova
a new istanza
instance dell'MPR121.
of the MPR121.

il pin
irqpin: the di richiesta
interrupt interrupt.
request pin.

touThresh: Touch
soglia threshold,the electrode
di tocco, l'elettrodo is recognizedcome
è riconosciuto as a threshold of the
una soglia 「Touch」
dello state.
stato「Touch」.

relThresh: Release
soglia dithreshold,the electrodeèisriconosciuto
rilascio, l'elettrodo recognized as a threshold
come of thedello
una soglia 「Release」 state.
stato「Release」.

The range ofdel


L'intervallo the electrode
valore datadell'elettrodo
del dato value is 0~255. For typical
è 0~255. Per touch application,
una tipica the threshold
applicazione touch, ilvalue candibe
valore in range
soglia può
essere nell'intervallo
0x05~0x30 0x05~0x30,
for example. The smallerad
theesempio. Più
value, the piccolo
more è il valore,
sensitive it is. Thepiù è sensibile.
setting L'impostazione
of the threshold della on
is depended soglia
the
dipende
actual dall'applicazionethe
application.Typically attuale.
touch Normalmente la soglia
threshold is a little biggerdi than
tocco leggermenti
theè release più to
threshold grande
touch della sogliaand
debounce di
rilascio, per avere un debounce di tocco e l'isteresi.
hysteresis.

248
void mpr121_setup()

Imposta il moduloMPR121.
Setup MPR121 module.

bool checkInterrupt()

Make
Fa unainterrupt judgment,
valutazione when the
di Interrupt: electrode
quando state changes,
lo stato the function
dell'elettrodo cambia,returns a Boolean
restituisce valueBooleano「0」.
il valore 「0」.

uint16_t readTouchInputs()

Lo stato
The touchtattile dell'elettrodo
state of the electrode produce
produces un valore value.
a Boolean Booleano. La funzione
The function accumula
accumulates i valori Booleani
the Boolean generatibyda
values generated all
tuttielectrodes
the gli elettrodi in sequenza,
in sequence into a in un numero
12-bit binarioasathe
binary number 12return
bit, restituito come
value. If the firstvalore. Se il primo
and eleventh e l'undicesimo
electrodes are touched,
elettrodo vengonoistoccati,
「100000000010」 viene restituito「100000000010」.
returned.

249
Phenomenon
Immagine Picture
Fenomenologica

250
2.25 Rotary Encoder Module

Overview

In this lesson,
questa you will
lezione learn about
imparerai Rotary Encoder.
a conoscere A rotary
l'Encoder encoder is
Rotativo. È an
unelectronic switch
interruttore with a set of
elettronico conregular
una pulses in
serie di
impulsi regolari
strictly timing in unaWhen
sequence. sequenza rigidamente
used with temporizzata.
IC, it can achieve Quando
increment, usato
decrement, conturning
page IC, può
andrealizzare incrementi,
other operations such
decrementi,
as cambio
mouse scrolling, pagina
menu ed altre
selection, andoperazioni
so on. come scorrimento del mouse, selezione del menu e via dicendo.

Componenti Richiesti
Components Required

Encoder
1 * Rotary Rotativo
Encoder 11**Mega
Mega2560
2560Board
Board

Several Jumper
Diversi JumperWires
Filari

251
Introduzione
Component del Componente
Introduction

Ci sono
There principalmente
are mainly due
two types of tipiencoders:
rotary di rotary encoder:
absolute assoluti o
and incremental
incrementali (relativi).
(relative) encoders. In questo
An incremental oneesperimento
is used in this verrà usato quello
experiment.
incrementale.
Most rotary encoders have 5 pins with three functions of turning left &
right and
Molti pressing
rotary down.hanno
encoder Pin 1 and
5 pin
pin 2con
are switch wiring terminals
tre funzioni: used
rotazione a
to press. &
sinistra Pindestra
4 is generally connected
e pressione deltopulsante.
ground. Pin 3 and
I pin 1 pin
e 25 are
sonofirsti
connected to
terminali a pull-up
utilizzati resistor
per and then toIl VCC
la pressione. pinand
4 they can generate
è generalmente
two-phase asquare
connesso terra.waves
I pin whose
3 e 5phase
sono difference is 90connessi
innanzitutto ° . Usuallyad
these
un
waves are called channel A and channel B as shown below:
resistore pull-up e poi alla VCC e possono generare onde quadrate
a due fasi la cui differenza di fase è di 90°. Normalmente queste onde
As shown on the right, when channel A changes from high level to low level, if
vengono chiamate canale A e canale B come mostrato di seguito:
channel B is high level, it indicates the rotary encoder spins clockwise (CW); if at
that moment
Come mostratochannel B is low
a destra, level, itimeans
quando spins counterclockwise
cambiamenti del canale A dal(CCW). So
livello
if we read
high the value
al livello low,ofsechannel
in quelB when
momento channel A is lowBlevel,
il canale we can
è high, know
indica in
una
which direction
rotazione thedel
oraria rotary encoder
rotary rotates.
encoder (CW); se invece è low, la rotazione
sarà antioraria (CCW). Perciò se leggiamo il valore del canale B quando il
canale A è al livello basso, possiamo capire in quale direzione il rotary
encoder ruota.

252
Fritzing Circuit

In this example,
questo we can
esempio connectcollegare
possiamo the Rotary Encoder
il pin pin directly
dell'Encoder to the direttamente
Rotativo Mega 2560 Board pin,
al pin connect
della Megathe GNDil of
2560, GNDthe
dell'Encoder alto
Rotary Encoder GND「+」 ai 5V,
GND, 「+」 SWSW
to 5V, al pin digitale
to digital pin4,
4, DT
DT al
to pin digitale
digital 3, e CLK to
pin 3, and al digital
pin digitale
pin 2. 2.

Diagramma
Schematic Schematico
Diagram

253
Code
Codice

const int clkPin= 2; //the clk attach to pin2


const int dtPin= 3; //the dt attach to pin3
const int swPin= 4 ;//the number of the button
int encoderVal = 0;
void setup()
{
//set clkPin,dePin,swPin as INPUT
pinMode(clkPin, INPUT);
pinMode(dtPin, INPUT);
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);
Serial.begin(9600); // initialize serial communications at 9600 bps
}
void loop()
{
int change = getEncoderTurn();
encoderVal = encoderVal + change;
if(digitalRead(swPin) == LOW)//if button pull down
{
encoderVal = 0;

254
}
Serial.println(encoderVal); //print the encoderVal on the serial monitor
}
int getEncoderTurn(void)
{
static int oldA = HIGH; //set the oldA as HIGH
static int oldB = HIGH; //set the oldB as HIGH
int result = 0;
int newA = digitalRead(dtPin);//read the value of clkPin to newA
int newB = digitalRead(clkPin);//read the value of dtPin to newB
if (newA != oldA || newB != oldB) //if the value of clkPin or the dtPin has changed
{
// something has changed
if (oldA == HIGH && newA == LOW)
{
result = (oldB * 2 - 1);
}
}
oldA = newA;
oldB = newB;
return result;
}

255
You
Si will see
vedrà the angular displacement
lo spostamento of the rotary rotativo
angolare dell'encoder encoder printed on sul
stampato Serial Monitor.
Monitor When Quando
Seriale. you turn the rotary
si ruota encoder
l'encoder
in senso oriario,
clockwise, lo spostamento
the angular angolare
displacement is aumenta;
increased; quando
when turn lo si gira inthe
it counterclockwise, senso antiorario,
displacement lo spostamento
is decreased. If you
diminuisce.
press Se si
the switch onpreme l'interruttore,
the rotary lereadings
encoder, the letture si azzerano.
will return to zero.

Analisi del Codice


Code Analysis

Quando l'Encoder
When Rotary Rotativo
Encoder viene
is used, the usato, il livello
following dei pin
situations puòlevel
of pin avere le
will
seguenti
occur. situazioni:


① Quando l'albero
When rotating theruota, dtPin will
shaft, dtPin andrà da livello
go from high high a livello
level to low.
low level.


② clkPin rimarrà
clkPin alto quando
will remain l'albero
high level ruota
when theinshaft
sensorotates
orario,clockwise,
altrimentiitva
otherwise a low.
goes low level.

③ When
③ Quando
thel'albero è premuto,
shaft is pressed, swPin
swPin avrà low
will have valore low.
level.

Da ciò,
From il flusso
this, del programma
the program è mostrato
flow is shown a destra.
on the right.

Per un'analisi
For detailed dettagliata
analysis della valutazione
of potential state changedel potenziale
judgment, cambio
please refer di
to
stato, si prega di fare riferimento alla Parte 1-1.10 State Change Detec-
Part 1-1.10 State Change Detection.
tion.

256
Phenomenon
Immagine Picture
Fenomenologica

257
2.26 Photoresistor

Overview

In this lesson,
questa you will
lezione learn about
imparerai Photoresistor.
a conoscere Photoresistor
il Fotoresistore. is applied in many
È applicato molti electronic goods, come
beni elettronici, such asesposimetri,
the camera
radiosveglie,
meter, dispositivi
clock radio, alarmd'allarme
device (as(come
beamrilevatore
detector),dismall
fascio), piccole
night lights,luci notturne,
outdoor orologi
clock, da esterno,
solar street lamps lampioni
and etc.
solari, ecc. Ilis Fotoresistore
Photoresistor è applicato
placed in a street in un
lamp to control lampione
when the lightper controllare
is turned quando
on. Ambient lightlafalling
luce on accesa.
è the La luce
photoresistor
ambientale
causes streetche cade
lamps sul fotoresistore
to turn on or off. determina l'accensione o lo spegnimento dei lampioni.

Componenti Richiesti
Components Required

Fotoresistore
1 * Photoresistor 11**10K
resistore 10KΩ
ohm resistor Diversi
Several Jumper Filari
Jumper Wires

1 * Mega 2560 Board 1 * Breadboard

258
Component Introduction
Introduzione del componente

A photoresistor
Un fotoresistoreorophotocell is aèlight-controlled
fotocellula variable resistor.
un resistore variabile The resistance
controllato dalla luce.ofLaa resistenza
photoresistor
di
decreases
un with increasing
fotoresistore incident
diminuisce conlight intensity; indell'intensità
l'aumentare other words, it exhibits
della lucephoto conductivity.
incidente; in altreA
photoresistor
parole, mostracanuna
be applied in light-sensitive
foto-conduttività. detector circuits,
Un fotoresistore puòand light-applicato
essere and darkness-activated
in circuiti di
switching circuits.
rilevatori sensibili alla luce e circuiti di commutazione
attivati dalla luce e dall'oscurità
Fritzing Circuit
Fritzing Circuit
In this example, we use analog pin ( A0 ) to read the value
of questo
In photoresistor.
esempio Oneusiamo
pin of photoresistor is connected
il pin analogico to
(A0) per
5V, the other
leggere is wired
il valore delup to A0. Besides,
fotoresitore. Unapin
10kΩ resistor is
è connesso
needed beforead
ai 5V, l'altro theA0.
other pin is èconnected
Inoltre, to GND.
necessario un resistore
da 10kΩ prima che l'altro pin sia connesso a terra.
Schematic Diagram
Diagramma Schematico

259
Code
Codice

void setup() {
Serial.begin(9600);
}

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}

After uploading
Dopo the codes
aver caricato to the
i codici Mega2560
sulla board, you can
scheda Mega2560, open the serial
è possibile apriremonitor to see
il monitor the read
seriale pervalue of the
leggere il pin. When
valore del
pin. Quandolight
the ambient la luce ambientale
becomes stronger,diventa più will
the reading forte, la lettura
increase incrementerà
correspondingly, anddi conseguenza,
the e il is
pin reading range range di
「0」~ lettura
「1023」 .
del pin è「0」
However, ~「1023」
according . environmental
to the Tuttavia, in base alle condizioni
conditions ambientali of
and the characteristics e the
allephotoresistor,
caratteristiche del fotoresistore,
the actual reading rangeil
range
may bedi lettura
smaller effettivo
than potrebbe
the theoretical essere
range. For a più piccolo
detailed di quello
explanation teorico.
of the Per una
code, refer spiegazione
to Part 1-1.5 Analogdettagliata
Read. del
codice, riferirsi alla Parte 1-1.5 Analog Read.

260
Phenomenon
Immagine Picture
Fenomenologica

261
2.27 Thermistor

Overview
Panoramica
In questa
In this lezione
lesson, imparerai
you will come
learn how usare
to use il termistore.
thermistor. Puòcanessere
Thermistor utilizzato
be used come circuit
as electronic componente per for
components la
compensazione di temperatura dei circuiti elettronici negli strumenti, come misuratori di corrente, di portata,
temperature compensation of instrument circuits. In the current meter, flowmeter, gas analyzer, and other devices. It can
analizzatori di gas e altri dispositivi. Può essere usato come protezione dal surriscaldamento, relé senza
also be used for overheating protection, contactless relay, constant temperature, automatic gain control, motor start, time
contatto, temperatura costante, controllo automatico del guadagno, avvio di motori, ritardo temporale,
delay, color TV automatic degaussing, fire alarm and temperature compensation.
degaussing automatico della TV, allarmi antincendio e compensazione di temperatura.

Components Richiesti
Componenti Required

1 * Termistore
Thermistor 11 **resistore
10K ohm 10KΩ
resistor Diversi
SeveralJumper Seriali
Jumper Wires

1 * Mega 2560 Board 1 * Breadboard

262
Component Introduction
Introduzione del componente

Thermistor
Il is aèsensitive
termistore element,sensibile
un elemento and it hasalla
twotemperatura
types: Negative Temperature
e può Coefficient
essere di due tipi:(NTC) and Positive
coefficiente di
temperatura negativo(PTC),
Temperature Coefficient (NTC)
alsooknown
positivo (PTC).
as NTC La Its
and PTC. suaresistance
resistenza
variesvaria significativamente
significantly conThe
with temperature. la
temperatura.
resistance La thermistor
of PTC resistenza increases
del termistore PTC aumenta
with temperature con
,while la condition
the temperatura, mentre
of NTC la condizione
is opposite di NTC
to the former. In
è opposta
this alla prima.
experiment we use In questo esperimento usiamo NTC.
NTC.

Il
Theprincipio
principleèis che la resistenza
that the del
resistance of thetermistore NTC changes
NTC thermistor cambia with
con the
la temperatura
temperature ofdell'ambiente esterno.
the outer environment.
Rileva
It la the
detects temperatura in tempo reale
real-time temperature dell'ambiente.
of the Quando
environment. When thela termperatura
temperature getsaumenta,
higher, thelaresistance
resistenza del
of the
termistore decreases.
thermistor diminuisce. Quindi
Then the il dato di
voltage voltaggio
data viene convertito
is converted in digitalebydall'adattatore
to digital quantities A/D.The
the A/D adapter. La
temperaturaininCelsius
temperature CelsiusoroFahrenheit
Fahrenheit viene prodotta
is output tramite programmazione.
via programming.

In this experiment, a thermistor and a 10k pull-up resistor are used. Each thermistor has a normal resistance. Here it is 10k
In questo
ohm, whichesperimento vengono
is measured under utilizzati
25 degree un termistore ed un resistore da 10KΩ.
Celsius.

Qui viene
Here is the indicata la relazione
relation between tra la resistenza
the resistance e la temperatura:
and temperature:

– 1/TN)
β(1/TK – 1/TN)
RTT =R
R =RN expB(1/TK
N exp

RTT is
R è la
theresistenza
resistance del termistore
of the NTC quando
NTC thermistor temperaturaisèTKT.K.
la temperature
when the

RN
R è la
N is theresistenza
resistance del termistore
of the NTC sotto
NTC thermistor underlathe
temperatura nominale
rated temperature TN. TN. Qui,
Here, theil numerical value of diRNRNis 10k.
valore numerico è 10k.

TKK is
T è la temperatura
a Kelvin Kelvin
temperature e the
and l'unità
unitdi
is misura K. numerical
K. Here, èthe Qui, il valore
valuenumerico di TK+
of TK is 273.15 è 273.15
degree+Celsius.
gradi Celsius.

TN
T è la temperatura Kelvin numinale; l'unità è ancora K. Qui, il valore numerico
N is a rated Kelvin temperature; the unit is K too. Here, the numerical value of TN
di TN è 273.15+25.
is 273.15+25.

263
E
And B(beta),lathe
β (beta), costante
materialdel materiale
constant delthermistor,
of NTC termistoreisNTC, è anche
also called heatchiamata
sensitivityindice di sensibilità
index with al calore
a numerical e il suo
value 3950.
valore numerico è 3950. exp è l'abbreviazione di esponenziale, e la base è il numero naturale ed equivale
exp is the abbreviation of exponential, and the base number e is a natural number and equals 2.7 approximately.
approssimativamente a 2,7. La conversione di questa formula in permette di ottenere la temperatura Kelvin,
Convert thisdiformula
maggiore 273.15Tdella
K=1/(ln(RT/RN)/B+1/T
temperatura N) to get Kelvin temperature that minus 273.15 equals degree Celsius.
Celsius.
TK=1/(ln(RT/RN)/β + 1/TN)
This relation is an empirical formula. It is accurate only when the temperature and resistance are within the effective range.
Questa relazione è una formula empirica. È accurata solo quando la temperatura e la resistenza sono
Fritzing Circuit
nell'intervallo effettivo.

Fritzing
In Circuit
this example, we use the analog pin A0 to get the value of
Thermistor. One pin of thermistor is connected to 5V, and
In questo esempio usiamo il pin analogico A0 per
the other is wired up to A0. At the same time, a 10k Ω
avere il valore del Termisotre. Un suo pin è connesso a
resistor is connected with the other pin before connecting
5V e l'altro ad A0. Allo stesso tempo, un resistore da
to GND.
10KΩ è connesso all'altro pin prima di GND (terra).
Schematic Diagram
Diagramma Schematico

264
Code
Codice

#define analogPin A0 //the thermistor attach to


#define beta 3950 //the beta of the thermistor
#define resistance 10 //the value of the pull-up resistor

void setup()
{
Serial.begin(9600);
}
void loop()
{
//read thermistor value
long a = analogRead(analogPin);
//the calculating formula of temperature
float tempC = beta / (log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
float tempF = 1.8 * tempC + 32.0;
Serial.print("Temp: ");
Serial.print(tempC);
Serial.println("degree Celsius");
Serial.print("Temp: ");
Serial.print(tempF);

265
Serial.println("degree Fahrenheit");
delay(200); //wait for 200 milliseconds
}

Dopo aver caricato


After uploading il codice
the code to thesulla schedaboard,
Mega2560 Mega2560,
you can possibile
è open aprire
the serial il monitor
monitor seriale
to check theper controllare
current la The
temperature.
temperatura corrente.
Kelvin temperature La temperatura
is calculated accordingKelvin
to the viene calcolata
formula TK=1/(lnsecondo la formula
(RT/RN)/B+1/ TN). TK=1/(ln(RT/RN)/B+1/TN).

Immagine Fenomenologica
Phenomenon Picture

266
2.28 Sound Sensor Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai adto use ailsound
usare sensor
modulo module.
sensore The sound
sonoro. sensor
Fornisce un module provides an
modo semplice pereasy way to
rilevare il detect
suono e viene
sound and generalmente
is generally used for utilizzato per rilevare
detecting sound l'intensità del suono.
intensity.

Componenti
Components Richiesti
Required

Modulo
1 * Sound Sensore
Sensor Sonoro
Module 11 ** Mega
Mega 2560
2560 Board
Board

Several Jumper
Diversi JumperWires
Filari

267
Component Introduction
Introduzione del Componente

Questo modulo
This module can può essere
be used for utilizzato per applicazioni
security, switch, di sicurezza,
and monitoring scambio
applications. e monitoraggio.
Its accuracy La sua
can be easily precisione
adjusted for the
può essre facilmente
convenience of usage. regolata per la comodità d'uso.

Esso
It usesusa un microfono
a microphone che
which fornisce
supplies thel'input adan
input to unamplifier,
amplificatore, un rilevatore
peak detector di picco
and buffer. Whenethe
un sensor
buffer.detects
Quando il
a sound,
sensore rileva
it processes un suono,
an output elabora
signal voltageuna tensione
which dela segnale
is sent to di uscita
micro-controller cheperforms
then viene inviata ad un
necessary microcontrollore,
processing.
quindi esegue l'eleborazione necessaria.
This module has two outputs:
Questo modulo ha due output:
① AO: analog output, real-time output voltage signal of microphone.
① AO: uscita analogica, segnale di tensione di uscita in tempo reale del microfono.
② DO: when the intensity of the sound reaches a certain threshold, the output is a high or low level signal. The threshold
② DO: quando
sensitivity can bel'intensità
achieved bydel suono raggiunge
adjusting una certa soglia, l'output sarà un segnale di livello high o low.
the potentiometer.
La sensibilità della soglia può essere ottenuta regolando il potenziometro.

268
Fritzing Circuit
In this example, we can directly connect the
In questo
pin of Soundesempio possiamo
Sensor Module collegare
to the pin of
direttamente
Mega il pinconnect
2560 Board, del Modulo Sensore
the pin「G」 of
Sound
Sonoro Sensor Module
al pin della to GND,
Scheda Mega the
2560,pin
il
「+」to 」del
pin「G 5V, AO to analog
modulo pinilA0,
aGND, and D0 5V,
pin「+」a to
digital pinanalogico
A0 al pin 2. A0 e D0 al pin digitale 2.

Diagramma Schematico

269
Code
Codice

void setup() {
pinMode(2,INPUT);
Serial.begin(9600);
}
void loop() {
int sensorDigitalValue= digitalRead(2);
int sensorAnalogValue = analogRead(A0);
Serial.print("Digital Reading: ");
Serial.println(sensorDigitalValue);
Serial.print("Analog Reading: ");
Serial.println(sensorAnalogValue);
Serial.println("");
delay(1);
}

After uploading
Dopo the code
aver caricato to the Mega2560
il codice board,
sulla scheda you can open
Mega2560, the serial
è possibile monitor
aprire to see the
il monitor read value
seriale of the pin.
per vedere When
il valore
letto dal pin.sound
the ambient Quando
getsil louder,
suono the
ambientale diventa
digital reading is più
「1forte, la lettura
」 (adjust digitale è「1 」(regolare
the potentiometer il potenziometro
of the module to modify the
del modulo
threshold to per modificare
trigger la level),
the high soglia and
di innesco del livello
the reading valuehigh), e ilanalog
of the valore pin
lettowill
dalchange
pin analogico cambierà
significantly; whenbru-
the
scamente; quando
environment is quiet,l'ambiente è silenzioso,
the digital reading is 「0」 la lettura
and thedigitale la lettura
è「0」echanges
analog reading analogica cambia dolcemente.
smoothly.

Il range
The della
range lettura
of analog analogica
reading è「0」
is「0」 ~「1023」
~「1023」 , ma è influenzato
, but influenced by the thedalle condizionicondition
environmental ambientali
andethe
dalle caratteristi-
characteristics of

270
che delsensor,
sound sensorethe
sonoro;
actualil campo
readingdirange
letturamay
effettivo
be smaller
può essere
than inferiore
the theoretical
a quelloone.
teorico.
If anSe
oscilloscope
si utilizza unis
used, the changing
oscilloscopio, of analog reading
il cambiamento of the
della lettura sound sensor
analogica will besonoro
del sensore more obvious.
sarà più evidente.

About
Per unathe detail codedettagliata
spiegazione explanation,
delrefer to Part
codice, 1-1.5
riferirsi allaAnalog ReadAnalog
Parte 1-1.5 and Part 1-1.4
Read Digital
e alla Read.Digital Read.
Parte 1-1.4

Phenomenon Picture
Immagine Fenomenologica

271
2.29 Water Sensor Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai to use
come a water
usare sensor module.
un modulo sensore A water Èsensor
acqua. moduleper
progettato is designed for water
rilevare l'acqua, detection,
può essere
largamente
which can be usato
widely nel
usedrilevamento delle
in sensing the precipitazioni,
rainfall, del livello
water level, even dell'acqua
the liquid leakage. e persino della perdita di liquido.

Componenti Richiesti
Components Required

Sensore
1 * Water di Rilevamento
Level del Livello dell'Acqua
Detection Sensor 11 ** Mega
Mega 2560
2560 Board
Board

Several Jumper
Diversi JumperWires
Filari

272
Component Introduction
Introduzione del Componente

This sensor works by having a series of exposed traces connected to ground. Interlaced between the grounded traces are
Questo sensore funziona tramite uana serie di tracce esposte collegate a terra. Intrecciate tra le tracce a terra ci
the sense traces.
sono le tracce sensoriali.
The sensor traces have a weak pull-up resistor of 1 MΩ. The resistor will pull the sensor trace value high until a drop of
Le tracce
water sensoriali
shorts hanno
the sensor una
trace to thedebole resistenza
grounded trace. di pull-up di 1MΩ. Il resistore tirerà su il valore della traccia
sensoriale finché una goccia di acqua cortocircuita la traccia sensoriale con la traccia a terra.
This item can judge the water level through with a series of exposed parallel wires stitch to measure the water
droplet/water
Questo size. può determinare il livello dell'acqua tramite una sierie di fili paralleli esposti per misurare la
elemento
goccia d'acqua/dimensione dell'acqua.
The core part of water level sensor is an amplification circuit composed of a transistor and several comb-shape PCB cables.
When
Il placed
cuore in water, del
del sensore the comb-shape cable will
livello dell'acqua è un change its resistance
circuito with the depth
di amplificazione of the water
composto da unand convert the
transistore depth
e diversi
signal into an electrical signal, and output analog value can directly be used in the program function, then to achieve the
cavi PCB a pettine. Quando viene posizionato in acqua, il cavo a forma di pettine cambierà la sua resistenza con
function of water level alarm.
la profondità dell'acqua e convertirà il segnale di profondità in un segnale elettrico, e il valore analogico di
uscita può essere utilizzato direttamente nella funzione del programma, quindi per ottenere una funzione di
allarme del livello dell'acqua.

273
Fritzing Circuit

In this
questo
example,
esempio
we collegiamo
directly connect
direttamente
the pins of
i pin
Water
del Sensor
ModuloModule
Sensore
toAcqua
pins ofaiMega
pin della
2560Scheda
Board. We
Mega
use2560.
analog
A0 to get
Usiamo the valueA0
l'analogico of per
Water Sensor
avere Mod-
il valore
ule,
del and get the
Modulo, ed pin「S」of Water Sensor
avere il pin「S」del
Module
Modulo to
su A0,
A0, 「-」to GND,「+」a
「-」a GND, 「+」to
5V.5V.

Schematic
DiagrammaDiagram
Schematico

274
Code
Codice

void setup() {
Serial.begin(9600);
}

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}

After uploading
Dopo the code
aver caricato to the Mega2560
il codice board,
sulla scheda you can open
Mega2560, the serial
è possibile monitor
aprire to see the
il monitor read value
seriale of the pin.
per vedere As the
il valore
letto level
water dal pin.
rises,Man mano increase.
the readings che il livello dell'acqua
Readings aumenta,
vary within the rangele「0」
lettura incrementano.
~「1023」 Le by
, but influenced letture variano nel
the environmental
range「0」 ~「1023」
condition and , ma sono of
the characteristics influenzate
water leveldalle
sensor,condizioni ambientali
the actual reading rangeemay
dalle
be caratteristiche
smaller than the del sensore
theoretical del
range.
livello
Refer todell'acqua; il range
Part 1-1.5 Analog di to
Read lettura
checkeffettivo
the detailpuà
codeessere inferiore all'intervallo teorico. Riferirsi alla Parte 1-1.5
explanation.
Analog Read per controllare la spiegazione dettagliata del codice.

275
Phenomenon
Immagine Picture
Fenomenologica

276
2.30 IR Obstacle Avoidance Sensor

Overview
Panoramica
In questa
In this lezione
lesson, imparerai
you will come
learn how utilizzare
to use il Sensore
IR Obstacle IR Rilevamento
Avoidance Sensor. This Ostacoli. comunemente
module isÈcommonly installato
installed in and
on the car
auto e robot per verificare l'esistenza di ostacoli di fronte. Inoltre è un dispositivo ampiamente usato nei
robot to judge the existence of the obstacles ahead. Also it is widely used in hand held device, water faucet and so on.
dispositivi portatili, rubinetti dell'acqua e via dicendo.
Components Richiesti
Componenti Required

1 * IR Obstacle Avoidance Sensor Module 1 * Mega 2560 Board

Several
Diversi Jumper
JumperWires
Filari

Component Introduction
Introduzione del componente

An IR
Un Obstacle
sensore di Sensor works
ostacolo a IRinfunziona
accordance with theil infrared
secondo reflection
principio principle
di riflessione to detect
delle onde obstacles.
infrarosseWhen there is no
per rilevare gli
ostacoli.
object, theQuando non c'èreceives
infrared receiver oggetto, il ricevutore
no signals; a infrarossi
when there nonahead
is an object ricevewhich
segnali; quando
blocks c'è un
and reflects theostacolo che
infrared light,
blocca e riflette
the infrared la luce,
receiver il ricevitore
will receive signals.rileverà dei segnali.

277
Fritzing Circuit

We can directly
Possiamo connect
collegare the pins of IRi Obstacle
direttamente Sensor Module
pin del Modulo Sensorewith the pins
Ostacoli IRofcon
Mega 2560
i pin Board.
della The digital
Scheda Mega pin 2 isIlused
2560. pin
digitale
to 2 èsignal
read the usatoofper leggere Avoidance
IR Obstacle il segnale Sensor
del Modulo. Connettiamo
Module. il VCC
We get the VCC of IRdel Modulo
Sensor conconnected
Module i 5V, GNDtoal5V,
GND e
GND
OUT
to al pin
GND, OUTdigitale 2. pin 2.
to digital

Diagramma Schematico
Schematic Diagram

278
Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
Serial.println(digitalRead(2));
delay(1);
}

Caricati
Uploadedi codici sullatoscheda
the codes Mega2560,
the Mega2560 è possibile
board, visualizzare
you can see le letture
the readings of pins dei pinserial
on the sul monitor
monitor.seriale.
When IR Quando il
Obstacle
Modulo Sensore
Avoidance IR di Rilevamento
Sensor Module detects thereOstacoli percepisce
is something che
covering c'è qualcosa
ahead, che 「0」
there appears copre
ondavanti,
the serialsul monitor
monitor; seriale
otherwise,
appare「0」
「1」is ; altrimenti
displayed. Refer toviene mostrato「1」.
Part 1-1.4 Digital ReadRiferirsi
to checkalla Parte code
the detail 1-1.4explanation.
Digital Read per controllare la spiegazione
dettagliata del codice.

279
Phenomenon
Immagine Picture
Fenomenologica

280
2.31 PIR Module

Overview
Panoramica

In questa
In this lezione
lesson, imparerai
you will adtoutilizzare
learn how il Modulo
use PIR Module. ThePIR.
PIR Ilsensor
sensore PIR infrared
detects rileva laheat
radiazione
radiationtermica infrarossa
or the presence of
o la presenza
organisms di organismi
that emit che
infrared heat emettono
radiation. radiazione
This module termica
is widely used infrarossa. Questo
in daily life for modulo
our intruder è largamente
alarm and visiting
usato
prompt.nella vita quotidiano per i nostri allarmi d'intrusione e campanelli.

Componenti Richiesti
Components Required

1 * Modulo PIR
PIR Module 11**Mega
Mega2560
2560Board
Board

Several
Diversi Jumper
JumperWires
Filari

281
Component Introduction
Introduzione del componente

Thesensore
Il PIR sensor is split
PIR into twoinslots
è diviso duethatslot
are connected
collegati toad
a differential amplifier.
un amplificatore
differenziale. Ogni volta
Whenever a stationary che
object unfront
is in oggetto
of thestazionario si trova
sensor, the two davantithe
slots receive al
sensore, i due
same amount slot ricevono
of radiation la output
and the stessaisquantità di radiazione
zero. Whenever a movinge object
l'uscita è
is in
zero. Ogni
front of volta che
the sensor, oneun
of oggetto in movimento
the slots receives si trovathan
more radiation davanti al sensore,
the other, which
uno degli
makes slot riceve
the output più high
fluctuate radiazioni dell'altro,
or low. This changeilinche fa fluttuare
output voltage isl'uscita in
a result of
alto o in of
detection basso. Questo cambiamento nella tensione di uscita è il risultato
motion.
del rilevamento del movimento.
After the sensing module is wired, there is a one-minute initialization. During the
initialization, module will output for 0~3Dopo
timesche il modulo
at intervals. di the
Then rilevamento è stato
module will camblato,
be in the standbyc'è un'inizializzazione
mode. Please keep the
interference of light source and other di sources awayDurante
1 minuto. from thel'inizializzazione,
surface of the module so as
il modulo to avoidun
emetterà theoutput
misoperation
0~3
volte
causeda by
intevalli. Quindi ilsignal.
the interfering modulo sarà
Even in modalità
you'd better usestandby.
the moduleSi prega di too
without tenere lontane
much le interferenze
wind, because the windluminose
can also
ed altre fonti
interfere dalla
with the superficie del modulo per evitare il malfunzionamento causato dal segnale interferente.
sensor.
Sarebbe meglio
Two trigger modes:inoltre utilizzare
(choosing il modulo
different modes senza troppo
by using vento,cap).
the jumper perché il
vento può anch'esso interferire con il sensore. Due modalità di trigger
Distance
(scelta Adjustment
di diverse modalità utilizzando il cappuccio del ponticello):

Turning the knob of the distance adjustment potentiometer clockwise, the range
Regolazione della distanza
of sensing la
Ruotando distance
manopolaincreases, and the maximum
del potenziometro sensing distance
di regolazione dellarange is about
distanza in
0-7 meters. If turn it anticlockwise, the range of sensing distance is reduced,
senso orario, il range della distanza di rilevamento aumenta e l'intervallo and
the minimum sensing distance range is about 0-3 meters.
massimo è di circa 0-7m. Se ruotato in senso antiorario, il range
diminuisce e l'intervallo minimo è di circa 0-3m.

282
Delay Adjustment
Regolazione Ritardo
Rotate the knob
Ruotando of the delay
la manopola adjustment potentiometer
del potenziometro clockwise,
di regolazione you caninalso
del ritardo see orario,
senso the sensing delay increasing.
è possibile aumentare The
il
maximum
ritardo di of the sensing delay
rilevamento. can reach
Il massimo up todi
ritardo 300s. On the contrary,
rilevamento if rotatefino
può arrivare it anticlockwise,
a 300s. Al you can shorten
contrario, the delay
se ruotato in
with
sensoa minimum ofè5s.
antiorario, possibile abbrebiare il ritardo fino ad un minimo di 5s.

Two
Due trigger modes:
modalità (choosing
di innesco differentlemodes
(scegliere by using
differenti the jumper
modalità cap).
usando il cappuccio del ponticello).

 H:
H: Repeatable
modalità di trigger mode,
innesco ripetibile,
after sensing
dopothe human
aver body,un
rilevato thecorpo
module outputs
umano, il high level.emette
modulo During un
the livello
subsequent
high.
Nel successivo
delay periodo di
period, if somebody ritardo,
enters se qualcuno
the sensing entra
range,the nellowill
output spazio
keepdi rilevamento,
being l'uscita sarà ancora high.
the high level.

 L:Non-repeatable triggernon
L: modalità di innesco mode,ripetibile,
outputs high level
emette unwhen it senses
livello the human
high quando body.
rileva unAfter
corpothe delay, the
umano. output
Dopo will
il ritar-
do, l'uscita
change from cambierà dal livello
high level into high
low level al livello low automaticamente.
automatically.

Il PIR
PIR può
can onlyessere installato
be installed soloand
indoors, all'interno, e il suo
its false alarm ratetasso
has a di falsirelationship
great allarmi dipende grandemente
with the dalla of
location and mode posizione e
installation.
dallecorrect
The modalità di installazione:
use should meet the following conditions:
1. It should beessere
Dovrebbe 2.0-2.2tra
meters
i 2.0above
e i 2.2the ground.
metri dal suolo;
2. Stay
Stareaway from da
lontano air conditioners, refrigerators,
condizionatori, frigoriferi,stoves
stufeand otherlaplaces
e dove where airdell'aria
temperatura temperature changes
cambi apparently.
apparentemente.
3. No screen,
Nessun furniture, large-scale
paravento, bonsai
mobile, pianta odoraltro
otheroggetto
isolationisolante
objects shall be detected
dovrebbe stare within the detection
nel range range.
di rilevamento.
4. Don't face straightly
Non posizionarlo ditoward
fronte the
unawindow,
finestra,otherwise
altrimentithe disturbance
il distrubo del of the hot
flusso air caldo
d'aria flow outside the window
fuori dalla stessa eand
il the
movement of people
movimento will causecauserà
delle persone false alarm.
falsi allarmi.
5. Do
Nonnot use ininareas
usare areewith
constrong airflow. d'aria.
forti correnti
6. The sensitivity del
La sensibilità of PIR
PIRtoalhuman
corpo body
umanois also closely related
è strettamente to the direction
collegata of movement.
con la direzione It is least sensitive
del movimento. È meno to radial
movement
sensibileand most sensitive
a movimenti to the
radiali movement
e più sensibileinathe crosscutting
movimenti direction.
trasversali.

283
Fritzing Circuit

In this example,
questo we can
esempio connect the
possiamo pins of direttamente
collegare Sound Sensor iModule
pin deltoModulo
the pins PIR
of Mega 2560
ai pin Board
della directly,
Scheda Mega and 2560
we use
e
possiamo
digital pin 2usare il the
to read pin signal
digitale 2 per
of PIR leggere
Module. il segnale
Connect dello
the VCC stesso.
of PIR Connettere
Module latoCCC
to 5V, GND del
GND, Modulo
and OUT toPIR ai 5V,
digital pin
GND alyou
NOTE: GNDcaneremove
OUT althe
pinPIR
digitale. NOTA:
cover to possibile
è pin
see the mark. rimuovere il coperchio per vedere l'etichetta dei pin.

Diagramma Schematico
Schematic Diagram

284
Code
Codice

void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
}

void loop() {
Serial.println(digitalRead(2));
delay(1);
}

After the
Dopo codes
aver are uploaded
caricato i codicitosulla
the Mega2560 board,
scheda Mega you can
2560, open the serial
è possibile apriremonitor to see
il monitor the reading
seriale value ofilthe
per vedere pin.
valore
letto
Whendal pin. Quando
PIR Module detectsilactivity
Modulo PIR the
nearby, rileva attività
serial nelle
monitor will vicinanze,
display「1」 il monitor it
; otherwise, seriale mostrerà「1」
will display「0」 ; altrimenti,
. Check Part 1-1.4
visualizzerà「0」
Digital . Controllare
Read for more la Parte
detail code 1-1.4 Digital Read per una spiegazione dettagliata del codice.
explanation.

Ci sono
There aredue
twopotenziometri
potentiometerssul
onmodulo
the PIR PIR: uno one
module: è per
is regolare
to adjust la sensibilità
sensitivity e l'altro
and perisregolare
the other distanza
to adjustlathe di
detection
distance. In order
rilevamento. Perto make
far the PIR module
funzionare meglio work better,PIR,
il modulo youèneed to try toprovare
necessario adjust these two potentiometers.
a regolare i due potenziometri.

285
Phenomenon
Immagine Picture
Fenomenologica

286
2.32 DHT11 Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai to use
come DHT11
usare Module.
il modulo The DHT11
DHT11. È un is a basic,diultra
sensore low-cost digital
temperatura temperature
ed umidità base and
e a
bassissimo
humidity costo.
sensor. Utilizza
It uses un sensore
a capacitive capacitivo
humidity sensor di
andumidità e un to
a thermistor termistore per surrounding
measure the misurare l'aria circostante,
air, and spits out e
a
butta fuori
digital signalun
onsegnale
the datasul
pindata pin (non
(no analog sono
input pinsnecessari pin di input analogici).
are needed).

Componenti Richiesti
Components Required

ModuloModule
1 * DHT11 DHT11 11**Mega
Mega2560
2560Board
Board

Several Jumper
Diversi JumperWires
Filari

287
Component Introduction
Introduzione del Componente
Sono disponibili solo 3 pin: VCC, GND e DATA. Il processo di comunicazione iniiza con
Only three pins are available: VCC, GND, and DATA. The communication process begins with the
la linea DATA che invia segnali di avvio al DHT11, che riceve i segnali e restituisce un
DATA linedisending
segnale start
risposta. signalsl'host
Quindi to DHT11,
iniziaand DHT11 un
a ricevere receives
dato the
di Usignals
/ T a and returns
40-bit anintero
(8-bit answer
signal. Then
umidità the host
+ 8-bit receives
decimale the answer
umidità signal
+ 8-bit and begins to
temperatura receive
intero 40-bittemperatura
+ 8-bit humiture data (8-bit
humidity integer
decimale + 8-bit+checksum).
8-bit humidity Perdecimal
maggiori+ 8-bit temperature
informazioni, si integer + 8-bit
prega di temperature alla
fare riferimento
scheda
decimal tecnica del DHT11.For more information, please refer to DHT11 datasheet.
+ 8-bit checksum).

Fritzing Circuit

In questo esempio
this example, we possiamo
can directlycollegare
connect direttamente i pin
the pins of DHT11
del modulo
Module to theDHT11 ai pin2560
pins of Mega della scheda
Board, Mega
and we 2560
use pin e
4 to
usiamo
read theilsignal
pin 4 of
per leggere
DHT11 il segnale
Module. del Modulo
Connect DHT11.
the pin 「+ 」of
Collegare il pin「+」del
DHT11 Module Modulo
to 5V, the pin「-」 ai 5V,
to GND, andilthe
pin「-」alla
pin OUT to
GND
pin 4. e il pin OUT al pin 4.

Diagramma di Cablaggio
Wiring Diagram

288
Code
Codice

IThe codes
codici use the
usano library dht.h.
la libreria dht.h.About how to import
Per importarla fare library, pleasealla
riferimento refer to Part
Parte 4 -44.1
- 4.1
AddAdd Libraries.
Libraries.

#include <dht.h>
<dht.h>
dht DHT;

#define DHT11_PIN 4

void setup()
{
Serial.begin(9600);
Serial.println("DHT TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT_LIB_VERSION);
Serial.println();
Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
}

void loop()
{
Serial.print("DHT11, \t");

289
int chk = DHT.read11(DHT11_PIN);
switch (chk)
{
case DHTLIB_OK:
Serial.print("OK,\t");
Serial.print(DHT.humidity,1);
Serial.print(",\t");
Serial.println(DHT.temperature,1);
delay(1000);
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error,\t");
break;
default:
Serial.println("Unknown error,\t");
break;
}
}

290
Dopo aver
After the caricato
codes i codici sulla
are uploaded to thescheda Mega2560,
Mega2560 il monitor
board, the seriale
serial monitor willcontinuerà
continue toad emettere
output i valori
the current correnti
temperature
di
andtemperatura ed umidità
humidity values dell'ambiente.
of the environment.

Analisi del Codice


Code Analysis

Le
Thefunzioni
functiondel modulo
of the sono
module incluseinnella
is included libreria
the library dht.h.
dht.h.

#include <dht.h>

Funzioni della Libreria:


Library Functions:

dht

Crea una
Creates nuova
a new istanza
instance della
of the classe
dht class dhat che rappresenta
that represents il particolare
a particular modulo
DHT-11 module DHT-11
attached collegato
to your allaboard.
Arduino scheda.

int read11(uint8_t pin)

This function
Questa will return
funzione CHECK
restituirà values.
i valori CHECK.

DHTLIB_OK significa
DHTLIB_OK means che
that il DHT-11
DHT-11 in buone
is inègood condizioni;
condition;
DHTLIB_ERROR_CHECKSUM significa che il valore può essere anormale;
DHTLIB_ERROR_CHECKSUM represents that the value may be abnormal;
DHTLIB_ERROR_TIMEOUT indica che c'è un timeout.
DHTLIB_ERROR_TIMEOUT indicates that there is timeout.
La funzione memorizzerà l'umidità e la temperatura nelle variabili con lo stesso nome che nella classe dht. La
The function will store the detected humidity and temperature into the variables with the same name in dht class.
funzione andrebbe richiamata ed utilizzata direttamente nel programma principale. (es. Serial.println(DHT.tem-
The function should be called and used directly in the main program. (e.g. Serial.println(DHT.temperature,1);)
perature,1);)

291
Phenomenon
Immagine Picture
Fenomenologica

292
2.33 Ultrasonic Module

Overview
Panoramica

In this lesson,
questa you will
lezione learn how
imparerai adtoutilizzare
use Ultrasonic module.
un Modulo Ultrasonico.

Components Richiesti
Componenti Required

UltrasonicUltrasonico
1 * Modulo Module 1 * Mega 2560 Board

Several Jumper
Diversi JumperWires
FIlari

293
Component Introduction
Introduzione del Componente

Ultrasonic
Il ranging
modulo di modulea provides
misurazione 2cm
ultrasuoni - 400cm
dà una non-contact
misurazione senzameasurement
contatto da
2cm a 400cm.
function. Il principio
The working di funzionamento
principle chesends
is that when the èMPU quando
outl'MPU
orders,invia ordini,
the ceramic
il chip
chip ceramico
begins iniziaand
to vibrate a vibrare e l'involucro
then aluminum in alluminio
enclosure vibra insieme
vibrates together with it ad
to
esso, ultrasonic
form per formare un'onda
wave ultrasonica,
and emit the wave emessa
towards dal
theretro
back dell'auto.
of the car.Dopo
After che
the
l'onda ultrasonica
emitted colpisce
ultrasonic wave unobstacle,
hits an ostacolo, si genererà
there un'onda
will be echo d'eco.
wave. This Essa
echo sarà
wave is
ricevuta by
received dallo
thestesso
same involucro
aluminum in alluminio
enclosure e the
and dal chip ceramico
ceramic chip in sotto forma
the form of
di vibrazione.
vibration. L'MPU
The MPU valuta
judges the la posizione
position of thedell'ostacolo calcolandothe
obstacle by calculating la time
dif-
ferenza diand
difference tempo e di difference
azimuth azimuth dell'onda
of the echo d'eco.
wave.Questo sensore
Ultrasonic è molto
distance sensorusato
can benel campo
widely useddel monitoraggio
in the del
field of material
livello
level dei level)
(liquid fluidi,monitoring,
dell'anticollisione dei robot,
robot anti-collision, di vari
various interruttori
ultrasonic di prossimità
proximity switches, ande intruder
di allarmi anti-intrusione.
alarm.

Il modulo
The moduleinclude trasmettitori
includes e ricevutori
ultrasonic transmitters, ad ultrasuoni
receiver e un
and control circuito
circuit. The di controllo.
basic I principi
principles di base sono:
are as follows:

(1) Use
un IO
anflip-flop per to
IO flip-flop processare un segnale
process a high di livello
level signal high10us;
of at least per almeno 10μs;

il modulo
(2) The moduleinvia automaticamente
automatically otto
sends eight 40KHz
40khz e rilevaifse
and detects c'è un
there is aritorno del segnale
pulse signal return. di impulso;

(3)sethe
(3)If il segnale ritorna,passing
signal returns, superando il livello
the high high,
level, the la durata
high dell'uscita
output highisdell'IO
IO duration è il from
the time tempo che
the intercorre of
transmission trathe
la
trasmissione
ultrasonic wavedell'onda ultrasonica
to the return e iltest
of it. Here, suo ritorno.
distance = Qui,
(highdistanza = (tempo
time x sound speedHIGH
(340×mVelocità
/ s) / 2.SUONO.) / 2. (VS=340m/s)

TRIG Pulsazione
Trigger Pulse Input GND Ground
TRIG GND Terra
d'innesco input
Pulsazione
ECHO
ECHO Echo Pulse Output VCC
VCC Supply
Alimentazione
d'innesco output

294
The
Il timing diagram
diagramma is shown
temporale below. Yousotto.
è mostrato only need
Bastatofornire
supply un
a short 10us
breve pulse for
impulso di the
10μstrigger input to
dell'input di start the ranging,
innesco per ini-
ziare la misurazione,
and then quindi
the module will sendilout
modulo invierà
an 8 cycle una
burst raffica di ultrasuoni
of ultrasound a 8 raise
at 40 kHz and cicli its
a 40KHz e genererà
echo. You la sua
can calculate theeco. Si
range
può calcolare
through la interval
the time distanza tramitesending
between l'intervallo di signal
trigger tempoand
trareceiving
il segnale d'innesco
echo signal. inviato e il segnale d'eco ricevuto.

Formula: μs
us / 58
58 =
= centimetri or or
centimeters μsus
/ 148 =pollici;
/ 148 =inch; oppure: distanza
or: the range = tempo
= high livello *high
level time × velocità
velocity (340m/s)
(340M/S) / 2; are
/ 2; you si
consiglia
suggesteddi
tousare un ciclo di misura
use measurement superiore
cycle over 60ms inaorder
60 msto per evitare
prevent collisioni
signal traofsegnale
collisions d'innesco
trigger signal e d'eco.
and the echo signal.

10μS TTL
Diagramma Temporale
Timing Diagram

Trigger
Input Input
d'Innesco
al to
Modulo
Module
Raffica8 di
Cycle Sonic Burst
Ultrasuoni di 8 Cicli

Sonic Burst
Raffica from
di Ultrasuoni
dal Modulo
Module

Input TTL lever


segnale signal
di Input
Echo Pulse Output
Pulsazione d'Eco di TTL lever
with conin
a range un
Output al circuito
To User Timing circuit intervallo
portion in
di temporizzazione porzione
dell'utente

295
Fritzing Circuit

In this example,
questo we collegiamo
esempio directly connect the pins iofpin
direttamente Ultrasonic Module
del Modulo with the pins
ad Ultrasuoni con of Mega
i pin 2560
della Board.
Scheda And2560.
Mega then
we get VCC ilofVCC
Collegiamo the del
Ultrasonic
ModuloModule con-
ai 5V, GND
nected to 5V,
alla GND, TrigGND todigitale
al pin GND, Trig to thealdig-
5, Echo pin
ital pin 5,
digitale 4.Echo to the digital pin 4.

Schematic
DiagrammaDiagram
Schematico

296
Code
Codice

const int echoPin = 4;


const int trigPin = 5;
void setup(){
Serial.begin(9600);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
Serial.println("Ultrasonic sensor:");
}

void loop(){
float distance = readSensorData();
Serial.print(distance);
Serial.println(" cm");
delay(400);
}
float readSensorData(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);

297
digitalWrite(trigPin, LOW);
float distance = pulseIn(echoPin, HIGH)/58.00;
return distance;
}

Dopo aver caricato


After uploading i codici
the codes allaMega2560
to the scheda Mega2560,
board, the ilserial
monitor seriale
monitor mostrerà
will display thela distanza
distance dagli ostacoli
of obstacles aheaddithat
fronte
the
che il sensore
ultrasonic adhas
sensor ultrasuoni
detected.ha rilevato.

Analisi del Codice


Code Analysis

Riguardo
About the all'utilizzo
application del sensore sensor,
of ultrasonic ad ultrasuoni, possiamo
we can directly controllare
check direttamente la sottofunzione.
the subfunction.

float readSensorData(){// ...}

PING è innescato
PING is daaun
triggered by impulso
HIGH pulse HIGH
of 2 ordimore
2 o più microsecondi
microseconds. (dare
(Give un breve
a short impulso
LOW pulse LOW in anticipo
beforehand to ensureper
a clean
garantire un impulso HIGH pulito).
HIGH pulse.)

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

Il
Thepinecho
eco pin
è usato per
is used toleggere il segnale
read signal da PING,
from PING, unpulse
a HIGH impulso HIGH
whose la cui isdurata
duration è il(in
the time tempo (in microsecondi)
microseconds) from the
dall'invio
sending ofdal
theping
ping alla ricezione
to the dell'eco
reception of echodell'oggetto.
of the object.

298
microsecond=pulseIn(echoPin, HIGH);

La
Thevelocità
speed ofdel suono
sound è dim/s
is 340 340orm/s o 29 microsecondi
29 microseconds per centimetro.
per centimeter.
Questo dà la distanza percorsa dal ping, alla collisione e ritorno, perciò dividiamo per 2 per ottenere la distanza
This gives the distance travelled by the ping, outbound and return, so we divide by 2 to get the distance of the obstacle.
dall'ostacolo.
float distance = microsecond / 29.00 / 2;

Phenomenon Picture
Immagine Fenomenologica

299
2.34 MPU6050 Module

Overview
Panoramica

this lesson,
In questa you imparerai
lezione will learn ad
howusare
to use MPU6050.È MPU-6050
l'MPU6050. is a di
un dispositivo 6-axis (combineddel
tracciamento 3-axis Gyroscope,
movimento a 63-axis
assi
(giroscopio combinato
Accelerometer) a 3 assi,
motion tracking accelerometro
devices. a for
It is often used 3 augmented
assi). Vienereality
spessoand usato perimage
electronic realtàstabilization
aumentata e
(EIS:
stabilizzazione
Electronic Image elettronica
Stabilization),dell'immagine. (EIS: Electronic
optical image stabilization ImageImage
(OIS: Optical Stabilization), stabilizzazione
Stabilization), "Zero touch" ottica
gesture(OIS:
user
Optical
interface.Image Stabilization), interfacce utente a gesti "zero tocchi".

Componenti
Components Richiesti
Required

1 * MPU6050 1 * Mega 2560 Board

1 * Breadboard

Several Jumper
Diversi JumperWires
Filari

300
Component Introduction
Introduzione del Componente

Its three
Il suo coordinate
sistema systems are èdefined
a 3 coordinate as come
definito follows:segue:

Put MPU6050
mettere flat on piatto
l'MPU6050 the table,
sulassure
tavolo,that the face with
assicurarsi label
che la is upward
faccia con laand a dot
scritta siaon this
verso
l'alto
surfacee isil on
punto sulla
the top leftsuperficie siathe
corner. Then all'angolo in alto aupward
upright direction sinistra. Quindi
is the z-axislaofdirezione
the chip.
verticale, verso
The direction froml'alto, l'asse
left toè right z del chip
is regarded . LaX-axis.
as the direzione da sinistra
Accordingly a destra
the direction è
from
considerata
back to front iscome
definedasse
as theX.Y-axis.
Di conseguenza la direzione da sotto a sopra è definita come l'asse y.

Acceleration
Accelerazione

L'accelerometro
The accelerometerfunziona
works onsul
theprincipio dell'effetto
principle of piezo-elettrico,
piezo electric la capacità
effect, the ability of certaindi acluni materiali
materials di an
to generate generare
electric
una carica elettrica
charge in risposta
in response allo stress
to applied meccanico
mechanical stress.applicato.

Si immagini
Here, imagineuna scatolabox,
a cuboidal cubica, con
having una ball
a small piccola palla
inside all'interno,
it, like come
in the picture nell'immagine
above. The walls of sopra.
this boxLe
arepareti sono
made with
realizzate
piezo con
electric cristalli
crystals. piezoelettrici.
Whenever you tiltOgni volta
the box, thesiball
inclina, la palla
is forced è costretta
to move a muoversi
in the direction nella direzione
of the inclination, due todella
inclinazione,
gravity. per
The wall gravità.
with whichIlthe
muro
ball con cui la
collides, pallatiny
creates si scontra crea minuscole
piezo electric correnti
currents. There piezoelettriche.
are totally, Ci opposite
three pairs of sono tre

301
walls in aopposte
coppie cuboid. Each pairnel
di muri corresponds to coppia
cubo. Ogni an axis in 3D space: X,ad
corrisponde Y and
un Z axes.
asse Depending
nello on the
spazio 3D: current
X, Y e Z. Aproduced
seconda from
della
corrente
the piezo prodotta dalle
electric walls, wepareti, possiamo
can determine thedeterminare la direzione
direction of inclination anddell'inclinazione
its magnitude. ed il suo valore.

Possiamo
We can useusare l'MPU6050
the MPU6050 per rilevare
to detect l'accelerazione
its acceleration su ogni asse
on each coordinate axis (nella
(in thesituazione statica della
stationary desktop scrivania,
state, the Z-axis
l'accelerazione
acceleration is 1Zgravity
è 1 unità,
unit, mentre
and thelaXXand
e laYYaxes
sono 0).0).SeIfinclinato
are it is tiltedo or
in in
una condizione di assenza/aumento
a weightless/overweight di
condition, the
peso, la letturareading
corresponding corrispondente
will change.cambierà.

Ci sono
There arequattro tipi
four kinds of di intervalliranges
measuring di misura chebesiselected
that can possono scegliere nella+/-2g,
programmatically: programmazione: ±2g,+/-16g
+/-4g, +/-8g, and ±8g e
±4g, (+/-2g
±16g (±2g
by default) predefinito),
corresponding corrispondenti
to each a ciascuna
precision. Values precisione.
range from L'intervallo di valori sarà -32768~32767.
-32768 to 32767.

La
Thelettura
readingdell'accelerometro
of accelerometer is viene convertita
converted in un valore
to an acceleration di accelerazione
value mappando
by mapping the i valori
reading from dall'intervallo
the reading range todi
the
lettura all'intevallo
measuring range. di misura.

Accelerazione = (dato grezzoaxis


Acceleration = (Accelerometer asse Accelerometro
raw data / 65536 */full
65536 * intervallo
scale scala
Acceleration di Accelerazione)
range) g g

Si prenda
Take l'asse
the X-axis asXancome esempio:
example, quando il datoX grezzo
when Accelerometer axis rawsull'asse X è 16384
data is 16384 e range
and the il range selezionato
is selected è ±2g:
as +/-2g:

Accelerazione lungo
Acceleration along thel'asse
X axisX==(16384
(16384//65536
65536 **4)
4)g=1g
g=1g

Giroscopi
Gyroscopes
IGyroscopes
giroscopi work
funzionano con il principio
on the principle of Coriolisdiacceleration.
Coriolis. Si Imagine
immagini
thatuna struttura
there is a forksimile ad unathat
like structure, forcella, in costante
is in constant back
movimento avantiIt eisindietro,
and forth motion. tenuta
held in place in posizione
using usando
piezo electric cristalli
crystals. piezoelettrici.
Whenever, you try to Setilt
si this
tenta di inclinare the
arrangement, questa di-
crystals
sposizione,
experience ai force
cristalli rilevano
in the unaofforza
direction nella direzione
inclination. di inclinazione.
This is caused as a result ofCiò causato
theèinertia dall'inerzia
of the dellaThe
moving fork. forcella in
crystals
movimento.
thus produce Iacristalli
current increano una corrente
consensus secondo
with the piezo l'effetto
electric effect,piezoelettrico
and this currenteistale corrente viene amplificata.
amplified.

302
Anche i giroscopi
The Gyroscope alsohanno 4 range
has four kindsdiofmisura: ± 250,
measuring ± 500,+/-
ranges: ± 1000, ± 2000
250, +/- 500,(±250°/s predefinito)
+/- 1000, . Il metodo di by
+/- 2000 (+/-250degree/s
calcolo .eThe
default) l'accelerazione sono fondamentalmente
calculation method coerenti.consistent.
and Acceleration are basically

La formula
The formulaper convertirethe
for converting la lettura
readingininto
velocità angolare
angular velocity is la follows:
è as seguente:

Velocitàvelocity
Angular angolare = (dato rawaxis
= (Gyroscope dell'asse del
raw data Giroscopio
/ 65536 * full/scale
65536 * intervallo
Gyroscope scala
range) °/s Giroscopio) °/s

Si prenda
The l'asse
X axis, for X come
example, theesempio: il datoXraw
Accelerometer axis dell'asse del
raw data is Giroscopio
16384 è 16384
and ranges + / - e250
l'intervallo
° / s: è ± 250 °/s:

Velocità angolare
Angular velocity lungo
along thel'asse
X axisX==(16384
(16384//65536
65536 **500)°/s
500)°/s=125°/s
=125°/s

303
Fritzing Circuit

In this example,
questo we drive
esempio MPU6050l'MPU6050
governiamo with IIC. Wecon
inset MPU6050
l'IIC. intol'MPU6050
Inseriamo the breadboard;
nellaget the VCC connected
breadboard; to 5V,
collegiamo GND
il VCC
ai
to 5V,
GND,GND
SCL alla GND,
to pin SCL SCL al pin
21, and SDASCL 21 pin
to the e l'SDA
SDA al
20.pin SDA 20.

Diagramma Schematico
Schematic Diagram

304
Code
Codice

#define ACCELE_RANGE 4
#define GYROSC_RANGE 500

#include<Wire.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
float AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
void setup() {
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)

305
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print(" AcX = "); Serial.print(AcX / 65536 * ACCELE_RANGE); Serial.print("g ");
Serial.print(" | AcY = "); Serial.print(AcY / 65536 * ACCELE_RANGE); Serial.print("g ");
Serial.print(" | AcZ = "); Serial.print(AcZ/65536 * ACCELE_RANGE); Serial.println("g ");
Serial.print(" GyX = "); Serial.print(GyX / 65536 * GYROSC_RANGE); Serial.print("d/s ");
Serial.print(" | GyY = "); Serial.print(GyY/65536 * GYROSC_RANGE); Serial.print("d/s ");
Serial.print("|GyZ= "); Serial.print(GyZ/65536*GYROSC_RANGE); Serial.println("d/s \n");
delay(500);
}

After uploading
Dopo the codes
aver caricato to sulla
i codici the Mega2560 board, youècan
scheda Mega2560, open the
possibile serial
aprire il monitor
monitorto see the
seriale gravity l'accelerazione
e vedere acceleration and
gravitazionale
angular velocityeoflaMPU6050
velocità in
angolare dell'MPU6050 in ogni direzione.
each direction.

Analisi del Codice


Code Analysis

Nella
In the situazione stazionaria
stationary desktop state,della scrivania,
the Z-axis l'accelerazione
acceleration lungo
is 1 gravity l'asse
unit, and theZ Xè and
1 unità, e are
Y axes la X0.e la Y sono 0.

Prima
Before dell'uso,
your use, è necessario
you calibrare
need to calibrate theil module,
modulo;the
il metodo il seguente:
methodsèare as follows:

306
①MPU6050
① il modulomodules are placed horizontally
viene posizionato on the desktop
orizzontalmente and then
sulla scrivania you can
e viene fix them
fissato conwith clampsoor
morsetti adhesive
nastro tape.
adesivo.

Run the sample


② eseguire codes
il codice to get theper
di esempio RAW DATA ofilMPU6050
ottenere RAW DATAwhen it is static.
dell'MPU6050 quando è statico.

③ Aggiungere la compensazione
Add compensation in base
according to the allewhen
readings letture quandoisl'MPU6050
MPU6050 static. è statico.

Prendendo l'MPU6050
Take MPU6050 we use asche abbiamoand
an example, usato nell'esempio,
the results i risultatiare
of compensation della compensazione sono i seguenti:
as follows:

Serial.print(AcX / 65536 * ACCELE_RANGE - 0.02);


Serial.print(AcY / 65536 * ACCELE_RANGE + 0);
Serial.print(AcZ/65536 * ACCELE_RANGE + 0.02);
Serial.print(GyX / 65536 * GYROSC_RANGE + 1.70);
Serial.print(GyY/65536 * GYROSC_RANGE - 1.70);
Serial.print(GyZ/65536*GYROSC_RANGE + 0.25);

Before the calibration After the calibration

307
Phenomenon
Immagine Picture
Fenomenologica

308
2.35 RFID-RC522 Module

Overview
Panoramica
In this
questa lezione
lesson, imparerai
you will learn howad to
usare un Modulo
use RFID Module. RFID. l'abbreviazione
È the
RFID is abbreviation ofdi Radio
RadioFrequency
Frequency Identification
Identification. Its
(Identificazione
working principleaisRadio
to carryFrequenza). Il suo principio
on the contactless di funzionamento
data communication betweenètheavere comunicazione
reader senza
and the label to contatto
achieve the goaldi
dati tra un lettore
of identifying e un'etichetta
the target. allo scopo
The application di identificare
of RFID l'obbiettivo.
is very extensive, currentlyL'applicazione dell'RFIDare
the typical applications è molto
animalampia,
chips,
attualmente le applicazioni tipiche sono chip per animali, immobilizer, controllo degli accessi, controllo
immobilizer, access control, parking control, production chain automation, material management and so on.
parcheggio, automazione della catena di produzione, gestione dei materiali e così via.
Components Richiesti
Componenti Required

1 * Card 1 * Mega 2560 Board


Key
1 * Chiave
1 * RFID

Several Jumper
Diversi JumperWires
Filari

309
Component Introduction
Introduzione del componente
Radio Frequency Identification
L'identificazione (RFID) (RFID)
a radiofrequenza refers tositechnologies that involveche
riferisce a tecnologie using wireless communication
comportano between
l'utilizzo della an object
comunicazione
wireless
(or tra an
tag) and uninterrogating
oggetto (o device
tag) e(or
unreader)
dispositivo di interrogazione
to automatically track and (o lettore)
identify suchper tracciare
objects. ed transmission
The tag identificare
automaticamente
range tali oggetti.
is limited to several metersLo spazio
from di trasmissione
the reader. del
A clear line oftag limitato the
è between
sight ad alcuni
reader metri dalis lettore.
and tag Non è
not necessarily
necessaria una chiara linea di visione tra il lettore e il tag.
required.

La maggior
Most parteatdei
tags contain tag
least contiene
one almeno
integrated circuit un
(IC) circuito integrato
and an antenna. (IC)
The e un'antenna.
microchip Il microchip
stores information andmemorizza le
is responsible
informazioni
for ed radio
managing the è responsabile della
frequency (RF) gestione della
communication comunicazione
with a radiofrequenza
the reader. Passive (RF)
tags do not have an con il lettore.energy
independent I tag
passiviand
source nondepend
hannoon
una
an fonte di electromagnetic
external energia indipendente e dipendono
signal, provided da un to
by the reader, segnale
power elettromagnetico esterno,
their operations. Active tags
fornito dal
contain lettore, per alimentare
an independent le loro
energy source, suchoperazioni. I tag
as a battery. attivi
Thus, theyinvece ne contengono
may have una, ad esempio
increased processing, una
transmission
batteria. Quindi
capabilities potrebbero aumentare le capacità di processazione, trasmissione e distanza di comunicazione.
and range.

MFRC522
L'MF
MF RC522
RC522 un chip
is aèhighly altamente
integrated integrato
read and di chip
write card lettura e scrittura
applied per schedem
to the 13.56MHz applicato
contactless alla comunicazione
communication. Launched
contactless
by a 13,56MHz.
the NXP Company, it is Lanciato dalla low-cost,
a low-voltage, società NXP, è un chip per
and small-sized schede senza
non-contact contatto
card chip, a bestachoice
bassa of
tensione, a
intelligent
bassso costo
instrument andeportable
di piccole dimensioni,
hand la scelta migliore di strumento intelligente e dipositivo portatile.
held device.

L' MF
The MFRC522
RC522usa un advanced
uses concetto modulation
avanzato diand
modulazione e demodulazione
demodulation definitivamente
concept which fully presented in presente in 13.56MHz
all types of tutti i tipi
passive contactless
di metodi communication
e protocolli methodspassiva
di comunicazione and protocols. In addition,
senza contatto a it supports rapid
13.56MHz. CRYPTO1supporta
In aggiunta, encryption algorithm
l'algoritmo
to
di verify MIFARErapida
crittografia products.
CRYPTO1 per verificare i prodotti MIFARE.

310
MFRC522 also
L'MFRC522 supports anche
supporta MIFARElaseries
serieofMIFARE
high-speed
pernon-contact communication,
la comunicazione ad altawith a two-way
velocità senzadata transmission
contatto, rate
con una
velocità di trasmissione
up to 424kbit/s. dati bidirezionale
As a new member finohighly
of the 13.56MHz a 424Kbit/s.
integratedCome
reader nuovo membro
card series, delle
MF RC522 serie similar
is much di lettori a
to the
13.56MHz, l'MFRC522
existing MF RC500 è molto
and MF RC530simile al già
but there alsoesistente MFdifferences.
exists great RC500 e MF RC530, ma ha anche grandi differenze.

Comunica con lawith


It communicates macchina
the hosthost tramite
machine il metodo
via the serialewhich
serial manner che richiede meno
needs less cablaggi.
wiring. possibile
You canÈchoose scegliere
between tra
SPI, I2C
le
andmodalità SPI,mode
serial UART I2C e (similar
UART (simile a RS232),
to RS232), which che
helpsaiuta a ridurre
reduce le connessioni,
the connection, salvare
save PCB boardspazio
space sulla scheda
(smaller size), PCB
and
(dimensioni
reduce cost. inferiori) e ridurre i costi.

Fritzing Circuit
In thisquesto
example, esempio inseriamo
we insert the l'RFID
RFID into the nella
breadboard.
breadboard.
Get the 3.3V ofCollegiamo i 3.3V
RFID connected dell'RFID
to 3.3V, ai 3.3V,
GND to GND, RST
GND
to pinalla GND,
2, SDA RST6,alSCK
to pin pinto2,pin
SDA al pinto
5, MOSI 6,pin
SCK4, al pin
MISO
5,
to MOSI al pin
pin 3 and IRQ4,toMISO
pin 7. al pin 3 e IRQ al pin 7.

Diagramma
Schematic Schematico
Diagram

311
Code
Codice
IThe codes
codici use the
usano rfid1.h library.
la libreria rfid1.h.About how to import
Per importarla, ci sithe library,alla
riferisca please refer
Parte 4 -to4.1
Part 4 - 4.1 AddLibrerie.
Aggiungere Libraries.

#include"rfid1.h"
RFID1 rfid; //create a variable type of RFID1
uchar serNum[5]; // array to store your ID

void setup()
{
Serial.begin(9600); //initialize the serial
rfid.begin(7, 5, 4, 3, 6, 2); //rfid.begin(IRQ_PIN,SCK_PIN,MOSI_PIN,MISO_PIN,SDA_PIN,RST_PIN)
delay(100);//delay 1 second
rfid.init(); //initialize the RFID
}
void loop()
{
uchar status;
uchar str[MAX_LEN]; //The maximum length of the array is 16

// Search card, return card types


status = rfid.request(PICC_REQIDL, str);
if (status != MI_OK)

312
{
return;
}
Serial.print("Card type: ");
Serial.println(rfid.readCardType(str));
//Prevent conflict, return the 4 bytes Serial number of the card
status = rfid.anticoll(str);
if (status == MI_OK)
{
Serial.print("The card's number is: ");
int IDlen=4;
for(int i=0; i<IDlen; i++){
Serial.print(str[i],HEX);
}
Serial.println();
Serial.println();
}

delay(500);
rfid.halt(); //command the card into sleep mode
}

313
Uploaded
Caricati the codes
i codici nellatoscheda
the Mega2560 board,
Mega2560, you canporre
è possibile get your RFIDRFID
la carta card (chiave
(secret key) closevicino
segreta) to thealRFID Reader.
lettore RFID.The
Il
modulo leggerà
module will le informazioni
read the della
card information andscheda e quindi
then print le stamperà
it on the sul monitor seriale.
serial monitor.

Analisi del Codice


Code Analysis
Le
Thefunzioni
functionsdel
of modulo sono
the module areincluse nella
included libreria
in the libraryrfid1.h.
rfid1.h.

#include <rfid1.h>

Funzioni della Libreria:


Library Functions:

RFID1

Crea una
Create nuova
a new istanza
instance della
of the classe
rfid1 class rfid1 che rappresenta
that represents il particolare
a particular RFID moduleModulo RFID
attached collegato
to your alla. scheda.
Arduino

void begin(IRQ_PIN,SCK_PIN,MOSI_PIN,MISO_PIN,SDA_PIN,RST_PIN)

Configurazione
Pin configuration.dei pin.

i pin
IRQ_PIN,SCK_PIN,MOSI_PIN,MISO_PIN: the usati
pins per
used forlathe
comunicazione SPI.
SPI communication.

SDA_PIN: Synchronous
adattatore sincrono dei dati.
data adapter.

RST_PIN: The
i pinpins
utilizzati per
used for il reset.
reset.

void init()

Inizializza
Initialize thel'RFID.
RFID.

314
uchar request(uchar reqMode, uchar *TagType);

Cerca
Searchla scheda
card e necard
and read legge il tipo,
type, e ridarà
and the lo will
function stato di lettura
return corrente
the current readdell'RFID, dando
status of RFID andMI_OK se riuscito.
return MI_OK if successed.

reqMode:Search
reqMode: metodi di ricerca.
methods. PICC_REQIDL
PICC_REQIDL è definito
is defined come
that 0x26 0x26 bitbits
command di comando
(Search the(cerca
cards le schede
that cheinnon
does not the sono
sleep
in modalità
mode sleep nell'area
in the antenna area). dell'antenna).

*TagType: It
è is usedper
usato to store card type, iland
memorizzare itsdi
tipo value canebe
carta, 4byte
il suo (e.g. 0x0400).
valore può essere di 4byte (es. 0x0400).

char * readCardType(uchar *TagType)

This function
Questa decodes
funzione the four-digit
decodifica hexadecimal
il numero number
esadecimale di of *tagType
quattro into
cifre the specific
*tagType nello card type and
specifico returns
tipo a string.
di carta e If
restituisce una"MFOne-S50"
passed 0x0400, stringa. Se passato verrà restituito 0x0400 "MFOne-S50".
will be returned.

uchar anticoll(uchar *serNum);

Previene conflitti
Prevent conflict, e read
and legge il numero
the card serialdinumber.
serie della
The schda.
functionLawill
funzione restituirà
return the lo statostatus
current reading di lettura corrente
of RFID. di
It returns
RFID.
MI_OKRestituisce
if successed.MI_OK se ha successo.

*serNum: It usato
è is usedper memorizzare
to store il numero
the card serial diand
number, serie dellathe
return scheda e card
4 bytes restituisce il numero
serial number. Thedi
5thserie
bytedella
is recheck
scheda
byte(e.g.ae.g.
4 byte. Il 5° bytecard
my magnetic è un
IDbyte di ricontrollo (ad esempio, l'ID della mia carta è 5AE4C955).
is 5AE4C955).

315
Immagine
Phenomenon
Fenomenologica
Picture

316
Part 3:3:Example
Parte Esempi
3.1 Aiuto alla retromarcia
3.1 Reversing Aid

Overview
Panoramica
With lo
Con thesviluppo
development of science
della scienza and technology,
e della a lot
teconologia, of high-tech
molti prodotti products have been sono
ad alta tecnologia installed in cars,nelle
installati among which
auto, tra
cui
the ilreversing
sistema assist
di assistenza
system isalla
oneretromarcia. Qui we
of them. Here utilizziamo il sensore
use ultrasonic ad ultrasuoni,
sensors, un LCD,
LCD, LED and untoLED
buzzer (manca
make qui
a simple
sotto, ndt)reversing
ultrasonic un cicalino
assistper realizzare un semplice sistema di assistenza alla retromarcia ad ultrasuoni.
system.

Componenti
Components Richiesti
Required
1 * Modulo adModule
Ultrasonic Ultrasuoni 11**Active
BuzzerBuzzer
Attivo 11* *I2C
I2CLCD1602
LCD1602

Several Jumper
Diversi JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

317
Fritzing Circuit
In this example,
questo the wiring
esempio is shown
il cablaggio è ilbelow.
seguente.

318
Schematic Diagram
Diagramma Schematico

319
Example Explanation
Spiegazione dell'Esempio
this project,
In questo we need
progetto to avoid
dobbiamo the
evita- START

re il più possibile
interference betweenl'interferenza tra lo
the LCD screen
schermo
and the LCD
alarme il sistema
system as dimuch
allarme
as Initial
intervallo iniziale
LCD
LCD = intervallo
Interval = Is
(ad esempio,
possible il tempo
(for example, thediLED
sfarfallio
flicker AlertAllerta = - 1= - 1
Interval
del
timeLED è troppo
is too lungo
long and e l'aggiorna-
the LCD refresh is
mento
delayed),dell'LCD è ritardato),
so please quindi
avoid using the Ultrasuoni
Ultrasonic
evita
delay()distatement
usare l'istruzione delay()
and use two ed
separate Rileva distanza
Get Distance

utilizza
intervals due
to intervalli separati
control the per
working
controllare
frequency of therispettivamente
LCD and alarm la fre-
system Valuta distanza
Judging Distance
quenza di lavoro
respectively. del sistema
Its workflow is shownLCD e
in the
dell'allarme.
flow chart. ForIl flusso di lavoro
analysis è mo-
of Interval <25cm 25~50cm >50cm
strato nel
function, diagramma.
refer Per
to Part 1-1.11 l'analissi
Interval.
della funzione Interval, fare riferi- Alert
Interv.Interval
Allerta ==0.3s
0.3s Alert
Interv.Interval
Allerta ==0.8s
0.8s Alert
Interv.Interval
Allerta

mento alla Parte 1-1.11 Interval.

Alert
Interv.Interval
Allerta !=!=-1-1
Refresh l'LCD
Aggiorna LCD
Every Interval
ad Ogni Intervallo
(Show
(Mostrac istance)
istanza) Alert Worklavora
Every
L'Allerta
ad ogni intervallo
Interval
(LED &+ Buzzer)
(LED cicalino)

320
Phenomenon
Immagine Picture
Fenomenologica

321
3.2 Pulsante di Attraversamento
3.2 Pedestrian Pedonale
Crossing Button

Overview
Panoramica
When pedestrians
Quando i pedoni cross the attraversare
devono street, they just
la need to devono
strada, touch thesolo
button on the
toccare lamppost sul
il pulsante of the roadside
palo signal lamp,
del semaforo and
e il verde
per green
the il traffico
lightdiventerà
above the rosso, quindi
traffic lane williturn
pedoni
into potranno attraversare
red then pedestrians caninpass
sicurezza. Pertanto,
safely. Thus, la difficile
the hard situationsituazione
of citizens
dei cittadini
crossing che attraversano
the street la strada
is comprehensively è completamente
resolved. risolta.
At the same time, whenAllo
therestesso tempo, quando
is no pedestrian to press,non
the c'è
lightnessun
above
pedone
the a premere,
lane that is set forilvehicles
semaforo perwill
to pass la corsia
always per il passaggio
be green, dei veicoli
thus greatly rimarrà
improving sempre
the use verde,
efficiency migliorando
of the così
road and traffic
notevolmente l'efficienza di utilizzo della strada e la capacità di traffico.
capacity.

Componenti Richiesti
Components Required
1 * 74hc595 2 * led 1 * 7-Segment
Display 7-Seg. 11**Touch
Touch 10**220Ω
10 resistore 220Ω
resistor

Diversi Jumper
Several JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

322
Fritzing Circuit
In this example,
questo 74hc595,
esempio 7-Segment,
il 74hc595, LED, touch
il Display sensor
7-Seg, il LEDare tosensore
e il be connected
touchaccording to the
si collegano chart.
come in tabella.

Mega 2560 Board 74hc595 7-Segment Mega 2560 Board Led Touch
Q1 b GND Short pin GND
Q2 c 5V VCC
Q3 d 5 Long pin(red)
Q4 e 6 Long pin(green)
Q5 f 2 IO
Q6 g
Q7 dp
GND GND
5V MR
8 SHcp
12 STcp
GND CE
11 DS
Q0 a
5V VCC

323
324
Schematic Diagram
Diagramma Schematico

325
Example Explanation
Spiegazione dell'Esempio
Il
Theflusso di lavoro
workflow of thedel progetto
project è mostrato
is as shown nel diagramma.
in the flow La funzione
chart. The function del
of number
START
numeroofmostrato
display 7-Segmentsul 7-Seg. by
is realized è realizzata
writing 8 bitscrivendo unn datoWhen
data into 74HC595. a 8 there
bit nel
is
74HC595.
a Quando「0」
need of displaying bisogna mostrare「0」,
, the pins abcdef of the isegment
pin abcdef delwill
display 7-Seg. saranno
be connected
Initialize
Inizializza LED verde
acceso (al pedone:
Green LED bright connessi
to adlevel.
the high un livello high.
The pins, I pin
g and dpgneed
e dptodevono essereto
be connected connessi
low levelato
livelllo
write
"Non puoi passare!")
(Passer Shall N o t Pass)
basso 」(B00111111)
「0x3f per scrivere in
i codici「0x3f」(B00111111). I codici
the codes. The complete codes completi
for number displayper
of
mostrare i numeri
7-Segment sul display 7-Segmenti sono i seguenti.
are as follows.

IlIsSensore Touch
Touch Switch
è stato toccato?
Touched?
Common Cathode
Numbers
(DP)GFEDCBA Hex Code
Il LED
Green LEDverde
blink 0 00111111 0x3f
lampeggia per 5 s
5 Seconds
7-Seg. mostra
7-Segment showsil 1 00000110 0x06
conto
coualla rovescia
ntdown
2 01011011 0x5b

LED verdeLED
Green spento
off
3 01001111 0x4f
Red rosso
LED LED bright
acceso 4 01100110 0x66
10per
Seconds
10 s
(Passer Can pass)
("Puoi passare...") 5 01101101 0x6d
7-Segment shows
7-Seg. mostra il
countdown
countdown 6 01111101 0x7d
7 00000111 0x07
LEDRed LEDspento
Rosso off
8 01111111 0x7f
Green LEDacceso
LED verde bright
7-Segment off
7-Seg. spento 9 01101111 0x6f

326
Phenomenon
Immagine Picture
Fenomenologica

327
3.3 Monitor di Surriscaldamento
3.3 Overheat Monitor

Overview
Panoramica
Potresti volertocreare
You may want make andioverheat
monitoraggio
monitoringdeldevice
surriscaldamento che si situations.
that applies to various applica aWhenvarie
thesituazioni.
temperature Quando
of room lais
temperatura
above 30°C indella stanza
summer, the è superiore
electric fan orathe
30 air
°C conditioner
in estate, un
willventilatore
be turned onelettrico o un condizionatore
automatically. If the refrigeratorverranno
stops to
attivati
refrigerate, there will emit alarm. When the CPU gets overheated, the water-cooling system turns on. Next, we diventa
automaticamente. Se il raffrescatore si ferma, emetterà un allarme. Quando la CPU will use
surriscaldata, il sistema di raffreddamento ad acqua si accende. Di seguito useremo un termistore, un relè, un
thermistor, relay, button, rotary encoder and LCD to make an intelligent temperature monitoring device whose threshold
pulsante, un encoder rotativo e un LCD per realizzare un dispositivo di monitoraggio della temperatura
is adjustable. You can make it suitable for the scene you want by inserting different peripherals into the relay and using a
intelligente la cui soglia sia regolabile. È possibile renderlo adatto alla situazione desiderata inserendo diverse
rotary encoder to adjust the high temperature threshold.
periferiche nel relè ed utilizzando un encoder rotativo per regolare la soglia di temperatura alta.

Components Required
1 **Encoder Rotativo
Rotary Encoder 11 ** button
pulsante 1 * Relay
Modulo Relè
Module 1 * ermistore
thermistor 1 * LED
led

328
1 * resistore 220 Ω
220Ω resistor 1 * LCD1602

2 * 10KΩ resistor
resistore10 KΩ

Diversi JumperWires
Several Jumper Filari

1 * Mega 2560 Board 1 * Breadboard

329
Fritzing Circuit
In this example,
questo the component
esempio modules aresono
i moduli componenti connected as shown
connessi comeinmostrato
the table.in tabella.

Mega 2560 Board LCD1602 Rotary Encoder Relay Module LED thermistor button

GND GND GND (-) (-) (-) (-)

5V VCC VCC (+)

SDA SDA

SCL SCL

7 CLK

6 DT

5 SW

2 S

13 (+)

A0 (+)

10 (+)

330
331
Schematic Diagram
Diagramma Schematico

332
Example Explanation
Spiegazione dell'Esempio
The
Il flow diagram
diagramma of the project
di flusso is as follows:
dell'esempio è il seguente:

START

Inizializza

Il pulsante è premuto?

Imposta la T di Rileva e mostra la T


soglia corrente

L'encoder è
ruotato? Tsoglia

Cambia la T di soglia in base al Accende il LED Spegne il LED


valore dell'encoder rotativo chiude il relè apre il relè

L'encoder è
premuto ?

333
By using la
Usando EEPROM.h library, the la
libreria EEPROM.h, high temperaturedithreshold
temperatura soglia è is saved in
salvata in EEPROM per
to avoid the value
impedire resetdel
il reset after the restart
valore dopo
il restart
of MCU. dell'MCU.

Funzioni
Library della Libreria:
Functions:

void write(address,value)

Scriveaun
Write byte
byte sull'EEPROM.
to the EEPROM.

void Read(address)

Leggeaun
Reads byte
byte dall'EEPROM.
from the EEPROM.Posizioni
Locationsche
thatnon sono
have mai
never state
been scritte
written hanno
to have theil value
valoreofdi 255.
255.

void update(address,value)

Scriveaun
Write byte
byte sull'EEPROM.
to the Il valore
EEPROM. The scritto only
value isè written soloifse differisce
differs da quello
from the salvato
one already a quell'indirizzo.
saved at the same address.

void put(address,value)

Write any
Scrive data type
qualsiasi ordi
tipo object
datoto
odthe EEPROM.
oggetto sull' EEPROM.

void get(address)

Legge qualsiasi
Read any tipo
data type or di datofrom
object od oggetto sull'EEPROM.
the EEPROM.

334
Phenomenon
Immagine Picture
Fenomenologica

335
3.43.4
Indovina il Numero
Guess Number

Overview
Panoramica
Indovina il Numerois èa un
Guessing Numbers fundivertente
party gameparty
wheregame
you and dove tu e
your i tuoitake
friends amici a turno
turns inserite
inputting un numero
a number (0~99).(0~99). L'inter-
The range will
vallo
be diverrà
smaller piùthe
with piccolo mano
inputting a mano
of the chetillsi ainserisce
number un numero,
player answers finché
the riddle un giocatore
correctly. Then therisponde
player isall'indovinello
defeated and
correttamente. Quindi il giocatore viene sconfitto e punito (cosa?). Per esempio, se il numero fortunato
punished. For example, if the lucky number is 51 which the players cannot see, and the player ① inputs 50, the prompt è 51,
of
che i giocatori non possono vedere, e il giocatore ① inserisce 50, cambia a 50~99; se il giocatore ② inserisce 70,
number range changes to 50~99; if the player ② inputs 70, the range of number can be 50~70; if the player ③ inputs 51,
l'intervallo dei numeri diventa 50~70; se il giocatore ③ inserisce 51, lui o lei è lo sfortunato. In questo caso
he or she is the unlucky one. Here, we use IR Remote Controller to input numbers and use LCD to output outcomes.
usiamo un Telecomando IR per inserire i numeri e un LCD per l'emissione dei risultati.

Components Required
1 * LCD1602 1 * IR Remote Controller
Telecomando IR Several
DiversiJumper
JumperWires
Filari

1 * Mega 2560 Board 1 * Breadboard

336
Fritzing Circuit
In this example,
questo the wiring
esempio of LCD1602
il cablaggio and infrared
dell'LCD1602 receiving
e del modulomodule is as follows.
di ricezione a infrarossi è mostrato di seguito.

337
Schematic Diagram

338
Example Explanation
Spiegazione dell'Esempio

START Inizializza

Genera il numero fortunato


Resetta l'intervallo di inserimento

Ricevitore IR
ha un valore
POWER
0~9
CYCLE
LCD mostra
l'input corrente.

Inserite due
cifre?

Valuta valore input.


Aggiorna range.

Input
F
corretto?

LCD mostra il
LCD mostra valore
il range corretto

339
Per rendere
In order il gioco
to make di indovinare
the number i numeri
guessing vivido evivid
game become divertente, dobbiamo
and funny, ottenere
we need to achieve le
theseguenti
followingfunzioni.
functions:

1 IlThe
numero fortunato
lucky number willverrà visualizzato
be displayed whenquando
we startavviamo
and resetethe
rispristiniamo il gioco
game, and the e ilrange
number prompt dell'intervallo
prompt is reset to 0di~
numeri
99. viene impostato su 0~99.

2 LCD will
mostrerà
displayilthe
numero inserito
number e il range
being input di number
and the input. range prompt.

3 Dopo due digitazioni,


After inputting lathere
two digits, valutazione
appearsdel numero
result appare
judgment automaticamente.
automatically.

4 Se inserisci
If you inputun solo numero,
a single digit, youpuoi
can premere
press the ilCYCLE
pulsante
key CICLO
(the key(ilatpulsante al centro
the center del Telecomando)
of the Controller) perresult
to start the
iniziare
judgment.la valutazione del numero.

5 Se la risposta
If the answer isnon
not viene indovinata,
guessed, il nuovo
the new number intervallo
range prompt diwill
numeri verrà visualizzato
be displayed (if the lucky (se il numero
number fortunato
is 51 and è
you enter
51
50, ethe
si number
inseriscerange
50, l'intervallo
prompt willdi inserimento
change cambierà a 50~99).
to 50~99).

6 Il
Thegioco
gamesi is
resetta automaticamente
automatically dopo
reset after the luckyche il numero
number è indovinato,
is guessed, così
so that the il giocatore
player can play apuò
newricominciare.
round.

7 IlThe
gioco può
game essere
can resettato
be reset direttamente
by directly premento
pressing the il pulsante
POWER button POWER
(the button (il pulsante
in the upper leftnell'angolo
corner). in alto a sx).

In conclusion,
conclusione,theilwork
flusso di of
flow lavoro è mostrato
the project nelindiagramma.
is shown the flow chart.

340
Phenomenon
Immagine Picture
Fenomenologica

341
3.5 Sistema di Controllo
3.5 Access degli Accessi
Control System

Overview
Panoramica
The
Il access di
sistema control system
controllo is theaccessi
degli systemviene
that isusato
used to
percontrol the entrance
controllare la via channel, which
di ingresso edisèdeveloped on the
creato sulla basis
base of
della
serratura
the della
traditional porta
door lock.tradizionale. Quest'ultima
The traditional è solo
mechanical door lockun semplice
is only dispositivo
a simple meccanico,
mechanical device, andeno
non importa
matter how
quanto siathe
reasonable buono il design
structural strutturale
design o quanto
is, how strong sia forte
the material il materiale,
is, people le persone
can always possono
open it through sempre
various aprirlo
means. Thecon
key
vari mezzi.
to the La chiave
entrance and exitper
(likel'ingresso e l'uscitaa (come
an office building, un edificio
hotel room) per uffici,
is cumbersome. unakey
If the camera d'albergo)
is missed è ingombrante.
or replaced, the lock is to
Se la chiave
be replaced persa
è the
with key.oIn sostituita, la these
order to solve serratura è dathe
problems, sostituire
electroniccon la chiave.
magnetic Per and
card lock risolvere questi coded
the electronic problemi,
lock
vengono presentati
are present, la raised
which has serratura elettronica con
the management carta
level magnetica
of the e la serratura
access channel elettronica
to a certain extent, codificata,
and then thechechannel
ha al-
zato in una certa
management misura
enters il livello
into the di gestione
electronic age. della via di accesso e quindi quest'ultimo entra nell'era elettronica.

Componenti
Components Richiesti
Required
1 * RFID 1 * Keypad 1 * Mod.
Powerdi Alimentazione
Supply Module

342
1 * I2C LCD1602 1 * ULN2003 1 * Buzzer 1 * Motore Passo-Passo
Stepper Motor

1 * Mega 2560 Board 1 * Breadboard Several Jumper


Diversi Jumper Wires
Filari

343
Fritzing Circuit
In this example,
questo PowerilSupply
esempio ModuloModule is used to power
di Alimentazione the breadboard.
è usato per dare We get the
energia GND
alla of Mega 2560
breadboard. Board connected
Collegiamo il GND
della
to theScheda
cathodeMega
rail of 2560 con il binario
the breadboard, GNDcatodo dellatobreadboard,
of ULN2003 the cathode GND
rail ofdell'ULN2003 al VCC
the breadboard, binario catodo
to 5V della
OUTPUT of
breadboard,
Power Supply VCC ai 5V
and the OUTPUT
Stepper dell'Alimentazione
Motor to OUT1-OUT5 ofeULN.
il Motore Passo-Passo agli OUT1-OUT5 dell'ULN.

Mega 2560 Board LCD1602 RFID Buzzer Mega 2560 Board ULN Keypad
GND GND GND (-) GND GND
5V
5V VCC
VCC 5V
5V VCC
VCC
SDA SDA 11 IN1
SCL SCL 10 IN2
3.3V 3.3V 9 IN3
6 SDA 8 IN4
5 SCK 31 1
4 MOSI 33 2
3 MISO 35 3
7 IRQ 37 4
2 RST 39 5
12 (+) 41 6
43 7
45 8

344
345
Schematic Diagram

346
Example Explanation
Spiegazione dell'Esempio START

The
Il workflow
flusso of del
di lavoro the sistema
access control system
di controllo is
degli Inizializza
shown
accessiinè the flow chart.
mostrato nel diagramma. Approvato = 0

When
Quaando therenon
is noviene
authorized ID identified
identificato alcun (the
ID
variable “Approved” equals to 0), the device
autorizzato (la variabile "Approvato" è uguale will Approvato==1?
perform
a functions eseguirà
0, il dispositivo of ID identification and
funzioni di iden-
password identification.
tificazione ID e identificazione password. Leggi ID
Carta
If the
Se authorized
viene IDl'ID
trovato is identified (“Approved”
autorizzato equals
("Approvato"
to 1),1),
== theladoor willsiopen.
porta After
aprirà. that, the
Quindi, door will
la porta be
verrà Verifica ID
closed ainfew
chiusa seconds
pochi later and
secondi e lothe identified
stato status
identificato Pulisci Dati Letti Apri la
will beripristinato
verrà reset (“Approved” equals touguale
("Approvato" 0). a 0). porta

In addition
Oltre to the core
alla funzione di access control
controllo function,
degli accessithe
di
Approvato = 1 Verifica positiva?

projectil also
base, uses utilizza
porgetto LCD and active
anche un buzzer
LCD e unto Approvato = 0
complete attivo
cicalino the work
perof completare
the user interaction system
il lavoro del Inserisci
of the access
sistema control system.
di interazione con l'utente del sistema Password
Chiudi la
di controllo degli accessi.
Verifica Password porta
Pulisci Dati Ingresso

Verifica positiva?

347
Phenomenon
Immagine Picture
Fenomenologica

348
Part 4:4:Appendix
Parte Appendice
4.1 Add Libraries
4.1 Aggiungere Librerie

Cos'è is
What una Libreria?
Library?
Una libreria,
A library, che raccoglie
gathering alcune
some function definizioni
definitions anddi funzioni
header files,eusually
file di contains
intestazione, di solito
two files: contiene
.h (header due file:function
file, including .h (file
di intestazione,
statement, Macrocon la dichiarazione
definition, constructordella funzione,
definition, etc.) la
and definizione delle file,
.cpp (execution Macro,
with del costruttore,
function ecc.) e .cpp
implementation, (file
variable
di esecuzione,
definition, and socon
on).l'implementazione
When you need to use della funzione,
a function la definzione
in some library, youdijust
variabili,
need to...).
addQuando
a headerserve usare
file (e.g. una
#include
funzione and
<dht.h>), in una
thenlibreria, basta
call that aggiungere
function. This can un
makefileyour
di intestazione (ad esempio
code more concise. #include)
If you don't e quindi
want to use therichiamare
library, you tale
can
funzione. Questo può rendere il tuo codice più conciso. Se non si vuole usare la libreria, si può anche scrivere
also write that function definition directly. Though as a result, the code will be long and inconvenient to read.
direttamente la definizione della funzione. Di conseguenza, però, il codice sarà lungo e scomodo da leggere.

Add libraries
Aggiungere librerie
Some libraries are already built in the Arduino IDE, when some others may need to be added. So now let's see how to add
Alcune librerie sono già incluse nell'Arduino IDE, mentre altre potrebbero dover essere aggiunte. Perciò ora
one. There are 2 methods for that.
vediamo come aggiungerne una. Ci sono 2 metodi possibili.

Method 1
Metodo 1
Directly import
Importare the library nell'Arduino
direttamente in Arduino IDEIDE(take Dht as anDht
(prendere example
comebelow).
esempioThequi
advantage
sotto). of
Il this methoddi
vantaggio is easy
questoto
understand
metodo and èoperate,
è che semplice butdaon capire
the other
ed hand,
usare,only
maone library lato,
dall'altro can besi imported at a time.
può importare Souna
solo it is inconvenient when
libreria alla volta.
you need
Perciò to èadd
non quite a lot of
conveniente libraries.
quando è necessario aggiungere un bel po' di librerie.

Passo
Step 1:1: Selezionare
Select Sketch
Sketch -> -> Include
Include Library
Library -> -> Add
Add ZIP ZIP Library.
Library.

349
Passo
Step 2: 2: SunFounder
trovare
Find MegaMega
SunFounder Kit\Library
Kit\Library, Clicca Apri.
, Click Open.

350
Step 3: 3:
Passo When you see
quando “Library
si vede added
“Library to your
added libraries.
to your CheckCheck
libraries. "Include library"
"Include menu”,
library" it means
menu”, you have
significa cheadded the library
la libreria è
stata aggiunta
successfully. conuse
Please successo.
the sameSimethod
prega pertanto di utilizzare
to add other lo stesso metodo per aggiungere altre librerie.
libraries then.

Method 2
Metodo
Directlydirettamente
Copia copy the library to libraries/Arduino
le liberie nel percorso path. This methodQuesto
libraries/Arduino. can copy all libraries
metodo and addtutte
può copiare themleatlibreria
a time,ebut the
aggiungerle in una
drawback is that volta, ma
it is difficult lo svantaggio
to find è che è difficile trovare il percorso libraries/Arduino.
libraries/Arduino.

Step 1: Click File File


cliccare -> Preferences
-> Preferences e nella
and on finestrawindow
the pop-up pop-upyou
si può vedere
can see il percorso
the path della cartella
of the libraries folder indelle librerie
the text box as
nella
showncasella
below.di testo, come mostrato di seguito.

351
Step 3:3:
Passo Copy all Libraries
copiare the library
tutte leinlibrerie nellafolder.
cartella library.

Step 4:4:
Passo Go to the al
andare path above and
percorso yousiwill
sopra; see there
vedrà libraries
is auna
che c'è folder,
cartella click tocliccare
libraries, open it. per aprirla.

Step 5: 5:
Passo Paste all the nella
incollare libraries copiedtutte
cartella. before
le to the folder.
librerie Then you can see
precedentemente them in
copiate. Silibraries folder.quindi nella
troveranno
cartella delle librerie.

352
Copyright
Avviso sulNotice
Copyright
All contents
Tutti including
i contenuti but not
inclusi ma limited to texts,
non limitati a images, and codeeincodici
testi, immagini this manual are owned
in questo by the
manuale SunFounder
sono Company.
di proprietà della
SunFounder Company.
You should only Si personal
use it for dovrebbero
study,utilizzare solo enjoyment,
investigation, per studio or
personale, analisi, divertimento
other non-commercial ed altri
or nonprofit scopi
purposes,
non
undercommerciali o senza finiand
the related regulations di lucro, ai sensi
copyrights delle
laws, normative
without correlate
infringing e delle
the legal leggi
rights sul author
of the copyright,
and senza violare
relevant right
iholders.
diritti legali dell'autore
For any e dei
individual relativi titolari
or organization di uses
that tali diritti.
these Verso qualunqueprofit
for commercial persona od organizzazione
without permission, the che li uti-
Company
lizzasse per right
reserves the scopitocommerciali senza autorizzazione, la Società si riserva il diritto di intraprendere azioni legali.
take legal action.

353

Potrebbero piacerti anche