0% found this document useful (0 votes)
117 views132 pages

Introduction To Arduino Projects The Best User Guide For Beginners

Uploaded by

camruthomas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
117 views132 pages

Introduction To Arduino Projects The Best User Guide For Beginners

Uploaded by

camruthomas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 132

www.electronic07.

com
INTRODUCTION TO

ARDUINO PROJECTS

THE BEST USER GUIDE FOR

BEGINNERS

BENJAMIN ISRAEL

Copyright © 2021 BENJAMIN ISRAEL

All rights reserved. This book is copyright and no part of it may be


reproduced, distributed, or transmitted in any form or by any means,
including photocopying, recording, or

other electronic or mechanical methods, without the prior written


permission of the publisher, except in the case of brief quotations embodied
in critical reviews and certain other noncommercial uses permitted by
copyright law.

Printed in the United States of America

Copyright © 2021 BENJAMIN ISRAEL

Contents

INTRODUCTION .................................................................................... 1

What is Arduino good for? ........................................................... 4

CHAPTER ONE: THE ARDUINO UNO REV 3 BOARD


.............................. 5

CHAPTER TWO: THE ARDUINO UNO WIFI REV 2 BOARD


..................... 8

www.electronic07.com
CHAPTER THREE: INTRODUCTION TO THE ARDUINO
PROGRAMMING

LANGUAGE .........................................................................................11

Support for Other Language ..........................................................15

The Arduino Programming Language Built-in Constants ...............15

Arduino Math Constants ............................................................16

The Arduino Programming Language Built-in Functions ...............17

Program lifecycle ........................................................................17

Handling I/O ...............................................................................17

Digital I/O ...................................................................................17

Analog I/O ..................................................................................19

Time functions............................................................................19

Math functions ...........................................................................20

Working with alphanumeric characters .....................................21

Random numbers generation ....................................................22

Working with bits and bytes ......................................................22

Interrupts ...................................................................................23

Milli, Micro, Nano and Pico as Units of Measurement ..............24

CHPTER FOUR: THE ARDUINO MKR WIFI 1010


..................................25

Form factor ................................................................................25


Power .........................................................................................26

Processor ....................................................................................27

Memory ..................................................................................... 27

I/O Pins ....................................................................................... 27

IoT connectivity .......................................................................... 30

Security ...................................................................................... 30

Li-Po charging circuit .................................................................. 30

Price ........................................................................................... 30

CHAPTER FIVE: INTRODUCTION TO ELECTRONICS


............................ 32

Electronics Basics: Analog vs Digital .............................................. 33

Electronics Basics: Current ............................................................. 37

Electronics Basics: Voltage ............................................................. 38

Electronics Basics: Vcc, Ground, .................................................... 40

Electronics Basics: Resistance ........................................................ 40

Electronics Basics: Short Circuit ..................................................... 42

Electronics Basics: Building Your First Circuit ................................ 43

Electronics Basics: Prototyping Using Breadboards ...................... 57

Electronics Basics: Using a Multimeter .......................................... 62

CHAPTER SIX: HOW YOU CAN MEASURE VOLTAGE, CURRENT


AND
RESISTANCE USING A MULTIMETER ..................................................
66

How to Measure Voltage ............................................................... 66

How to Measure Resistance .......................................................... 67

How to Measure Current ............................................................... 71

CHAPTER SEVEN: ITEMS OR TOOLS TO BUY TO GET STARTED


WITH

ARDUINO AND ELECTRONICS ............................................................


76

CHAPTER EIGHT: ARDUINO PROJECT – BLINK A LED


........................ 82

CHAPTER NINE: THE ARDUINO BUILT-IN LED ....................................


93

CHAPTER TEN: BREADBOARD POWER SUPPLY MODULE


.................. 96

CHAPTER ELEVEN: THE ARDUINO CREATE PLATFORM


.................... 104

CHAPTER TWELVE: HOW TO CONNECT TO A WIFI NETWORK


USING

AN ARDUINO ....................................................................................110

CHAPTER THIRTEEN: HOW CAN YOU RUN A WEB SERVER ON AN

ARDUINO? ........................................................................................119

CONCLUSION ....................................................................................135

INTRODUCTION

www.electronic07.com
Arduino is a revolutionary technology in the electronics ecosystem.

By this, I do not mean it introduced a new dominant microprocessor or


anything like that.

It essentially produced an entire industry, a movement, where there was


none existent before it.

I mean the makers movement. Before Arduino existed, electronics was not
interesting and easy to learn as it is today, and there was not so much of
resources available.

Arduino was developed in in a city called Ivrea in Italy. This is where the
company that created the first personal

computer in 1965 is also located.

Arduino was specially designed to be a learning device ab initio. This


simple fact explains why the original Arduino Core team incorporated
several design choices in the programme.

The most important success factor of Arduino is that it is completely Open


Source, and is one of the first to do so too.

Both the hardware and software are open source.

For instance, the diagrams of the latest version Arduino Uno board, the
Arduino Uno Wifi Rev2, can be found online. It’s cool because you can
build your own Arduino, if you want.

In fact, companies can build and sell their own Arduino clones, and many
are doing it.

Additionally, there’s a whole ecosystem of tools, libraries and educational


resources around it that made it a huge success. A few years ago, it was
extremely difficult to get boards with material that was practical, students-
oriented rather than technicians-oriented. Today, Arduino has changed all
that. Also, Arduino created an IoT cloud hub, to let you connect devices to
the network.

Over time, the Arduino team has released several

different boards such as Arduino Uno, Arduino Mega, Arduino Diecimila,


Arduino Robot, Arduino Nano, Arduino

Micro, Arduino Leonardo, Arduino MKR etc.

Each board has its own use case. Arduino Nano and Arduino Micro for
instance are awesome for IoT, wearables and small devices. However,
Arduino Mega has more memory and I/O

pins than any other board.

Nonetheless, the Arduino Uno board is considered the best board for
learning so far, and it’s included in many toolkits and used in so many
tutorials today.

The Arduino MKR WiFi 1010 board is commonly used in IoT, as it has
buit-in WiFi and Bluetooth.

Arduino does not have its own operating system, and it simply runs a single
program at a time. So, you don’t have to worry about anything since there is
nothing else than your program running on the Arduino.

In fact, most Arduino boards do not even have network connection, out of
the box! Although some do, like the Arduino Uno WiFi rev 2 or the
Arduino MKR WiFi 1010.

Once you load a program, it boots any time the Arduino is powered, either
via USB or via the power port via a AC-to-DC power cable or a battery.

By inference, once you have loaded the program, you can put the Arduino
on a mountain with a solar panel and a battery, and it will keep running
until there’s power.
It only operates programs that were compiled for the Arduino platform,
which typically means programs written

in the Arduino Language, which is C++ with some suitable features that
make it easy for beginners to start with.

This is not to say you are restricted to it. If you don’t mind having the
Arduino attached to the USB port of the computer (or a Raspberry PI
driving it), you can run Node.js code on it using the Johnny Five project,
which is pretty cool. There are related tools for other languages, like
pyserial and Gobot .

What is Arduino good for?

Firstly, it’s awesome for learning electronics.

Secondly, Arduino is wonderful when you want to compile

a program for it, attach a battery or a power connector and put it somewhere
to run, and play around with sensors and some other really cool stuffs that
interface with the real world.

For instance, you could use an Arduino to power your self-watering plants
or track the temperature outside, or power some other home automation
stuff.

4
CHAPTER ONE: THE ARDUINO UNO REV

3 BOARD
This is a microcontroller board.

The reference board shown above is the reference Arduino

version for prototyping. A good number of tutorials use this version of


Arduino as their reference board.

The Arduino Uno rev 3 possesses the same form factor of the Arduino 101,
Arduino Zero, Arduino Yún, Arduino Leonardo, Arduino Uno Wifi rev 2
and Arduino Ethernet.

It boasts of an 8-bit microcontroller, an ATmega328P,


which has 32 KB of Flash memory, 2 KB of SRAM and 1 KB of EEPROM.

It operates at 16MHz with a voltage of 5V, and it can be powered with a


recommended input of between 7V and 12V.

As per I/O, the Arduino Uno has a USB-B port that can be

used by a computer to transfer new programs to run, a power input and a set
of I/O pins. It also has 20 I/O pins, 14

digital and 6 analog pins that have 10 bits, mapping values from 0 to 1023.

Looking at the above picture carefully, we’ll notice that at the top of it, we
have 14 digital I/O pins, which can be 6

configured

to

be

output

pins

or

input

pins

programmatically.

Then, at the bottom of it, we have the power pins, and the 6

analog input pins.

There is also a built-in led, linked to pin 13, which offers us status
information.
In addition, the Arduino Uno comes with a USB port that

allows you to connect it to the computer and load a program on it.

The Arduino does not have an operating system, and it runs one single
program at a time.

Once you load a program, it boots any time the Arduino is powered, either
via USB or via the power port via a AC-to-DC power cable or a battery. In
that case, once you load the program, you can put the Arduino on a
mountain with a solar panel and a battery, and it will keep running until
there’s power.

7
CHAPTER TWO: THE ARDUINO UNO

WIFI REV 2 BOARD


As stated earlier, the Arduino Uno is a microcontroller board. It is the most
up-to-date reference version of Arduino, as well as the latest version of an
official Arduino device.

The Arduino Uno Wifi rev 2 possesses the same form factor as the Arduino
101, Arduino Zero, Arduino Yún, Arduino Leonardo, Arduino Uno and
Arduino Ethernet.

It

comes

along

with

an

8-bit microcontroller,

an ATmega4809, which has 48 KB of Flash memory, 6 KB of 8

SRAM and 256 bytes of EEPROM. That’s a lot more memory than
previous Arduino Uno rev 3 boards with the

ATmega328P. Take note of this change if you have an older Arduino Uno
board.

The Arduino runs at 16MHz at a voltage of 5V, and can be

powered with a recommended input of between 7V to 12V.

www.electronic07.com
When it comes to I/O, the Arduino Uno has a USB-B port

that can be used by a computer to transfer new programs to run, a power


input and a set of I/O pins. It also has 20 I/O

pins, 14 digital and 6 analog pins that have 10 bits, mapping values from 0
to 1023.

It has a WiFi module that supports 802.11b/g/n, the NINA-

W13 which comes with an integrated TCP/IP protocol stack that is capable
of giving access to a WiFi network, with hardware-based security.

Otherwise, you can let the Arduino act as an access point, so you can
connect to it.

Also, it comes with an integrated IMU (Inertial

Measurement Unit) which allows you to do some very nice

motion sensor applications, the LSM6DS. This module provides 3D


accelerometer and 3D gyroscope.

The Arduino Uno possesses an integrated high speed ADC, analog-to-


digital converter.

The Arduino Uno has a USB port that lets you to connect it to the computer
and load a program on it.

The Arduino does not have an operating system, and it runs just one single
program at a time.

Any time a program is loaded, it is booted whenever the Arduino is


powered, either via USB or via the power port via a AC-to-DC power cable
or a battery. This means that you

can load the program and put the Arduino on an elevation


with a solar panel and a battery, and it will keep running until there’s power.

10

CHAPTER THREE: INTRODUCTION TO

THE ARDUINO PROGRAMMING

LANGUAGE

Arduino, primarily, supports a language that is called the Arduino


Programming Language, or Arduino Language.

The

Arduino

Language

is

founded

upon

the Wiring development platform, which in turn is based upon Processing,


which if you are not familiar with, is what p5.js is based upon. It’s an
extensive account of projects building upon other projects, in a very Open
Source way. The Arduino IDE is built upon the Processing IDE, and the
Wiring IDE which in turn builds on top of it.

When we’re working with Arduino, we commonly use the

Arduino IDE (Integrated Development Environment), a

software available for all the major desktop platforms (macOS, Linux,
Windows), which offers us two things: firstly, a programming editor that
incorporates libraries support, and secondly, a means to easily compile and
load our Arduino programs to a board connected to the
computer.

11

The Arduino Language is essentially a framework built on top of C++. You


can argue that it’s not a real programming language in the customary way,
but I think this is for clearer understanding for learners.

When we have program written in the Arduino

Programming Language, we called it a sketch and is usually saved with the


. ino extension (from Arduino).

The main difference from “normal” C or C++ is that you wrap all your code
into two major functions. You can have more than two anyway, of course,
but any Arduino program

must provide at least two

One is called setup(), the other is called loop(). The former is called once,
when the program starts, the latter is repeatedly called while your program
is running.

There is no main() function like you are used to in C/C++ as the entry point
for a program. Once you have compiled your sketch, the IDE will make
sure the end result is a correct C++

program and will essentially add the missing glue by preprocessing it.

Every other thing is normal C++ code, and since C++ is a superset of C,
any valid C is also valid Arduino code.

12

One important difference that might cause you troubles while using
Arduino is that while you can spawn your program over multiple files,
those files must all be in the same folder. This might be a big limitation if
your program will grow very large, but at that point it will be easy to move
to a native C++ setup, which is possible.
The Arduino Programming Language has built-in libraries which allow you
to easily integrate with the functionality provided by the Arduino board.

Your first Arduino program will definitely include making a led turn on the
light, and then turn off. To do this, you will use

the pinMode(), delay() and digitalWrite() functions,

along with some constants like HIGH, LOW, OUTPUT.

An example is the canonical first Arduino project (the

“Hello, World!”):

#define LED_PIN 13

void setup() {

// Configure pin 13 to become a digital output

pinMode(LED_PIN, OUTPUT);

13

void loop() {

// Turn on the LED

digitalWrite(LED_PIN, HIGH);

// Wait 1 second (1000 milliseconds)

delay(1000);

// Turn off the LED

digitalWrite(LED_PIN, LOW);
// Wait 1 second

delay(1000);

This is all part of the Arduino Programming Language, or you may call it
suite or library.

14

Support for Other Language

It is important to note that you are not limited to using this language and
IDE to program an Arduino. There are projects to let you run Node.js code
on it using the Johnny

Five project, Python code using pyserial and Go code with Gobot, but the
Arduino Programming Language is certainly the one you’ll find in most
tutorials, as it’s the primary and official way to work with these devices.

The Arduino Programming Language Built-in

Constants

Arduino offers two constants we can use:

HIGH equates to a high level of voltage, which varies depending on the


hardware (>2V on 3.3V boards like Arduino Nano, >3V on 5V boards like
Arduino

Uno) LOW equates to a low level of voltage. Also, the exact value depends
on the board used

There are three constants we can use in combination with

the pinMode() function:

▪ NPUT sets the pin as an input pin


▪ OUTPUT sets the pin as an output pin

15

▪ INPUT_PULLUP sets the pin as an internal pull-up resistor

The other constant we have is LED_BUILTIN, which points

to the number of the on-board pin, which usually equates to the number 13.

In addition to this, there is also the C/C++

constants true and false.

Arduino Math Constants

▪ M_PI the constant pi (3.14159265358979323846)

▪ M_E the constant e

▪ M_LN10 the natural logarithm of the number 10.

▪ M_LN2 the natural logarithm of the number 2.

▪ M_LOG10E the logarithm of the e to base 10.

▪ M_LOG2E the logarithm of the e to base 2.

▪ M_SQRT2 the square root of 2.

▪ NAN the NAN (not a number) constant.

16

The Arduino Programming Language Built-in Functions

In this section we shall make reference to the built-in functions provided by


the Arduino Programming Language.

Program lifecycle
▪ setup() This function is called only once, when the program starts, and
when the Arduino is shut down and

restarted.

▪ loop() This function is called repeatedly while the Arduino program is


running.

Handling I/O

The following functions are used to handle input and output from your
Arduino device.

Digital I/O

▪ digitalRead() reads the value from a digital pin. Accepts a pin number as a
parameter, and returns

the HIGH or LOW constant.

▪ digitalWrite() writes a HIGH or LOW value to a digital output

pin.

You

pass

the

pin

number

and HIGH or LOW as parameters.

17

www.electronic07.com
▪ pinMode() sets a pin to be an input, or an output. You pass the pin number
and the INPUT or OUTPUT value

as parameters.

▪ pulseIn() reads a digital pulse from LOW to HIGH and then

to LOW again,

or

from HIGH to LOW and

to HIGH again on a pin. The program will block until the

pulse is detected. You specify the pin number and the kind of pulse you
want to detect (LHL or HLH). You can

specify an optional timeout to stop waiting for that pulse.

▪ pulseInLong() is same as pulseIn(), except it is

implemented differently and it can’t be used if interrupts are turned off.


Interrupts are commonly turned off to get a more accurate result.

▪ shiftIn() reads a byte of data one bit at a time from a pin.

▪ shiftOut() writes a byte of data one bit at a time to a pin.

▪ tone() sends a square wave on a pin, used for

buzzers/speakers to play tones. You can specify the pin,

and the frequency. It works on both digital and analog

pins.

▪ noTone() stops the tone() generated wave on a pin.


18

Analog I/O

▪ analogRead() reads the value from an analog pin.

▪ analogReference() configures the value used for the top input range in the
analog input, by default 5V in 5V

boards and 3.3V in 3.3V boards.

▪ analogWrite() writes an analog value to a pin

▪ analogReadResolution() lets you change the default analog bits resolution


for analogRead(), by default 10

bits. Only works on specific devices (Arduino Due, Zero

and MKR)

▪ analogWriteResolution() lets you change the default analog bits resolution


for analogWrite(), by default 10

bits. Only works on specific devices (Arduino Due, Zero

and MKR)

Time functions

▪ delay() pauses the program for a number of milliseconds specified as


parameter

▪ delayMicroseconds() pauses the program for a number of microseconds


specified as parameter

▪ micros() the number of microseconds since the start of the program.


Resets after ~70 minutes due to overflow

19
▪ millis() the number of milliseconds since the start of the program. Resets
after ~50 days due to overflow

Math functions

▪ abs() the absolute value of a number

▪ constrain() constrains a number to be within a range, see

usage

▪ map() re-maps a number from one range to another, see

usage

▪ max() the maximum of two numbers

▪ min() the minimum of two numbers

▪ pow() the value of a number raised to a power

▪ sq() the square of a number

▪ sqrt() the square root of a number

▪ cos() the cosine of an angle

▪ sin() the sine of an angle

▪ tan() the tangent of an angle

Note: There are more built-in mathematical functions the ones listed above.
These are the common ones you’re likely to make use of most at this level.

20

Working with alphanumeric characters

▪ isAlpha() checks if a char is alpha (a letter)


▪ isAlphaNumeric() checks if a char is alphanumeric (a letter or number)

▪ isAscii() checks if a char is an ASCII character

▪ isControl() checks if a char is a control character

▪ isDigit() checks if a char is a number

▪ isGraph() checks if a char is a printable ASCII character, and contains


content (it is not a space, for example)

▪ isHexadecimalDigit() checks if a char is an hexadecimal digit (A-F 0-9)

▪ isLowerCase() checks if a char is a letter in lower case

▪ isPrintable() checks if a char is a printable ASCII character

▪ isPunct() checks if a char is a punctuation (a comma, a semicolon, an


exclamation mark etc)

▪ isSpace() checks if a char is a space, form feed \f, newline \n, carriage
return \r, horizontal tab \t, or vertical tab \v.

21

▪ isUpperCase() checks if a char is a letter in upper case

▪ isWhitespace() checks if a char is a space character or an horizontal tab \t

Random numbers generation

▪ random() generate a pseudo-random number

▪ randomSeed() initialize the pseudo-random number

generator with an arbitrary initial number

Just like in most languages, it’s impossible to get really random numbers in
Arduino, and the sequence is always the same, so you seed it with the
current time or (in the case of Arduino) you can actually read the input from
an analog

port.

Working with bits and bytes

▪ bit(): this calculates the value of a bit (0 = 1, 1 = 2, 2 = 4, 3

= 8…)

▪ bitClear(): it clears and also sets a bit of a numeric variable. Receives a


number, and the number of the bit

starting from the right

▪ bitRead(): It reads a bit of a number. Also Accepts a number, and the


number of the bit starting from the right

22

▪ bitSet(): It sets to 1 a bit of a number. It also accepts a number, and the


number of the bit starting from the right

▪ bitWrite(): It’s used to write 1 or 0 to a specific bit of a number Also


accepts a number, the number of the bit starting from the right, and the
value to write (0 or 1)

▪ highByte(): Gets the high-order (leftmost) byte of a word variable (which


has 2 bytes)

▪ lowByte(): Helps to get the low-order (rightmost) byte of a word variable


(which has 2 bytes)

Interrupts

▪ noInterrupts() : disables interrupts

▪ interrupts(): re-enables interrupts after they’ve been disabled


▪ attachInterrupt(): allows a digital input pin to be an interrupt. Different
boards have different allowed

pins, you can check the official docs.

▪ detachInterrupt(): disables

an

interrupt

enabled

using attachInterrupt()

23

Milli, Micro, Nano and Pico as Units of Measurement When it comes to


electronics and time measurements, you’ll often come across the use of
these terms: milli, micro, nano, pico.

Here are the meanings of these terms:

▪ Milli equals 10^-3 equals 0,001

▪ Micro equals 10^-6 equals 0,000 001

▪ Nano equals 10^-9 equals 0,000 000 001

▪ Pico equals 10^-12 equals 0,000 000 000 001

Take note of the order in which they’re used here to help you remember
what they mean: repeat it a few times, milli-micro-nano-pico and you’ll
remember them the next time.

24
CHPTER FOUR: THE ARDUINO MKR WIFI

1010

This is the first board that has WiFi and Bluetooth connectivity built-in, and
it’s quite exciting to talk about the opportunities and possibilities it enables.

Let’s have an overview of the board, and compare it to the Arduino Uno,
which is the one most commonly used by beginners.

Form factor

Looking at the physical properties, the Arduino MKR Wifi

1010 measures 61.4mm x 25mm and weighs just 32 grams.

Compared to the Arduino Uno board, the Arduino MRK

WiFi 1010 is much smaller (less than half).

25
Arduino Uno Wifi

Arduino MKR Wifi

Power

The Arduino MKR WiFi 1010 can be powered with a 5V


input, or with a Micro-USB connector.

It runs at 3.3V. This is a crucial difference with Arduino Uno, which runs at
5V. 3.3V, the maximum voltage the I/O pins

can support.

26

Processor

The Arduino MKR WiFi 1010 board goes with a low power

SAMD21 Cortex-M0+ 32-bit ARM processor.

The processor is 32 bit. The Arduino Uno board presents the ATmega328
processor, which is 8 bit.

Memory

The board holds 256KB of Flash Memory and 32KB of SRAM.

I/O Pins

www.electronic07.com
The Arduino MKR WiFi 1010 provides:

▪ 8 Digital I/O pins, from pins 0 to 7.

▪ 7 Analog Input pins (ADC 8/10/12 bit) and pins A0 / A6.

▪ 1 Analog Output pin (DAC 10 bit), the one recognized with DAC0/A0.

27

▪ The DC current for each I/O pin is given as 7mA.

Pins 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 18, 19 are all PWM pins.

28
29

IoT connectivity
The Arduino MKR WiFi 1010 has the provision of a WiFi module, the
WiFi U-BLOX NINA-W10 Series Low Power

2.4GHz. It works with the protocol 802.11 b/g/n and also provides
Bluetooth Low Energy (BLE).

Security

The board has a crypto chip that allows SHA-256 secure connections, the
ATECC508.

Li-Po charging circuit

When you’re charging the Arduino MKR WiFi 1010 board through the
Micro-USB port, it can charge an external battery through its Li-Po
charging circuit.

However, the battery needs to be a Li-Po Single Cell, 3.7V, 700mAh


minimum.

Once the USB power is disconnected, the device switches to the external
battery automatically.

Price

As per the price, the Arduino MKR WiFi 1010 is more expensive than an
Arduino Uno Rev3 board, but less expensive than an Arduino Uno WiFi
Rev2.

30
If we consider the fact that Arduino Uno Rev3 board does

not have WiFi / Bluetooth connectivity, we would not even want to compare
them – they are no match!

Therefore, we would be right to say the Arduino MKR WiFi

1010 is more economical than its Uno IoT counterpart, Arduino Uno WiFi
rev2, which can be considered its educational counterpart.

31

CHAPTER FIVE: INTRODUCTION TO

ELECTRONICS

In the last decade or so, electronics have become more advanced than ever.
We have moved from a society where

computers were once installed upon desks to one in which

everyone now has an ultra-modern internet connected device in their


pockets.
I believe in the near future, we’ll be deeply immersed into much more
electronics than we are today, with the adoption of 5g technology, cheap
mobile networking and the constant development of renewable energies, an
understanding of how all that works is a highly valuable skill capable of
earning you high amounts of income as well as giving you a lot of
satisfaction in your craftsmanship.

Building your own devices and tools and watching them actually work, in
the real world, is something that can make you really happy and feel very
proud of yourself.

To start with, we go to the very basics of electronics. Let’s start with


Analog Electronics.

Meanwhile, let’s work on simple projects first, with increasing complexity


and fun as we go on.

32

You’ll really start getting excited when we begin to add programmable


devices in the mix, Arduino in particular.

You’ll know how to program Arduino starting from beginner to advanced,


with the Arduino Language (C++). In addition, we’ll also use other
languages, like the CircuitPython and Johnny Five, and we’ll work on very
interesting projects using it.

Electronics Basics: Analog vs Digital

We

can

divide

electronics

into
two

major

categories: analog and digital.

Everything in the natural world is analog. Temperature, light, distance,


speed, humidity, sound, etc. are measured in an almost infinite amount of
values and accuracy.

ANALOG is natural while DIGITAL is artificial. In their ancestral quest to


comprehend nature and create artificial systems and simulations, humans
contrived the concept of

digital measurements and values.

digital

representation

can

only

assume

two

states: on or off. 1 or 0.

33

Being able to represent basic values this way, that is, using only 0 and 1
values, made it possible to solve complex problems in a simple way, and
ultimately led us to producing things like our computers, smartphones and
even the Internet.
It is possible to combine multiple binary values to represent numbers that
have more than two states. For instance, if we have two numbers, we can
define four states, if we have three numbers, we can define eight states, and
if we have four numbers, we can define sixteen, and so on.

Then we use definite protocols and conventions to represent values.

For instance, we can represent decimal numbers using a series of bits:

1 can be represented as 1×20

10 can be represented as 1×21+0×20

111 can be represented as 1×22+1×21+1×20

Zeros in a number can be dropped, or added if needed, because they do not


mean anything on the left or the top left 1: 110 can be represented a 0110 or
00000110 if needed. It holds exactly the same meaning, because as the
system 34

above explained, we are simply multiplying a power of 2

times zero.

Depending on the value we’re representing, we must have to have an


adequate number of digits to represent sufficient numbers.

If we want to have 16 values, we will count from 0 to 15, that means we


need 4 digits (bits). With 5 bits, we’ll be able to count 32 numbers. 32 bits
will give us 4,294,967,296 possible numbers.

64 bits will give us 9,223,372,036,854,775,807 possible numbers.

The following is a simple conversion table for the first 4

digits, which we can generate using just 2 bits:

Decimal number Binary number


0

00

01

10

11

35

Below is a simple conversion table for the first 8 digits: Decimal number
Binary number

000

001

010

011

100
5

101

110

111

Note the changes that occur in the sequence above –

addition of 1 instead of 0 in the series from 4 to 7.

Below is a simple conversion table for the first 16 digits: Decimal number
Binary number

0000

0001

0010

0011

0100

5
0101

0110

36

0111

1000

1001

10

1010

11

1011

12

1100

13

1101

14

1110
15

1111

Electronics Basics: Current

Current simply refers to the flow of electrons between two points with
different voltage. Current is measured

in ampere (A).

There are 2 types of current, namely: alternating current (AC) and direct
current (DC)

In direct current (DC), the current flows in one direction.

Example is the the type of current generated by batteries.

In alternating current (AC), the current changes direction from time to time.
This is the type of current that powers our houses from a grid that we
connect to.

37

The two types of current are different in nature and have different
characteristics, and thus, they allow very different usages and applications.

For example, in long distance transmission of current, we use AC instead of


DC.

Nonetheless, most electronic devices run with DC. We can

transform AC into DC using rectifier.

We can also transform DC into AC using devices

called power inverters. This is what is commonly used in recreational


vehicles.
Electronics Basics: Voltage

In simple terms, we define voltage as the electric potential that electrons


have to flow from one point to another in a circuit. Usually, one point has
more charge than the other, and electrons flow from the point with higher
charge to the point with lower charge.

It is measured in volts (V).

The more the voltage, the more the electrons that flow in a circuit: that is
what we call current.

38

Think of having a circuit with a LED light. Let’s first of all power it with a
1.5V battery, lighting up the led a little bit. If you then add another 1.5V
battery to make a 3V battery, the light will shine more, because you now
have more current

flowing in the circuit.

Earth has a null electric potential, i.e, 0V (zero volts). We call it ground.

Voltage is a comparative measure. It is used to measure the difference of


potential between one point and another.

Thus, when we say 5V, for instance, we mean 5V in relation to ground.

Most of the commercial DC (direct current) electronic devices will run at


5V or 12V.

Usually, AA batteries provide 1.5V of power. This means the + pole of the
battery has 1.5V more voltage than the - pole. Some devices will use
several batteries connected with each other to provide more voltage, for
example 3V

with 2 batteries connected in series.

If you live in Europe, your home is wired with a 230V or 110V


www.electronic07.com

if you live in the US alternating current (AC). Different countries might


have different values.

39

Electronics Basics: Vcc, Ground,

In all the projects and explanations in this book, you will come across
various terms that mean the same thing. For instance, the terms -, 0V,
negative pole of the battery, ground, GND and Vss all mean the negative
pole of the battery that is at 0V.

On the other hand, +, Vcc, Vdd or positive pole refers to the positive pole
of the battery which precise value will be different based on the battery or
power source utilized, e.g. 9V, 5V, 3.3V, as the case may be.

You may wonder why do we have to use so many terms?

That’s because different families of electronic components adopted different


acronyms:

• TTL (Transistor-Transistor

Logic)

components

use Vcc and GND.

• CMOS (Complementary

Metal-Oxide-

Semiconductor) components use Vdd and Vss).

Electronics Basics: Resistance

Resistance is the measure of opposition or restriction to the flow of an


electric current in an electric circuit.
40

Resistance restricts the amount of current flowing in a circuit. Every


component in a circuit has some resistance.

Even the wire has some resistance, but it’s extremely low.

Resistance is measured in ohms (Ω).

1 ohm, simply put, is defined as 1 volt divided by 1 ampere: 1 Ω = 1 V / 1


A

That’s what is called the Ohm’s law: R = V / I, where R is the symbol for
resistance, V is the symbol for voltage and I is the symbol for current.

From this we can derive the following:

▪V=R*I

▪I=V/R

A resistor is a circuit component that’s created solely to provide a certain


amount of resistance.

We have resistors of various values. The very common ones you will find
used in circuits are 220Ω, 1kΩ, 4.7kΩ, 10kΩ, and so on.

Having Omh’s law, we can calculate the current flowing in a circuit when
you know the voltage provided by the battery, 41

and the resistance that’s provided by the circuit components.

If the battery provides 5V and the circuit provides a 1kΩ resistance, the
current flowing in the circuit will be 5mA.

Electronics Basics: Short Circuit

In an electronic system there are different components that perform


different jobs, and combine to form a circuit.
Typical circuits have a voltage source, and devices that have some utility.

The voltage source can be a battery. An alternative can be an Arduino board


providing power.

Let’s assume the voltage is 5V, and we a have a positive pole as well as a
negative pole.

If we then connect those 2 poles directly by means of a wire, we’re going to


have a short circuit.

Short circuits are dangerous and capable of causing serious damage to our
devices and components, making them

unusable. That’s why we take a lot of precautions to avoid them.

42

Even in the case of a 1.5V battery, the amount of current flowing between
the positive and negative poles can ignite a fire.

You can imagine what will happen with a larger battery.

Some batteries (including your cell phones’) will explode if short-circuited.

Electronics Basics: Building Your First Circuit

One very simple, yet correctly-working circuits we can build is a circuit to


light a LED.

We’re going to use a 9V battery, a 470ohm resistor, and a LED.

Later, we’ll talk about resistors and LEDs in details, but let’s create our first
circuit now.

We have many online tools that you can use to simulate a

circuit. In this book, we’re going to use Tinkercad, and is available for free
use at https://tinkercad.com.
43

Tinkercad, is a web application made by Autodesk, the creators of the


renowned AutoCAD. It allows you create and simulate electronic circuits as
well as create designs for 3D

printing.

Create free user account on the website, then from the dashboard choose the
Circuits menu:

44
Then click the Create new Circuit button to display the circuit builder
interface:

45
Here, you can drag and drop components from the right sidebar on the main
screen.

Select a 9V voltage battery, a resistor and a LED: 46


By hovering each item, you’ll see the connections you can create from
them, or to them. For example, the battery shows a positive pole and a
negative pole:

47

Pull the negative pole to meet one of the poles of the resistor:

At this point, connect the resistor to the pole of the LED

called cathode, the one that’s straight, on the left.

Lastly, connect the anode, the right pin of the LED, to the positive pole of
the battery:

48
You can change the colors of the wires by clicking on them: 49
You can also alter the settings for each component by clicking on it. For
example, click the resistor to reveal and modify its resistance value, which
is 1kΩ by default: 50

www.electronic07.com
Double-click a wire to add a point to it for a nicer circuit: 51
After a little tidying up, you’ll have this result:

52
Now click the Start simulation button. You’ll see the LED

light up, till you click Stop simulation:

53
Now try changing the resistance to 220Ω:

54
Then run the simulation again, and you’ll see a warning on the LED,
notifying you the current flowing through is too much, and that the
recommended maximum amount of

current the LED can handle is 20mA:

55
While the simulation is running, you can as well change the value of the
resistor. If you use 1000Ω instead of 220, you’ll notice the light on the led
will be less bright.

Add 10000Ω, and the LED will not give any light at all.

The higher the resistance of the resistor, the lesser the current flowing in the
circuit, and consequently, the dimmer the light produced by the LED.

Recall Ohm’s law, I = V / R: the current flowing through the circuit with a
220Ω resistor is 9 / 220 = 40mA.

Using a 1kΩ resistor the current is 9⁄1000 = 9mA.

56
Take a look at the same circuit, but in the real world:

Electronics

Basics:

Prototyping
Using

Breadboards

Looking closely at the image below, you will see a simple circuit with a
battery, a resistor and a LED.

57
The elements are shown inside a tiny white box which is called the
breadboard:

Breadboard

The breadboard has 17 sets of 5 interconnected elements on one side, and


another 17 sets of interconnected elements on the other side.

58

Underneath the surface, the 5 holes in a set are connected with each other,
so as to enable us create electric connections very easily.

It’s a tiny board suitable for simple prototyping.

Below is a bigger board:

The principle is the same, except that we have more elements on the outer
border, the ones wrapped inside the red and blue lines:

59
In this instance, the items on the outer boarder are connected longitudinally,
and then, orthogonally to the 5-elements sets in the inside of the board (see
illustration below):

60
We use them to connect the positive and negative poles of the battery (or
any other power source) to the board, so your elements can have easy
access to them on the board.

Red wires are commonly for the + positive pole and black wires for the -
negative pole:

You typically prototype a circuit using a breadboard:


61

and once you’re set to move on, all you need is just to solder it into a
perforated board.

Electronics Basics: Using a Multimeter

A digital multimeter is one handy tool, among the few you’ll need to start
with.

There are several types of multimeters, from very cheap ones (<10$) like
this one below which is quite ok for a beginner.

As you grow on to become a professional, you can get a great one for <
30$. Take a look at this:

62
63
If you compare these two, you’ll see there’s a big difference in size and
build quality:

You can also see one has a 10A port, and the other has a 20A port. That is
to say one can measure up to 20 Ampere of current before breaking its fuse,
the other half of that.

Also, the mA port can measure up to 500mA in the bigger


www.electronic07.com

one, but only 200mA in the smaller one.

64

Again, one can measure temperature as well with a special cable. It has a
light, and so on.

A digital multimeter can be used to measure voltage (voltmeter), current


(ammeter), resistance (ohmmeter), capacity, frequency, and so on.

It’s one tool having many other tools built in.

Let’s see how you can measure the first 3 things.

65
CHAPTER SIX: HOW YOU CAN MEASURE

VOLTAGE, CURRENT AND RESISTANCE


USING A MULTIMETER

How to Measure Voltage

Follow the simple steps below:

1. Take a battery

2. Select the V symbol

3. Connect the black connector to COM, the common

ground,

4. Connect the red connector to the V symbol

5. Connect

the

other

end

of

the

cables

to

the + and - battery terminals


66

There you have the result:

How to Measure Resistance

Follow the simple steps:


1. Connect the two cables to the two ends of a resistance 2. Select the Ω
symbol on the multimeter

67
It’s a 220Ω resistance.

Here’s the same measurement on the cheaper multimeter:

68

Note: In the previous experiment, we didn’t have to set the scale, it was
automatically determined. But in this case, if you notice the resistance is too
low or too high for the scale, 69
you

need

to

adjust

it

between

the 200 2000 20k 200k 2000k points to see which one gives you a
satisfactory result.

For example, in this case, I chose the 20k scale, and I got 0.22 in the
display. 20k here means it’s able to measure up to 20kΩ and 0.22 means it’s
0.22 of 1kΩ:

70

Does that look confusing? Oh well, it’s not the best method anyway. I
would therefore recommend you get a multimeter
that can determine the scale automatically for you.

How to Measure Current

Now you know how to measure voltage and resistance.

Right? I showed you those first because they work in a similar way: the
connectors are put in parallel to the item we want to measure. We call that a
parallel connection.

However, measuring current is different. Here, we need to put the


multimeter in series, allowing current flow through it. It’s called series
connection.

Also, depending on the multimeter you’re using, you might need to modify
the entry point for the cable. In this instance, we’re measuring volts and Ω
using the input #4, but we’ll measure current using input #1 (and high
amounts of current through input #2):

71
To measure current let’s build a little circuit. In this circumstance, we’ll use
a potentiometer that lights a LED.

Now, use the two cables connect the LED cathode to the lead that closes the
circuit to GND.

72
NOTE: You don’t measure the current flowing through an

element by connecting the multimeter to its cables directly.

You have to make sure the multimeter is part of the circuit.

Here, the multimeter works like wire.

On the multimeter, you can Select the scale for measuring the current. Here,
we’ll set it to mA, but you can try switching to uA and measure it in
microamperes:

73
There you have 753uA, which are equal to 0.753mA.

Let’s see the same measurement using the small, yellow multimeter, in this
case we use the same port to measure small currents as the one we used for
voltage and resistance: And what do you get?

74

CHAPTER SEVEN: ITEMS OR TOOLS TO

BUY TO GET STARTED WITH ARDUINO

AND ELECTRONICS

Arduino is a wonderful project, and I very much recommend you to buy


original Arduino parts to maintain and sustain the project and the whole
network.

But when you’re starting out you need a lot of little components that when
you buy them individually might cost a lot. It’s possible to get kits that
come with many, many things at once.
Precisely, I would recommend a kit made by Elegoo. It’s available on
Amazon for $53.99 at the time of writing. The name is of the kit is called
ELEGOO UNO R3 Project Most Complete Starter Kit with Tutorial
Compatible with Arduino IDE (63 Items).

It’s a box containing an Arduino Uno rev 3 clone board, and several other
components, sensors and small parts you’ll find very useful:

76
77
It contains a lot of useful items: a breadboard, lots of wires, resistors, LEDs,
a battery, a shield, a power supply module, a joystick, a water level sensor,
an LCD screen, a keypad, buttons, a stepper motor and a servo motor, an IR
receiver and transmitter, a relay, an ultrasonic sensor, etc.

Another good one, though not as complete as the first, is the ELEGOO
UNO Project Super Starter Kit with

Tutorial and UNO R3 Compatible with Arduino IDE

78
www.electronic07.com

79
There are other similar kits out there that you can buy, but make sure the
board is an Arduino Uno, which is better to start with.

You also need to buy a multimeter. Any one will suffice. You can find one
to buy at your local tools store or on any place on the Internet.

That’s all you need to start with. You need to try first with cheap kit, then if
you like tinkering with electronics, it’s endless possibilities!

80

It’s cool to get a device that communicates with WiFi and Bluetooth like the
Arduino MKR Wifi 1010 and the Arduino
MKR GPS shield to work with GPS, for example.

81

CHAPTER EIGHT: ARDUINO PROJECT –

BLINK A LED

Recall, we learned a few things about Arduino in

Introduction to Arduino.

Now, we’re going to build the first Arduino project. We’ll turn a LED light
ON and OFF.

Also, you will learn how to create your first Arduino program, upload it to
the Arduino board via USB, and how

to write to a digital I/O pin.

It’s quite a simple project, but you’ll learn a lot of stuff about Arduino if it’s
your first time.

We’re going to use an Arduino Uno rev 3 clone board.

If you already have an Arduino board, you can still use it.

The most important thing to take note of is that the board should work at 5V
I/O pins.

Here’s the board:

82
We can power it with a USB-B port, or a battery (a 9V battery works
perfectly since the recommended input voltage is 7-12V):

We’ve got a set of power pins and analog I/O pins on one

side:

83
and another set of digital I/O pins on the other side:

Now let’s build a simple circuit that will light a LED. We use a 1kΩ
resistor, a yellow 5mm LED, and we connect it to - and + as usual:

84
We connect + and - to the power pins of the Arduino that serve 5V and
GND:

As you can observe, the LED turns on when we power the


Arduino with a battery:

85

Note that in this circuit, Arduino doesn’t do anything useful yet other than
scaling the 9V in the input provided by the battery to 5V.

Now let’s make the LED blink by writing our first Arduino program.

To do that, we have to first of all install the Arduino IDE on our computer.

Follow the simple steps below:

1.

Go

to https://www.arduino.cc/en/software and select your operating system


version and download:

86
2.

After downloading the software:

(i) On macOS: You need to move the Arduino app to your Applications
folder.

(ii) Check

the Windows and Linux installation instructions.

3.

Start the program and you should see a blank program:

87
NOTE: The setup() function is only executed once, just after the program
starts, and that’s where we commonly set up

the pin modes for example.

The loop() function is performed constantly in a loop, forever.

In our program we’ll take the following steps:


Firstly, set the digital I/O pin # 13 as an output pin:

88

#define LED_PIN 13

void setup() {

// Configure pin 13 as a digital output

pinMode(LED_PIN, OUTPUT);

Secondly, in loop() we tell our Arduino to write a HIGH

level of tension (5V)

Thirdly, we ask it to wait 1 second

Fourthly, we write a LOW level of tension (0V = ground)

Fifthly, we ask it to wait 1 second and then

Finally, we tell it to repeat forever:

void loop() {

digitalWrite(LED_PIN, HIGH);

delay(1000);

digitalWrite(LED_PIN, LOW);

delay(1000);

89
NOTE: HIGH and LOW are constants available by default in our Arduino
programs.

digitalWrite() is used to write a HIGH or LOW value to a particular digital


output pin. You’re going to pass the pin number and HIGH or LOW as
parameters.

delay() will pause the program for a particular number of milliseconds


stated as parameter.

You might have to choose the Arduino board on the Tools -

> Port menu the first time you start the program.

You have to be sure the Arduino is connected to the computer.

First of all, you need to save the file before you can compile the program
and write it on the Arduino. You’re free to save it anywhere you like. So
let’s create an Arduino folder in our Documents folder, and there store all
the Arduino programs we write.

Click the Upload button (the one with a right arrow in it) and the program
will be compiled and installed on the Arduino. The LED should start
blinking.

90

www.electronic07.com
Should you disconnect the USB cable from the computer, you will see the
LED will turn off because the Arduino is no longer powered.

However, if you connect the USB cable to a normal USB

charger, the LED will blink. The computer is no longer needed. The
Arduino will run the program we’ve loaded, just this program, it won’t run
anything else.
91

Once we have powered it, the program will automatically start and run.

92
CHAPTER NINE: THE ARDUINO BUILT-IN

LED
Arduino boards usually come along with a little utility: the built-in LED.

It is recognized by the letter L next to it. On the Arduino Uno, it is close to


the pin #13:

On the Arduino MKR 1010 WiFi it’s close to the 5V output

pin:

93

This LED is connected to the digital I/O pin #13 in majority of the boards.
In some other boards, like the Arduino MKR

series, it’s connected to the pin #6.

Regardless, you can also reference the precise pin using the LED_BUILTIN
constant, that is always correctly

mapped by the Arduino IDE to the correct pin, depending

on the board you are compiling for.

In order to light up the LED, you need to first of all set the pin to be an
output in setup():

pinMode(LED_BUILTIN, OUTPUT);

Then you can send it a HIGH signal:

digitalWrite(LED_BUILTIN, HIGH);

or
digitalWrite(LED_BUILTIN, 1);

94

Here’s is how a simple program that makes the built-in LED

blink every second look like:

void setup() {

pinMode(LED_BUILTIN, OUTPUT);

void loop() {

digitalWrite(LED_BUILTIN, HIGH);

delay(1000);

digitalWrite(LED_BUILTIN, LOW);

delay(1000);
}

95

CHAPTER TEN: BREADBOARD POWER

SUPPLY MODULE

Sometimes in my projects, I connect the circuit to a 9V

battery, because it’s very simple to start with and it’s quite easy to find.

But it’s not optimal. First because the battery does not last long as
commonly advertised.

A Breadboard Power Supply Module receives an input through a barrel


jack from a battery or a 12V adapter or any other source, and supplies to
our circuit a 5V or 3.3V tension, depending on our needs. Soon, we’ll
introduce Arduino into our circuits, and all our Arduino circuits are going to
work with those voltage levels.

There are many different ones available, but the one I’ll show you below is
part of the Elegoo kit, although there are those from other brands in this
same shape and

characteristics – any one will suffice. You can check for

“Arduino power supply” on Amazon to see some other alternatives:

96
97
The input voltage allowed is 6.5V - 9V DC. The maximum

output current is 700mA.

We connect it to the breadboard directly:

98
99
Then on each side, you can choose which tension you would apply to the
power lines in the breadboard, independently: 5V like in this case:

Or 3.3V, by shifting the position of the jumpers:


If you want to turn it off, simply position the jumpers in the middle:

100
From there, you can now connect to a 12V to 220V adapter

using the barrel jack input:

Press the gray button to turn it on. The LED will turn on as well:

101
The USB port you see there is not to power the power supply module. It’s
meant to power an USB Device if needed (like the Arduino, for example).

You also have other output pins on top that provide GND,

5V and 3.3V in case you need them:

102

www.electronic07.com
103
CHAPTER ELEVEN: THE ARDUINO

CREATE PLATFORM
This is a cloud editor that lets you write and compile code directly in your
browser.

You can find it at http://create.arduino.cc, it’s a really amazing tool.

Here, we shall explore the Web Editor.

With this, you don’t have to install anything on your computer to create
your Arduino programs, other than a 104

plugin to let it “see” the board connected to the computer.

Once you have that, everything automatically updates and

there’s no extra setup needed to get up to speed quickly with Arduino.

It’s absolutely free, with a substantial free stage. Being a cloud tool, it has
the advantage of providing automatic backups and cross-device usage, plus
it works on Windows, Mac and Linux.

It

also

lets

you

share

programs

on
Project

Hub https://create.arduino.cc/projecthub, (where you can share your


projects and see what other people create)!

After signing up, you are asked to install the plugin I mentioned earlier, and
once you run it, you’re good to go!

Then move on to https://create.arduino.cc/editor, and you will immediately


see a new sketch. That’s the name Arduino gives to programs:

105

Look there on top, and you’ll find it already recognized the Arduino
Uno

connected

to

the

USB

port

(the /dev/cu.usbmodem14301 line shows the USB port).

That’s because it automatically recognizes Arduino boards.

On the left hand, you have a sidebar.

The Examples menu lists a lot of pre-made examples with source code,
instructions and in some instances, you may have schematics and pictures
of the circuit:

106
You also have a handy “From libraries” tab on the same Examples menu
that lists examples that are provided by the Arduino libraries.

The Libraries menu lists the official Arduino libraries, in addition to lots of
community contributed ones.

107
One beautiful thing is that you can mark libraries as favorites and find them
very easily.

The next item you’ll see in the sidebar is the serial monitor, which helps to
debug and get information from your Arduino programs (as well as send
information to your board):

108
Next you have an inline help, which contains some tutorials, the preferences
and your usage quota of features like storage compilation time and the
number of projects.

You have a maximum of 100MB of storage, 100 sketches and

200s of compilation time per day, after which you can upgrade to a paid
plan for $6.99/month which also includes advanced IoT features.

109

CHAPTER TWELVE: HOW TO CONNECT

TO A WIFI NETWORK USING AN


ARDUINO

It really starts becoming interesting when you connect electronic devices


you build with Arduino to the network.

Let’s see how we can connect an Arduino to a WiFi network.

First, the Arduino must have WiFi connectivity, for example the Arduino
MKR WiFi 1010, (that’s the one I use) or the Arduino Uno WiFi Rev2 and
others.

We’re going to use the library WiFiNINA. This library is very handy. It lets
you connect to a WiFi network, and also create a WiFi network if you want.

Start your Arduino sketch using:

#include <SPI.h>

#include <WiFiNINA.h>

NOTE: The SPI library is used by the WiFiNINA library, so load it as well.
SPI stands for Serial Peripheral Interface

110

The WiFiNINA library gives us the right to use, plus other things, the WiFi
object that we’re going to use.

Now let’s work on the body of the setup() function. This is the only
Arduino core function we’re going to implement (we’ll leave loop() empty).

void setup() {

First of all, we’re going to define two strings to hold the network name, the
SSID, and the network password.

www.electronic07.com
Since we’re using Arduino Create, we’ll just use constants that we’ll fill
separately in the Secret tab:

char ssid[] = SECRET_SSID;

char pass[] = SECRET_PASS;

Next thing to do is to initialize the Serial interface to communicate


information from the Arduino back to

Arduino Create:

111

Serial.begin(9600);

And we wait until it’s ready using

while (!Serial);

After that, we put WiFi.begin() inside a loop that will check if its return
value is WL_CONNECTED, and keep retrying every 2 seconds until it is:

int status = WL_IDLE_STATUS;

while (status != WL_CONNECTED) {

Serial.print("Connecting to ");

Serial.println(ssid);

status = WiFi.begin(ssid, pass);

delay(2000);

We then initialize it to WL_IDLE_STATUS, another


constant of WiFiNINA, although we may also choose to initialize it to an
empty string.

112

Once we’ve ended this loop, we are connected and we can call the
WiFi.localIP() method to collect the device IP

address and print it to the serial:

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

Here’s the full program:

#include <SPI.h>

#include <WiFiNINA.h>

void setup() {

char ssid[] = SECRET_SSID;

char pass[] = SECRET_PASS;

Serial.begin(9600);

while (!Serial);

113

int status = WL_IDLE_STATUS;

while (status != WL_CONNECTED) {

Serial.print("Connecting to ");

Serial.println(ssid);
status = WiFi.begin(ssid, pass);

delay(5000);

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

void loop() {

114

Now we have access to other information, such as the network SSID with
WiFi.SSID() and the signal strength using WiFi.RSSI():

Serial.print("Signal strength in dBm: ");

Serial.print(WiFi.RSSI());

At this juncture we are connected and we can move on to

other tasks.

Note: There might be a NINA firmware upgrade available.

Just add this check to your program:

if

(WiFi.firmwareVersion()

<

WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Firmware upgrade available");

to confirm if that’s the case. If you’re sure, connect to the board using the
Arduino IDE and then load the example sketch File -> Examples ->
WiFiNINA -> Tools -> FirmwareUpdater

115

At that point, open the Tools -> WiFi101 / WiFiNINA Firmware Updater
menu:

116
and press the Update Firmware button:

117
118

CHAPTER THIRTEEN: HOW CAN YOU

RUN A WEB SERVER ON AN ARDUINO?

In this section, we’re going to learn how to start a Web Server on an


Arduino device with WiFi, Arduino MKR WiFi

1010, for example.

We’re going to connect to an existing WiFi network, and then, we’re going
to interact with the Arduino from our browser via HTTP.

This is very fascinating for a range of applications. From very simple check
of the sensors data, to performing some actions based on the HTTP request
performed.

Let’s begin from this program defined in the Connect to a

WiFi network using an Arduino lesson:

#include <SPI.h>

#include <WiFiNINA.h>
void setup() {

char ssid[] = SECRET_SSID;

char pass[] = SECRET_PASS;

119

Serial.begin(9600);

while (!Serial);

int status = WL_IDLE_STATUS;

while (status != WL_CONNECTED) {

Serial.print("Connecting to ");

Serial.println(ssid);

status = WiFi.begin(ssid, pass);

delay(5000);

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

void loop() {

120

Before you begin the setup(), add this line:


WiFiServer server(80);

to set a TCP server on port 80 and when you are done with the end of
setup() call

server.begin();

to start the server.

Note that this is a TCP server, not an HTTP server. However, HTTP (which
is a TCP/IP application protocol) is built on top of TCP (i.e. the transport
layer), Therefore, we can build the HTTP server on our own quite simply.

To do this, we first of all need to listen for client connections. We do so in


loop():

void loop() {

WiFiClient client = server.available();

121

if (client) {

The available() method of server attends to incoming clients.

Then inside the if (client) {} check, there is an HTTP client connected.


Then all we need to do is:

▪ call client.connected() to check if the data is

connected, and also, if there is data to read

▪ call client.available() to get the number of bytes available for reading (this
helps to ensure there is data to read)
▪ call client.read() to read one byte from the incoming

data (the HTTP request sent by the client)

▪ call client.println() or client.print() to send data to the client, thereby


building a proper HTTP response

▪ call client.stop() to end the connection

122

Then we can now start printing to the serial interface each character sent by
the client, and in the end we close the connection:

void loop() {

WiFiClient client = server.available();

if (client) {

while (client.connected()) {

if (client.available()) {

char c = client.read();

Serial.write(c);

client.stop();

123
Attempt to upload this program on the Arduino. Point your browser to the
IP address. You will see something like this (below) printed to the serial
interface. This is what is sent by the browser:

GET / HTTP/1.1

Host: 192.168.1.40

Upgrade-Insecure-Requests: 1

Accept:

text/html,application/xhtml+xml,application/xml;q=0.9,*/*

;q=0.8

The user-Agent: Write: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6)


AppleWebKit/605.1.15 (KHTML, like Gecko)

Version/14.0.2 Safari/605.1.15

Accept-Language: en-us

Accept-Encoding: gzip, deflate

Connection: keep-alive

Take note of the ending empty line. This is the end of the HTTP request.

124

We’ll need to intercept this empty line.

Every line in the HTTP request is ended by a CR carriage return character


(\r), and a LF line feed character (\n).

Therefore, the end of the request can be ascertained by 2 sets of those


sequences: \r\n\r\n.

www.electronic07.com
Thus, the simple algorithm is going to work, we just have to memorize 2
characters prior to the current one, and then check if we identify the
sequence \n\r\n (the last 3

characters in that sequence are enough to ascertain the last line):

void loop() {

WiFiClient client = server.available();

if (client) {

char prevprev;

char prev;

while (client.connected()) {

125

if (client.available()) {

char c = client.read();

Serial.write(c);

if (prevprev == '\n' && prev == '\r' && c == '\n') {

//we can send the response!

prevprev = prev;

prev = c;

}
client.stop();

126

So we can now send the response inside the if, we may use client.println()
for this, and we then add a simple response like thus:

HTTP/1.1 200 OK

Content-Type: text/html

Connection: close

<!DOCTYPE HTML>

<html>

test

</html>

In this way:

client.println("HTTP/1.1 200 OK");

client.println("Content-Type: text/html");

client.println("Connection: close");

client.println();

client.println("<!DOCTYPE HTML>");

127

client.println("<html>"); client.println("test");
client.println("</html>");

break;

The break; statement

is

going

to

end

the while

(client.connected()) {} block.

Take a look at the full program:

#include <SPI.h>

#include <WiFiNINA.h>

WiFiServer server(80);

void setup() {

char ssid[] = SECRET_SSID;

char pass[] = SECRET_PASS;

Serial.begin(9600);

128

while (!Serial);

int status = WL_IDLE_STATUS;


while (status != WL_CONNECTED) {

Serial.print("Connecting to ");

Serial.println(ssid);

status = WiFi.begin(ssid, pass);

delay(5000);

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

server.begin();

void loop() {

129

WiFiClient client = server.available(); if (client) {

char prevprev;

char prev;

while (client.connected()) {

if (client.available()) {

char c = client.read();

Serial.write(c);

if (prevprev == '\n' && prev == '\r' && c == '\n') {


client.println("HTTP/1.1 200 OK");

client.println("Content-Type: text/html");

client.println("Connection: close");

client.println();

130

client.println("<!DOCTYPE HTML>"); client.println("<html>");

client.println("test");

client.println("</html>");

break;

prevprev = prev;

prev = c;

client.stop();

Attempt this, you should see test showing up in the browser: 131

www.electronic07.com
The method works until you need to discover how, what the client asked us.

In that circumstance, you want to read each line, so this alternative method
works even better:

void loop() {

WiFiClient client = server.available();

if (client) {

String line = "";

132

while (client.connected()) {
if (client.available()) {

char c = client.read();

Serial.write(c);

if (c != '\n' && c != '\r') {

line += c;

if (c == '\n') {

if (line.length() == 0) {

client.println("HTTP/1.1 200 OK");

client.println("Content-Type: text/html");

client.println("Connection: close");

client.println();

client.println("<!DOCTYPE HTML>");

client.println("<html>");

133

client.println("test"); client.println("</html>");

break;

} else {

line = "";

}
}

client.stop();

In the last else we can check the line because the line is ended, and acts
accordingly to our requests.

134

CONCLUSION

Congratulations for coming this far! Now that we have successfully gone
through this course together, I believe you have acquired the basic
knowledge and skills in the field of electronics in general, and Arduino in
particular to make you that pro you’d like to be.

However, you need to constantly practice with other projects applying the
knowledge and skills you have acquired, as well as exploring other ways of
improving on what you have learned. Why? Because practice, they say,
makes perfect.

I wish you the best of luck in actualizing your dreams!

135

www.electronic07.com

You might also like