Arduino For Beginners
Arduino For Beginners
This book will act as a starting point for all you need to learn about Arduino
programming. We will provide links to all the software you may need to learn
Arduino programming.
This book will seek to teach all aspects of Arduino Programming to a complete
beginner with absolutely no experience writing programs. So, for those who fear
programming as head-cracking work, we will seek to dissuade you from such as
you read through this course.
Makerspaces the world over are increasingly interested in including electronics
and programming into their education. Integration of Arduino boards into their
lessons and projects is often the way they go about doing this. A lot of maker
educators often avoid Arduino because they fear programming is a difficult thing
to learn. We are here to prove them wrong.
For those more familiar with Arduino programming, there is still much you
could learn from reading this book. Each step in the programming steps will be
explained to carry everyone along.
This book will act as a starting point for all you will need to know about Arduino
programming. We will provide links to the software you may need to learn
Arduino programming.
Chapter 1: Diving into the World of Arduino
A Brief History
Ivrea is a small town that sits across the Dora Baltea River in Italia. Famous for
its underdog kings, one of which was King Arduin who was eventually deposed
by King Henry II, of Germany.
We take the name of the platform from Bar di Re Arduino, a bar popularly
frequented by Massimo Banzi. The bar’s name was inherited from the Italian
king of 1002, King Arduin.
Arduino was introduced by Massimo Banzi, David Mellis and David Cuartielles
in Italia in 2005 at the Interaction Design Institute Ivrea (IDII) to provide access
to a cheap and simple tool for creating hardware for non-engineers.
It was forked from the work of Hernando Barragán , a student at the IDII who
had created a language called Wiring for his master’s thesis. Wiring was
designed to simplify the creation of interactive electronics for artists and
designers.
What Is Arduino?
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.
Arduino Uno
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.
Because of its cheap price and ease of use, Arduino has become very popular for
makers that want to dabble in the creation of interactive hardware.
Unlike most previous programmable circuit boards, Arduino does not require
any extra hardware (Programmer) to load new code into the board.
You can buy Arduino directly from https://store.arduino.cc/ or from retail for a
price range of $22-$24.
The Board usually appears as a blue circuit board the size of a credit card
although varying models come in varying sizes. It comes with an Atmel
microcontroller which is a tiny computer, a USB connector, a power connector
and two rows of headers. The pins of the connectors are connected to the headers
which can be connected to virtually any electronics you can imagine.
There are usually 9 digital pins (I/O) and 4 analogue input channels. The I/O
pins can be used as input pins – to connect light sensors, temperature sensors,
sound sensors, keyboard or mouse, buttons… or they can be used as output pins
– to drive motors, control lights, connect displays, LED’s, check mail…The
USB also allows you to control your Arduino with your computer or control
your computer with the Arduino.
Arduino Leonardo
Arduino Leonardo is based on the ATmega32u. It has 20 digital I/O pins. It
contains everything you will need to support the microcontroller.
Arduino Ethernet
Arduino Ethernet is based on the ATmega328. It has 14 digital
Input/Output pins, six analog inputs and a 16 MHz crystal oscillator.
Arduino Due
Souped-up clock speed and ridiculous amounts of memory are the two things
that truly make the Due stand separate from the others.
Arduino Yun
Arduino Yun is the first of a new line of Wi-Fi products that seek to combine the
power Linux with the ease of use of Arduino. Arduino Yun is the combination of
an Arduino Leonardo (based on the Atmega32U4 processor) board with a Wi-Fi
system-ona-chip that runs Linino.
Arduino Mini
If you need to pack electronics into space not much larger than a postage stamp,
then the Arduino Mini is probably what you want.
And many other models
For this lesson, we will use the Arduino Uno model as a sample.
Arduino Clones
Some Arduino clones that you may also desire to purchase include:
NodeMCU
NodeMCU is one of a kind. It is one of the most favorite alternatives to Arduino
available right now. It has a similar size to the Arduino mini and Nano, but it
packs a meaner punch.
Teensy 3
Teensy is one of the best Arduino alternatives available right now. They are very
similar to Arduino micro and Nano, much like NodeMCU. And much like the
lauded Node, they are even better than the official Arduino versions. A little bit
more expensive at $30, its processing power surpasses almost every other
microprocessor.
MSP430 Launchpad
Power consumption often proves to be the problem of most DIY builds, this is
why the MSP430 boards are impressive. Drawing in current claimed to be three
times as low as most other Arduino boards, it is exactly what is needed for builds
meant to run for long periods.
There are many Arduino clone other types; The STM32, PocketBeagle, DIY
(Homemade)…
Caution!
Do not fry your Arduino!
It might be a good idea to read this chapter before you actually unpack your
Arduino, Bad things may happen if you do not.
1. An Arduino can only supply 40mA output per pin, so you may not
want to drive a speaker or motor directly and you cannot directly
connect a LED without a resistor.
2. Do not short an output at +5v, +3.3v or the ground pins. The amount
of current drawn from an output pin at +5v connected to the ground
will fry the board.
3. Do not put Arduino on a metal surface, it will short out the pins.
4. Do not draw more than 200mA from the total output pins altogether.
The ATmega chip supplies only 200mA total, so driving 10LED’s
will eventually kill your board.
5. Do not supply more than +5v to your input pins. Even a +0.5v excess
charge may damage your board. This also applies to sensors… always
check your voltages carefully before connecting anything.
6. Do not supply more than the accepted voltage to the input pins. A +5v
ATmega chip has an absolute limit of +6v and +5v for a +3.3v one.
7. The vin chip will fry if it takes in more than +12v. There is an
onboard voltage regulator that will fry if it takes more than +12v.
8. When running on external power, do not draw more than 500mA
from the +5v pin.
9. Do not draw more than 50mA from the +3.3v pin.
10. Be careful of reverse polarity. Swapping in a GND pin for the
vin or +5v pin will kill the board.
11. Do not connect a load to the vin pin while you are using USB
power.
12. Remove the carpet under your work desk to protect against
static charge.
If this seems needlessly complicated, but do not worry. Just pay special attention
to 1-5 and 10 and you will be fine.
Chapter 2: Hardware and Tools
For you to begin practicing with Arduino, you will probably need a few things to
get started with.
While you can learn Arduino programming with only the contents of your
Arduino Uno Budget Pack, please do make sure you have all the materials listed
below within the pack:
Power Supply
Arduino rarely comes with a power pack. For most projects, you will use the
USB cable to draw power from your computer. However, for any mobile project,
you will need to consider a 9V AC power supply to make it independent.
The Breadboard
The breadboard is a revolutionary design when it comes to programming a
board. Before its invention, it was necessary for an engineer to perfect his entire
board design on paper before doing any form of prototyping, or spend ruinous
amounts of money soldering and unsoldering the board (the board may get
damaged). The breadboard eliminated that limitation entirely by allowing its
users to program their circuits without permanently soldering anything until they
have perfected their designs.
A breadboard allows the user to prototype and experiment with different circuit
designs before doing any permanent soldering of the board.
The breadboard contains metal clips in the holes on their plastic housing which
are connected to each other by thin strips of conductive materials. These allow
currents to flow freely between one hole to the next, mimicking a circuit.
However, since the breadboard on its own is not self-powered, it requires power
to be sent through jumper wires from the Arduino. These wires are also
sometimes used to form circuits by connecting switches, resistors and other
components.
The jump cables are connected to the breadboard through two power rails clearly
visible on it, for both power and ground connections. The rail in between the
breadboard is to enable circuits to be more easily mounted on it.
Jump Wires
Jumper wires serve the very simple function of connecting your Arduino header
pins to the breadboard. As already stated above, using these to test-drive your
circuit allows you to see if your circuit is accurate without having to solder
Arduino. You will need jumper wires, if you want to use the breadboard.
Multimeter
A multimeter is a very vital part of working with electronics. It is a combination
of a voltmeter (measures voltage {AC and DC}), an ohmmeter (measures
resistance) and an ammeter (measures current). Because of the precision
required when working with Arduino, it becomes almost vital if you are to work
required when working with Arduino, it becomes almost vital if you are to work
on the board without blowing out your board at the first attempt. It will solve a
lot of the Mathematical issues you will face when learning Arduino
Working on Arduino without a multimeter is possible. But it is not advised if
you are not already proficient in working with other electronics with tight
tolerance ranges.
Diode
Diodes are like transistors, a semiconductor device. One of the many interesting
properties of the diode is that they conduct electrons only in one direction.
Arduino boards have a diode in series (directly connected one after the other)
with their power input jack to prevent you from reversing the power, which will
damage the chip.
Diodes are generally built with a forward voltage drop that ranges from 0.5v to
0.7v. If you measure the voltage before the diode and after the diode, the voltage
will be 600mV higher before the diode as compared to after it.
This, of course, has its limits, if the reverse voltage surpasses the diodes limit,
This, of course, has its limits, if the reverse voltage surpasses the diodes limit,
the diode will break, which will cause current to flow freely in the wrong
direction. In some diodes called zener diodes, this will be controlled. Zener
diodes only conduct current if the voltage exceeds a certain value.
This value is specific and constant, so zener diodes can act as a reference in
voltage regulators.
LED
The LED is much like a diode, this means that it will connect electricity only in
one direction. This is an internal limitation deliberately built into its function.
LEDs have both a cathode (negative) and an anode (positive).
The cathode is usually the flat and shorter leg side, while the anode often acts as
the round and longer leg.
LEDs often come in various color, Red, Green Orange, Blue… and with various
forward voltages often written as VL (This will become significant later on).
Since they emit low energy light, their voltage drop is much lower than light
sources that emit UV, Blue… light.
Color Forward voltage (V L )
Red 1.7v - 2.2v
Orange 2.0v
Yellow 2.1v
Green 2.2v
Blue 3.2v - 3.8v
White 3.2v - 3.8v
This is an assumption that may not always be true for LED forward voltages.
Always confirm what your LED’s forward voltage is before using it.
The Capacitor
A capacitor is a small electronic component that stores electric charges for a
circuit. Capacitors are used in Arduino to give the programmer more control
circuit. Capacitors are used in Arduino to give the programmer more control
over how power flows in the circuit.
Since, the capacitor is capable of storing electronic charge in an electric field, by
using them within the circuit, you can generate analogue voltages under the
program’s control with a simple “analogWrite(){” function.
Capacitors, like resistors, are by themselves useless as a part of the circuit. They
are often referred to as passive components. However, when combined with
other circuit components, they become immensely useful.
The capacitor also provides protection from overfiring relays.
What the above commands do is: opens the Downloads folder, then unzip the
downloaded file, it then moves the unzipped file to “/opt/” folder, and finally, it
will run the install script.
The install script will then create a desktop file, and a MIME type file will also
be created to associate “.ino” files with the IDE. Finally, add “a = append” user
to the 'dialout' group (-G). This will allow the IDE to access the serial ports.
Upon opening the IDE, you will notice the greyed out “Tools > Port”. Upon
successfully adding your chosen ‘dailout’ group to the IDE, the option will
become enabled. You will have to close the IDE and reopen it for this to happen.
Or you can look at the installation steps as provided here:
(https://tutorials.ubuntu.com/tutorial/install-the-arduino-ide#0 ).
Arduino IDE + Teensyduino:
You will need the Teensyduino add-on for the Arduino IDE if you have a
Teensy board. A comprehensive installation guide can be found here
https://www.pjrc.com/teensy/td_download.html/ .
Teensyduino does not support the latest versions (1.6.10 & 1.6.11) of the
Arduino IDE, for now, so you will have to download this version (1.6.9).
You may come across an error while installing Arduino: If this is the case, try
running the command
sudo chmod +x /opt/arduino-1.6.6/install.sh
This adds (+) the permission to be executed (x).
Then from the above installation steps for ubuntu, try running: /opt/arduino-
1.6.6/install.sh again.
Chapter 3: Working with Arduino
Sketch
On Arduino, A sketch is just another name used to describe what might be a
code when working with anything else, not Arduino. The sketch tells the board
how to behave, and what functions it needs to perform.
Using a Resistor
As you really get into Arduino programming, it gets more complicated. To be
honest, making what passes for a small bulb blink is not something really
impressive. That’s why you will learn how to add a resistor here.
Continuing
The resistor can be connected to either the anode or cathode of the LED without
affecting the circuit, as long as it is in series with the LED.
You will now need to connect a red jumper cable from pin labelled as
5v to the positive horizontal rail on the breadboard.
Similarly, a blue cable will be used to connect from a pin labelled
ground to the negative breadboard horizontal rail. This is a
configuration you will use again and again for Arduino work.
Your next step is to plug a yellow pin into pin 13 and the other end
should be plugged in any of the labelled 10 rows on the breadboard
(c10).
You will next need to connect another blue wire from your negative
ground rail to any other row on the breadboard (c18).
The next step is now for you to plug your resistor into row d18 (the
row next to the one you chose above), with the other leg plugged just
under your yellow cable in c11.
Finally, you will need to connect your LED’s cathode to the resistor
at d11 and connect the Anode to the yellow wire at d10.
Uploading your new program will light up your LED again. The
current runs through the resistor, into your LED and back into the
Arduino in a loop with a delay value (????).
Arduino sketch examples in your Arduino IDE are a great way to learn
Arduino programming. Just load the examples, and compare it to your own
code (debugging) to fix any problems that may come up.
code (debugging) to fix any problems that may come up.
Note: You may need to trim the legs of your resistor in order to reduce the
chances of any open leg coming in contact with other wires and shorting the
board.
More LEDs
This is something very easily done with Arduino and a small breadboard. This
will be done similarly to what was done with the resistor, but a little differently.
Connect the two pair of rails on the breadboard together using jumper
cables. (positive to positive and negative to negative). The widely
used method is using a red cable for the positive rail and a blue cable
for the negative rail. This makes it easy to distinguish which is which
without retracing your steps. It allows power to flow to both sides of
the breadboard.
The next step is similar to what you did in the one LED example
(connect the 5V pin to the bottom of the first positive rail using the
red wire, connect the ground pin to the bottom of the first negative
rail using the blue cord. Connect pin 13 with the yellow cable as
shown before). Repeat the rest of the first tutorial to add the other
blue cable, resistor and LED.
We start adding more LEDs by connecting a resistor from the ground
(the other negative rail) to h12, and a LED with the shorter end
(negative) at g12 (same row as a resistor) and the longer one
(positive) at g11.
Add the remaining LEDs with the same pattern as the first slowly
going down.
Now you are to change the position of the yellow wire on pin 13 to
pin 6 and add another yellow connecting from pin 5 to f11 on the
breadboard.
Do the same for the remaining pins, slowly going from pin 4 – 3.
Congratulations, you are finished with your Arduino board. Now it’s
time to code.
Coding
The first step to coding is to perform certain declarations you may need to use in
the rest of your code.
You can start by declaring “int timer = 200;” , this tells the compiler
that an integer called “timer” should have a value of “200” .
Declare the “void setup() {” , then unlike before within the “{”, you
will declare;
What this means is that the setup will configure the pins 3 to 7 as
output, as the code had declared that “let “thisPin” be 3, let
“thisPin” be < 8, let “thisPin” be all values (integers) greater or
equal to 3 but less than 8, now set “thisPin” as output.
This short piece of code together with the set the code into a changing
mini loop. Each time the loop repeats, the value of “thisPin” is
increased by 1. Thus, by the next loop instead of 3, the value of
“thisPin” will now be set to 4. This will repeat itself over and over
again until the loop is complete.
To continue with the rest of the code, you will now need to set the
digitalwrite(thisPin, HIGH);” together with the rest of the blink
code. If you followed the blink example, then you already know what
that does.
There is an inclusion though. Since the “void loop(){”s “for”
declaration changes value, you will need to declare
Since we don’t want to have the LEDs turn on one after the other
before turning off, we will include “digitalwrite(thisPin, LOW);”
after declaring the “delay(timer)” . This makes the LED turn off
after the delay.
However, since the value of “thisPin” changes as the loop repeats,
the LED changes as the light flashes. This causes the LEDs to flash
one after the other in a smooth row, from the one connected to pin 3
to the one connected to pin 7.
This is a simple method of connecting multiple LEDs and an example
of how to code such a thing. We will explain more as we cover more
topics.
Note: this code can also be done by writing it as:
Note: this code can also be done by writing it as:
for (int thisPin = 7; thisPin >= 3; thisPin- -) {
pinMode(thisPin, OUTPUT);
} .
This does exactly what the above code does, but instead of increasing the value
of “thisPin” as the mini-loop runs, it decreases it till it gets to 3, before starting
again. “>=” means greater or equal to (the value will include the integer),
“<=” means lower than or equal to (the value will include the integer), “<”
means less than ( the value does not include the integer), “>” means greater
than (the value does not include the integer).
Optimizing
The above code is an example of optimized code. It does everything you need it
to do while requiring only the shortest amount of code.
Optimization in coding is the process of reducing the code to the bare minimum
required for it to carry out the exact function needed. An optimized code is one
containing no extra words that can be done in another way to make it a shorter
code.
There are many ways to write code. The blink code for multiple LEDs, as shown
above, could be written in a different way. Another way to write this code is:
void setup() {
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop() {
for (int thisPin = 3; thisPin < 8; thisPin++) {
digitalWrite(thisPin, HIGH);
delay(timer);
digitalWrite(thisPin, LOW);
}
}
This does exactly what the above code does. However, it is almost twice as long.
This is an unoptimized code.
The mark of a good programmer is the ability to write a code in the shortest
amount of words possible without affecting its action.
Another advantage of optimized codes is that they run faster than normal code
since the computer reads all the declarations faster. This might have no effect on
the speed of the light coming on, but as the code gets larger, the effect slowly
compounds and the code runs slower.
Chapter 4: Exploring Arduino
Connect the LED again much like when you practised the blink
example, but change the pin position of the yellow cable to pin 9
from pin 13. Everything else will be the same. Connect you Arduino
back into the system and make sure your port is selected correctly.
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}
Upload your code and restart your Arduino. The LED will start
fading in and out.
Like we mentioned earlier, this is in truth a manipulation of how the Arduino
interprets the code. Arduino can normally only generate digital signals.
Button
Connecting a button to Arduino is not very difficult. It is different from what
you have been doing so far because instead of just doing output code, for the
Arduino to function, you will need to do input. The Arduino will read the input
from the Button and interpret what to do based on the code you uploaded.
Much like you did with your first Arduino, connect the blue and red
cables to the power rails of your breadboard. Then connect the yellow
cable to pin 13 and d6.
Connect both rail sides of your breadboard together, connecting two
positive sides together and two negative sides together.
Connect your resistor to the negative rail (we are not using another
cable to connect to the breadboard) and to d5.
Connect your LED to e5 and e6 using what you have learned so far.
Another Yellow wire will be used to connect pin 2 to b18 and a
resistor will lie between a18 and a positive breadboard rail.
Finally, the button should lie between e16-e18 depending on your
button type and f16-f18. Then g16 will be connected to the negative
power rail on the other side as illustrated above.
Now that you have to code what your board looks like into your IDE
const int buttonPin = 2; // declaration of “buttonPin” {it is connected to pin
2} to represent the value 2:
const int ledPin = 13; // declaration of “ledPin” to represent the value 13:
int buttonState = 0; // declaration of “buttonState” to represent the value 0:
void setup() {
pinMode(ledPin, OUTPUT); // declares the LED as an output:
pinMode(buttonPin, INPUT); // declares the pushbutton as an input:
}
void loop() {
buttonState = digitalRead(buttonPin); // reads the state of the
pushbutton:
if (buttonState == LOW) // checks if pushbutton is currently pressed:
{
digitalWrite(ledPin, HIGH); // The LED turns on:
}
else // if the pushbutton is not pressed”:
{
digitalWrite(ledPin, LOW); // The LED turns off:
}
}
The interpretation for this code is fairly obvious. The Arduino reads the code
top-down, so if the button is pressed (current flows through the button, thus, it is
called HIGH), the LED turns on. If it is not pressed (no current flows through
the button, thus, it is called LOW), the LED goes off. This is the function of the
attributes “if” and “else” .
Temperature Sensor
A temperature sensor does as its name implies; it senses changes in temperature.
A popular basic program is to connect a temperature sensor to an LCD and
Arduino to make it display the current temperature. Most large appliances use it
to monitor their own internal temperature changes to prevent damaging rises in
temperature.
Photoresistor
This is basically a light-dependent resistor. Its resistance varies with the intensity
of the light to which it is exposed. This is used as a sensor to build equipment
that only works when there is light, or that shuts down when there is light, like a
light-sensitive coffeemaker.
light-sensitive coffeemaker.
Sound Sensor
This has proven to be very popular with makers of voice changers. The sensor is
capable of detecting changes in the surrounding sound, and it interprets these
changes as data. It usually has adjustable sensitivity.
Knock Sensor
This is used to build knock sensitive locks. They detect the sound of a knock.
For most builds, they are connected to LEDs that turn on when the sensor detects
someone knocking.
There are many other sensor types available, and we cannot list them all.
Pulse-Width Modulation
Pulse-Width Modulation is a type of digital signaling that has proven incredibly
useful to programmers everywhere. It is used by engineers and circuit designers
to create circuitry with sophisticated controls.
It is very common and useful to people who work with Arduino.
PWM allows the programmer to change how long Arduino pin spends at HIGH
in analog at a consistent interval.
PWM is used by Arduino programmers to effect fine control over circuit
components that cannot normally perform at such fine levels. It is especially
popular for controlling the brightness of display units (RGB LED, LCD…), fine-
tuning the grip of a robot arms, etc.
The term duty cycle is generally used to describe this difference in the amount of
time a signal is high compared to when it is low. This is calculated in
percentages. The “on-time” describes when the signal is high.
Thus, if a signal (5V) has a duty cycle of 50%, you are getting only 2.5V of
electricity in reality.
Apart from dimming LEDs, this is also used to the reduce power consumption of
Arduino by altering digitally how much current is supplied without actually
touching the board.
Switches
A switch is a mechanical device that is capable of either breaking a circuit or
connecting it. It is just one small pushbutton in a completed board. However, its
importance is not depicted by its small size. Any Arduino board that was built
importance is not depicted by its small size. Any Arduino board that was built
for use must have a switch, this is to give a degree of control to the user,
allowing him/her to control whether the device should be currently working or
not.
A Sensor Sketch
This will be an example using an actual sensor. We will be demonstrating this
using a potentiometer. The attempt is to build Arduino that is capable of sensing
sound waves.
An ultrasonic sensor emits sound at a frequency of 40,000HZ. This sound
bounces back to the sensor, which records the time as data. The sensor interprets
the data using the relationship between time and velocity.
VCC, Echo, Ground and Trig are the four pins that can be found in an HC-SR04
Ultrasonic module. To make Arduino that can sense distance, we connect the
shields VCC pin to the 5V pin on Arduino, the Ground pin connects to the other
Ground pin, while the Trig and Echo pins connect to pin 9 and 10 on the
Arduino.
The code will be found here. The comments within the code explain what the
various code sections do.
https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
The distance is calculated by multiplying the duration by 0.034 and dividing the
result by 2. This is a fairly simple example of a sensor sketch.
You can freely experiment by using different sensor types.
Arduino Logic
void setup( ){
statements-1;
.
.
.
statement-n;
}
void loop ( ){
statement-1;
.
.
.
.
statement-n;
}
The above is a simple example of what an Arduino code should look like. Most
Arduino codes will follow this simple basic design. There are two blocks to
Arduino programming, the Preparation and the Execution. Each block is
always enclosed in curly braces. The setup (), is the preparation block. Loop () is
the execution block, and everything contained within it is what the Arduino
reads to determine its function.
The setup function starts serial communication. It is where you declare whether
your pin is to be output or input as we had explained above. Once setup has been
declared the board starts reading pin numbers and setting them as input/output.
void setup ( )
{
pinMode (pin-number, OUTPUT); // this will set the ‘pin-number’ as
an output
pinMode (pin-number, INPUT); // this will set the ‘pin-number’ as
an input
}
The codes in-between the loop are executed continuously. The code runs from
the beginning of the curly bracket to the end of it, before returning to the
beginning to start again, until the Arduino is switched off.
Void loop ( ){
digitalWrite (pin-number,HIGH); // this will turn ON the component
connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
digitalWrite (pin-number, LOW); // this will turn OFF the component
connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
}
}
Declaration sometimes comes before the setup, but it is always read as part of
the setup. These usually take the form of the int attribute, which means integer.
They are used to change certain functions about how the code is interpreted once
it starts executing.
All statements in a code ends with a semicolon.
int led = 9;
int brightness = 0;
int fade = 3;
void setup( ){
}
There are literarily thousands of Arduino syntaxes out there. It is impossible for
us to go through them all. We will examine some, however.
Variables
Constants
Floating Point Constants: This variable is similar to integer constants. They
are used to make code readable. They allow the use of scientific variables like e
and E.
Integer Constants: This variable consists of numbers. They are automatically
treated as base 10 but can be modified with modifiers like; 10 (decimal), 2
(binary), 8 octal.
HIGH | LOW: These variables specify the two values of a pin (HIGH/LOW).
For Input : HIGH is reported when the voltage at the pin is greater than 3.0V for
5V boards and 2.0V for 3.3V boards OR for Output : HIGH is reported at 5V
for 5V boards and 3.3V for 3.3V boards.
For Input : LOW is reported when the voltage is at 1.5V for 5V boards and 1.0V
for 3.3V boards OR for Output : LOW is reported as 0V for both 5V and 3.3V
boards.
INPUT | OUTPUT | INPUT_PULLUP: This function changes the electrical
behaviour of a pin with “pinMode()” . Pins configured as INPUT; make
extremely small demands on the circuit they are on. For INPUT_PULLUP;
This is the same as input, but instead of external resistors being used to reduce
voltage demands, the circuit will use its own internal pull-up resistor. For
OUTPUT; This makes the pin into power demanding conductors on the circuit,
allowing the board’s full voltage to flow into them.
LED_BUILTIN ; This variable stipulates the pin to which the on-board LED is
connected to. This is usually pin 13.
true | false ; These are Boolean constants. False is defined as 0 and true is
defined as 1. Any integer that is non-zero is true, but true is often used to
represent a true statement. It is typed in lower case, unlike the other variables.
Data Types
Variable datatypes that exceed their maximum or minimum capacity are said to
overflow . This causes unpredictable results. To avoid this problem, some
programmers use unsigned datatypes like “unsigned int, unsigned long,
unsigned char ”.
String(val); String(val, base); String(val, decimalPlaces); This constructs an
instance of the string class. It will return a single instance of the string class. It
allows multiple data types.
array ; This is variables in a collection that can be accessed with an index
number. Examples are;
int my[6];
int myT[] = {2,4,6,8};
int myTs[6] = {2,4,-8,3,
Char message[6] = “hello”;
All the above methods are valid for the declaration of an array.
Arrays are accessed by declaring;
myT[0] == 2, myT[4] ==8,…
This means that the last declarable index for an array is “n-1”. C++ does not
check if the array you declared is legal or not. Be careful not to exceed the
number of arrays you declared if you do not want errors.
bool: This holds one of two values (true/false).
boolean: This is a non-standard term for bool in Arduino
byte: This stores an 8-bit unasigned number. It is from 0-255.
char: This is used to store character values. Only use this datatype to store
characters. It occupies 8 bytes
double: It is implemented like float and occupies 4 bytes. It is a double-
precision floating number.
float : This is a datatype for numbers with decimal points. It is popularly used to
approximate analog and continuous values due to their greater resolution as
compared to integers.
Float should be avoided in mathematical calculations because they can only
contain 6-7 characters, their absolute values are different and they run slower
when compared to integer math. Float will be treated as integer unless you add a
decimal point.
int: These are the primary datatype. It is a number storage and stores a 2-byte (2
bit) value. They store negative numbers by “2’s complement math” and the
highest bit is called the “sign” bit.
long: these are variables that store 4-byte (32 bit), they are extended size
variables for number storage. L is added to at least a number when doing real
math with integers.
short: This datatype is 16 bit.
string: There are multiple versions string constructs but they can all be
represented in two ways. A string can be made out of a datatype or from an array
(made from type char) and simply null-terminate it. Examples for the first type
will be described in function . Strings are normally automatically terminated
with a null character “ASCII code 0”. This allows the function “serialPrintln() ”
and others like it to tell where a string ends and terminate it there. Strings have
one more character than the text it contains.
char str1[15];
char Str1[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’};
char str7[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘\g’};
char str8[] = “Arduino”;
char str9[8] = “Arduino”;
char str5[15] = “Arduino”;
All the above strings are correct and will run without error.
Note: Strings are always defined in a double quote (“bvc”) while characters are
in a single quote (‘fds’).
void: This is used only for function declarations. They signify that the function
is not to return any information to the function it was called from.
word: This datatype stores unsigned number of 16 bits (2-byte).
Structures
Structures
Sketch
setup(): This is what is called to start a sketch. It is used to initialize variables,
pinModes… It runs only once.
loop(): This does exactly what its name says. It runs after setup and does so
forever and without end. It is what actively controls the board.
Arithmetic Operators
% (remainder) : This calculates the remainder after an arithmetic division
operation. It does not work on floats and is useful in keeping variables within
range. If its first value is negative, the result will be negative.
* (multiplication) : This operator multiplies two values together. It often causes
an overflow because it is easy for the result to exceed the datatype in this type of
operation.
Should any of its datatype be float or double, floating point math will be used to
obtain the result.
+ (addition) :
- (subtraction) : This operator finds the difference between two datatypes. It can
easily overflow should the result be smaller than the datatypes range. Much like
with multiplication, floating point math is used should one of the data be of type
float or double.
/ (division) : This operates on two datatypes to produce a division of the lower
data from the upper data. Float point math will also be used for the result if one
of the datatype is floator double.
= (assignment operator) : This tells the microcontroller to evaluate the variable
or datatype on the right of the assignment operator and store said data on the left.
Control Structures
break : This is a structure used to exit conditional statements. It can also be used
to exit a switch case. The break statement bypasses the normal loop condition.
continue : This structure skips the rest of the loops current iteration. It is a
conditional statement containing conditions like (for, while…). The Arduino
checks the condition and proceeds if said condition is met.
do...while : This does the same thing as the while structure, but it will run after
the loop, thus, making the loop run at least once even if it does not meet the
required condition.
else : This allows for the grouping of multiple tests. It will only be executed if
the “if” statement result yields “false”. The tests will carry on until it yields
“true”. If none of the conditions report “true”, the default operation is carried
out. It is normally used with the “if” statement, to grant a bit more control to the
statement.
for : This statement repeats a block of statements. It uses an increment counter
to terminate the loop. It is useful for any repetitive operation and often appears
with arrays operating on collections of data.
goto : This will transfer the program flow to a specified point in the program. It
allows the Arduino to skip certain codes. It lets the programmer place his code
without having to worry about where it is.
if : This structure is used to check for a condition and the proceeding statement
will be executed if the condition is “true”.
return : This is used to terminate a function and return the value of that function
should it be called.
while : This is used to loop a statement infinitely until the statement condition
eventually proves “false”. It only applies to test variables that changes while the
code is running.
Boolean Operators
! (logical not) : This reports as “true” only if the operator is “false” and “false”
only if the operator is “true”
&& (logical and) : This is a logic operator that reports “true” only if both
conditions are “true”.
|| (logical or) : This reports as “true” if even one of the 2 operator is “true”.
Comparison Operators
!= (not equal to) : It compares variables from both sides and reports “true” if
they are not the same, otherwise it reports “false”. You should only compare
variables of the same datatype, otherwise you may get unpredictable results.
Negative numbers are less than positive ones.
< (less than) : This compares variables on both sides of the operator. It will
return “true” if the operator on the left is less than that on the right. Negative
numbers are less than positive ones. You should only compare variables of the
same datatype, otherwise you may get unpredictable results.
<= (less than or equal to) : This compares variables on both sides of the
operator. It will return “true” if the operator on the left is less than or equal to
that on the right. Negative numbers are less than positive ones. You should only
compare variables of the same datatype, otherwise you may get unpredictable
results.
== (equal to) : It compares variables from both sides and reports “true” if they
are the same, otherwise it reports “false”. You should only compare variables of
the same datatype, otherwise you may get unpredictable results. Negative
numbers are less than positive ones.
> (greater than) : This compares variables on both sides of the operator. It will
return “true” if the operator on the left is greater than that on the right. Positive
numbers are greater than negative ones. You should only compare variables of
the same datatype, otherwise you may get unpredictable results.
>= (greater than or equal to) : This compares variables on both sides of the
operator. It will return “true” if the operator on the left is greater or equal to the
operator to the right. Positive numbers are greater than negative ones. You
should only compare variables of the same datatype, otherwise you may get
unpredictable results.
For further reading on the types of functions and syntaxes in Arduino, please
visit (http://arduino.cc/en/Reference/HomePage/ ). This is an Arduino reference
page that lists all the different types of functions for controlling the Arduino
board. Use this to code when coming up with your own projects that may not
have functions already listed in this book.
Functions
Functions in Arduino represent a modular series of code that performs a defined
task and then returns to the area of code from which the function was called. It is
like writing a mathematical equation in the code. For programmers
accomplished in the use of BASIC, functions allow the utility of subroutines.
Functions codify one action in a single place so that, the code only has to be
perfected once. This allows you to debug a single code and use that function an
unlimited amount of times without having to worry about errors.
Functions also influence your coding by making it modular. This makes the
program more readable and gives the programmer significant freedom in time
program more readable and gives the programmer significant freedom in time
when coding, since a large part of the code would have been done as functions in
a previous work.
There are two required functions for Arduino to work, “setup()” and “loop()” .
All other functions must be created outside the curly brackets of these two
functions.
Examples:
int myMultiplyFunction(int x, int y) {
int result;
result = x * y;
return result;
}
The above code is a function. It allows for the multiplication of two integers “x”
and “y” and save the result into memory. We declared “myMultiplyFunction”
to be an integer containing two values “x” and “y” . Then, within the
declaration, we declare another integer “result” . By giving result a value of “x
* y” (a multiplication of “x” and “y”), the function is to return the result of that
multiplication and assign it to whatever contains the “myMultiplyFunction” .
To use the function, we can do this:
Voidloop() {
int h = 2;
int g = 3;
int z;
z = myMultiplyFunction(h, g);
serial.print(z);
delay(3);
}
In the above code, we use the function we had declared by equating “z” to be
“myMultiplyFunction” , this mean that the values of “g” and “h” will
substitute for “x” and “y” in the above declared function and return “z as 6” .
The remaining code does serial print for the Arduino so that we can physically
observe the result.
The “myMultiply function can be declared above or below the rest of the code.
The “myMultiply function can be declared above or below the rest of the code.
While it is preferable to declare a function before you use the function, it is not a
rule.
A complete code will look like this:
int myMultiplyFunction(int x, int y){
int result;
result = x * y;
return result;
}
void setup(){
Serial.begin(9600);
}
void loop() {
int g = 2;
int h = 3;
int z;
k = myMultiplyFunction(g, h);
Serial.print(z);
delay(500);
}
Do not leave spaces in the declaration of names within your function. Arduino
will only accept 0-9, A-Z and the underscore (_), a function is not allowed to
start with a number.
A functions body must be contained within braces as we have seen with the
“voidloop(){” and “void setup(){” examples. The type of function is declared
first (int, void, const). The name of the function usually follows
(myMultiplyFunction, setup, loop). After this is to be the body of the function
contained within curly braces.
Within a functions body, a return type must always be present, even if it is void
like in “void loop” . The function must be called within the “void setup()” body,
by either simply declaring the name as in the above example or for those that are
not integers;
void DashedLine() {
serial.println( “----------” );
}
}
void loop() {
}
void setup() {
serial.begin(9600);
DashedLine();
}
As you will notice the function is called without any preceding “int” call. This is
because so far, we had been dealing with integers (numbers), but because the
new function is simply letters, we can call on it without preceding it with any
data type.
Note: we used “serial.println” and “serial.print” , both attributes do the same
thing, with the exemption that “serial.println” does this on a new line while
“serial.print” does it on the same line.
There are many different functions out there, we will list a few.
Digital I/O
digitalRead(pin, value) : This function reads the value of a specified digital pin
(HIGH/LOW).
digitalWrite(pin, value) : This function writes a value (HIGH/LOW) to a
digital pin.
pinMode(pin, mode) : This function configures the specified pin to behave as
either input or output.
Analog I/O
analogRead(pin) : This function reads the value from the specified analog pin.
analogReference(type) : This function configures the reference voltage for
analog input (DEFAULT/INTERNAL/EXTERNAL/INTERNAL1V1…)
analogWrite(pin, value) : This function writes an analog value to the specific
pin (PWM pins).
Math
abs(x) : This calculates the absolute value of a number. It returns +x if >= 0 and
-x if < 0.
constrain(x, a, b) : This function constrains a number within range. X will be
the constrained number (all data types), a is the lower end of the range (all data
types) and b will be the upper range (all data types). It will return x - if within
range, a – if less than a and b – if greater than b.
map(value, fromLow, fromHigh, toLow, toHigh) : This re-maps a number
from one range to another. It returns the mapped value
max(x, y) : This calculates the maxima of two numbers. It returns the larger of
the two numbers
min(x, y) : This calculates the minimum of two numbers. It will return the
smaller of the numbers.
pow(base, exponent) : It calculates the value of a number raised to a power.
Used to generate curves… It returns the exponent result. The data type for
exponent is float, for base is float and for return is double.
sq(x) : This will calculate the square root of a number. It returns the number’s
square root as data type double.
sqrt(x) : This calculates the square of a number. The datatype of the return is
double.
Random Numbers
random(min, max) ; or random(max) : This will generate pseudo random
numbers. It will return a number between min and max-1 with datatype long.
randomSeed(seed) : It initializes pseudo random number generator. The seed
data type is usually unsigned long.
Circuit Diagrams
We discussed resistors and voltages earlier. There is a lot more to learn if you
are to become proficient in Arduino.
A simple electric circuit, as can be seen, has a battery (supplies power), a resistor
(controls the current) and a LED (lights up to signify the circuit is on. More
components can be easily added to this circuit, like more resistors, LED, a
capacitor, a potentiometer, a switch…
The load of a circuit is the total amount of power all the components of the
circuit will need to function. If the power supplied to the circuit is smaller its
load, the circuit will not work (or will work slowly/weakly).
Arduino circuit diagrams looks a little different however.
The large rectangles represent the Arduino
The labels had already been explained in a previous topic, please
refer to it.
The “-/\/\/\/\-” represents the power source (battery)
The lines represent cables and connections linking to each other. Any
label not linking to another represents a label that was not employed
The “-/ -” represents the switch and the rest of the symbols represent
what they stand in for in a normal circuit.
Shields
They are modular circuits that can piggyback on your Arduino to give it extra
functions. Arduino shields are a must if you want to do something more than
light up a LED and print a few things on your computer. While you may be able
to rotate a motor with your Arduino, what if you wanted to connect to twitter
with it?
Shield were built in the same spirit as that of Arduino. Easy to use, cheap, small
and functional are the best words to describe Arduino shields. Much like
Arduino itself, they come in various shapes, sizes and functionalities.
It is possible to add more than one shield to Arduino, in fact, the only thing that
limits the number of shields that can be added to Arduino is the circuit load.
Shields often come with a library or an example sketch. This makes working
with shields a very easy thing to do. For an experienced Arduino user, it is
possible to connect Arduino to a shield and get it working in just 5 minutes.
possible to connect Arduino to a shield and get it working in just 5 minutes.
Arduino shields are built with a similar form as Arduino boards themselves.
Power and ground pins will be on one eight pin header, and there will be other
analog pins on a six-pin header next to the eight pins. Digital pins will usually
occupy the other side, an eight-pin header that is seperate from another ten-pin
by some spacing.
Some shields will require another connection to the Arduino's ICSP header as
shown above (the2- 3 pins at the vertical left). Most Arduino shields will use
every pin available on the board, although some take only a few.
Some shields are capable of communication using SPI, I2 C or serial, while
others use analog inputs or Arduino’s interrupts.
Note: Do not use overlapping pins when using multiple Arduino shields.
Types of Shields
Prototyping Shields and Others
Protoshield Kit
This Shield works as a big prototyping area. It is the most popular prototyping
shield. A breadboard can be connected to it, or you can just solder directly to the
board.
Go-Between Shield
This shield solves the issue of overlapping pins by sitting between two shields
and swapping the pins of the top shield.
ProtoSrew Shield
This is a useful tool for linking Arduino to external motors and heavy-duty
sensors. It is similar to the ProtoShield, but each pin is linked to a new screw
terminal.
Danger Shield
This shield typically contains everything from potentiometers, to display, to a
couple of other impressive sensors. The danger shield allows you to mess around
with your Arduino by warning you of danger. It is very important when learning
the ins and outs of using Arduino.
Joystick Shield
This is used to turn the Arduino into a control tool. It contains what might be a
controller, thus allowing you to use your Arduino to control things like robots.
MicroSD Shield
Because of the limited space typical in most Arduino, it might make sense to
connect a microSD shield to the board. This will allow you to input a microSD
in your board and use its memory space for extra storage functions. It typically
comes with an SD library.
XBee Shield
XBee provides Arduino with the ability to communicate wirelessly. While it
cannot connect to world wide web, it can be used to wirelessly start sprinklers,
lights, and coffee machines. It is also very cheap and easy to use.
GPS Shield
Like its name suggests, this shield allows you to use the Global Positioning
system with Arduino. With this, you will always know where you Arduino is.
Spectrum Shield
This allows Arduino to listen to various sounds and turn them into frequencies,
before presenting it in a graphic equalizer display.
Display Shields
Color LCD Shield
This is a small screen component that allows you to display text and pictures
with a 128x128 cell phone color LCD.
CMUCam Shield
This will turn Arduino into a camera. This component is a small camera that
allows the user the option of vision. It is especially useful to users who may be
using their Arduino to control small robots by allowing the user to visually track
it.
Motorz! Shields!
PWM Shield
As I had mentioned earlier, pulse-width modulation can also be used to drive
servo-motors, beyond just dimming LEDs. This shield allows Arduino a fine
range of control over servo motors.
Before you begin, make sure the headers you have match your Arduino footprint
(use the new shield header for R3 layouts and the old headers for Arduino with
that type of header layout).
There are two types of headers. If you will be stacking shields, it is advisable to
use the stackable header and the male header tor single shield works. Male
headers make a lower-profile stack when used to stack shields compared to
stackable headers, but, stackable headers allow you to still insert jumper cables
into the Arduino when the shields are stacked.
Note: stick to headers that have straight, rectangular and male pins for now.
They are easier to work with, and most Arduino components come adapted for
male header pins.
Assembly
Attaching the Header
Headers should be inserted into the shield first. Orientation is of utmost
importance . The headers should face the correct direction. Male pin headers
should enter the top of the shield and extend downwards. Solder the pins only
once you have the header facing the right direction.
Once the headers are inserted properly, flip the board so that the female side
Once the headers are inserted properly, flip the board so that the female side
rests on the flat work-table. Align all headers carefully so that they rest
perpendicular to the Shield.
Soldering
Carefully solder a single pin on each inserted header, this ensures that the
headers remain perpendicular to the shield (in the event of a shake). Ensure the
solder is not too much for each pin.
Testing
Carefully Align the Shield with Arduino and plug it in. This ensures that your
Shield headers are properly aligned. If it is not an immediate fit, please realign
the board and perform the above steps again until the fit is exact.
Soldering
Once your shield headers pass the above test, then solder the rest of the pins to
the shield. Once all your pins are soldered, please check for bad solder joints.
Bad Joints
There are possible mistakes when soldering. Please check that your solder
doesn’t link two pins together if you do not want a short-circuit. Also check for
cold solder joints (they are not soldered but look like they are).
Plug in
It is good practice to disconnect your Arduino before working on it. Now plug in
the Shield by matching Arduino headers to the ones on your shield. Please be
careful not to bend your header pin while doing this.
Congratulations, you have connected your shield to Arduino.
Tricks
A known trick is to use an old shield to aid in aligning the header.
Aligning a male header is significantly easier to align than stackable headers.
This is because you can just plug your pin directly into the Arduino first before
carefully laying your shield on it.
Solder away.
Be careful not to burn your header by leaving the soldering iron on the pins for
Be careful not to burn your header by leaving the soldering iron on the pins for
too long.
Library
Arduino libraries are useful when a programmer needs to make a complex task
as simple as possible. These are contained as part of the extensive add-ons
available to all Arduino users. An example is writing a code to capacitive touch
sensing, while we could spend a few days writing and perfecting the code on our
own, we could just get a code from a great library and implement it into our
Arduino.
You can learn all about how to download and install libraries at the official
Arduino library website. It comes with great instructions about using the
Arduino IDE library manager. (https://www.arduino.cc/en/Guide/Libraries/ ).
First, you will have to download the library from the web
Locate the “.zip” file on the computer and double-click to open it and
extract the folder contained inside
In most library folders, there will be a “.h” and a “.cpp” file.
Copy the whole file.
Open your Documents folder, in it will be an Arduino folder, open it.
Navigate to libraries and past your copied file in that folder.
Edit the name of your pasted folder to remove any symbol that is not
A-Z and 0-9. If you do not do this, you will not be able to use it.
Restart your Arduino if it was already open and by navigating to the
examples folder, you will see the contents of your library there. You
may now open it.
Chapter 6: Practical Projects
Arduino UNO
64 LEDs (3.3V)
10 resistors (the resistor value will depend on the voltage of your
LED)
Craft wire
Prototyping board
Drill of the same size as LED
Crocodile clips
A wooden holder in a 4x4x4 cubic configuration
Because of the limited number of pins available on Arduino UNO, we will
build the 4x4x4 cube using multiplexing. This allows us to break down to 4
layers. This means that we only need to control just 16 LEDs directly.
We simply need to activate a layer and the control pin to light a specific LED,
meaning that we can control all the 64 LEDs with just 20 pins total.
Each layer will be built with a common cathode which will lead to a single pin.
Each LED will be linked to the one above and below it, and since we have 16
layers of positive and 4 layers of negative LED pins, we can do this easily.
The directions are:
Fold the LEDs short leg and drill the needed holes in your wooden
placeholder. It needs to be very tight. The holes should be equidistant
from each other and the folded legs should be of the same size.
Follow the directions as shown in the picture.
Solder the short legs (cathode) on a thin craft wire as shown above.
Test the above configuration using the blink code by connecting a
resistor and ground to cathode (1 pin for all four), and 5V to each
anode and run it. It should light up all the LEDs. If not, all LEDs light
up, check your connections again.
Now do the same for all the remaining 60 LEDs and ensure the
connections are solid.
Then arrange all the 4 LEDs in a cube configuration and ensure the
vertical legs (anode) are soldered together while the cathode is
similarly linked per layer.
If you cannot get a perfect fit for anodes, use a clip to hold them
together and keep them at appropriate height. And ensure anode only
connects to anode. You may snip any out of place wire/leg to ensure a
smoother build.
Once you have your cube, connect the resistors to your prototyping
board and your board to the cube wire frame in what order you want
(LED to board first before resistor or resistor to board first before
LED).
Once your pins are finally connected (the 4 cathode layers to analog
pins 2 to 5, 16 LED anode pins to digital pin 0 to 13 and analog 0 and
1), and we are done.
Upload your code:
https://github.com/brucetsao/eLedCube/blob/master/LED_1cube_4x4x4_Blank_Show_/LED_
Now you can see what it does. You can modify the code by using
“plane(layer)number ” to choose the LED you want to command. Ensure that
all other planes are HIGH before commanding a LED otherwise everything will
light up.
The Arduino shield consists of a 12V jack whose purpose will be to regulate the
3.3V pin for the LoRa module and to power Arduino through the vin pin. The
regulated 5V will thus be used in powering the 12x6 LCD. The two resistors R1
and R2 will act to fix the voltage of the LM317 regulator. An external regulator
is more reliable than the Arduino’s own internal voltage regulator. Included
within the shield will be a potentiometer with the purpose of regulating the
LCD’s brightness.
To design your own PCB:
Download the PCB design software, install it, open it and format your
PCB tracks.
Go to (https://www.pcbgogo.com/?code=t ) and log in or sign up.
Enter your PCB dimensions in the prototyping tab.
Select “quote now ” and change whatever parameters you want. It
costs about $5 and will be delivered in 2-3 days.
Upload the Gaber file generated by the PCB software and once your
file has been verified, you may use whichever payment option you
want.
Once you get the PCB, you may start assembling the board.
Download the LoRa library (https://github.com/sandeepmistry/arduino-LoRa ).
You will need two shields for this project, one for transmission and the other as a
receiver. The receiver will be the one with the LCD attached.
Now that you have the transmitter module ready, you may connect your GPS
module.
Connect the pins D4 to RX and D3 to TX, and ppower it with the 5V pin.
You will need to download the TinyGPS++
(https://github.com/mikalhart/TinyGPSPlus/archive/master.zip ) Library to
interprete the data sent from the GPS module (NMEA sentence).
Coding:
Ensure that you have downloaded and installed the two libraries in your IDE
before proceeding.
To program the transmitter, we use the following code:
https://circuitdigest.com/microcontroller-projects/lora-based-gps-tracker-using-
arduino-and-lora-shield
Once our codes are uploaded, power up the transmitter and the LED on the PCB
will start blinking. The receiver will similarly turn on and display the welcome
message we typed in the above code.
Once the transmitter receives data from the satellite, the LCD will immediately
display it.
The next step is to put the transmitter where you want; car, bag, etc. and you will
be able to track whoever is currently carrying the transmitter with the receiver.
We will connect an LED to Arduino’s pin 13 and the PIR data OUT
pin to Arduino’s pin 8. The LED will indicate that the light has turned
on or off.
Pin 9 of Arduino will connect to IN1 pin of the relay module and a
bulb will be connected to the mains of the Relay (one to mains supply
and the other wire to NO relay contact).
COM of the relay will link up with the other wire of main.
The sensor will link up with pin 8 on Arduino and its ground pin to
ground. Its main pin must be connected to the Arduino’s pin 13
through the breadboard.
Please be careful when connecting to mains (240V AC), if you are
not sure, examine the circuit diagram again.
The code below will then be loaded into the Arduino IDE:
https://www.maxphi.com/pir-motion-sensor-light
Once someone enters the range of the sensor, the sensor detects the movement
through infrared, it’s OUT pin changes from LOW to HIGH, and alerts the
Arduino which changes its configuration from relay pin HIGH to LOW.
This will cause the light to come on.
Once the intruder leaves, the sensor no longer detects motion and changes its
configuration back to LOW from HIGH. This in turn causes Arduino to assume
a HIGH command at the relay pin.
This design is easily applicable as: Garage Lights, Bathroom Lights and Security
Lights.
From your Arduino board to your sensor, connect VCC to 5V pin and
GND to the GND pin.
Connect the Arduino’s pin 2 (digital) to the output signal pin on the
sensor.
Connect Arduino’s GND pin through a breadboard or directly to the
buzzer’s negative terminal.
Connect Arduino’s digital pin 9 to the positive terminal of the buzzer.
The circuit follows the diagram below.
Arduino UNO
2 LED
DS1307 RTC
330K and 4 120K resistor
The circuit uses a multiplexing technique to reduce the number of wires that are
used to link with Arduino while similarly reducing the power consumption
significantly.
The RTC module, keeps track of the time and compensates for drifts like leap
years. We only need hour and minute information though, so that is all we will
extract from it.
The circuit makes extensive use of the breadboard to link multiple pins to the
same Arduino pin. The colored chart describes what is linked to what.
To set the time, open the IDE include the library “DS1307RTC ” you have
downloaded, ensure the time is correct and run the serial monitor.
Once that is done, we upload the code found here:
https://electronics-project-hub.com/arduino-7-segment-display-clock-with-and-
without-rtc/
The libraries can be found here: (https://github.com/PaulStoffregen/Time )
(https://github.com/PaulStoffregen/DS1307RTC )
(https://github.com/DeanIsMe/SevSeg ).
The next thing to do is to power up the module and watch it display the time.
The RTC though, is still vulnerable to temperature variations. For high accuracy,
you will need an RTC with inbuilt temperature compensated crystal.
A breadboard
Arduino Uno
Unity game engine
An Uniduino plugin
10K resistor and potentiometer
Hook-up wires
You may purchase an Arduino starter kit that contains most of this from here
(https://www.makeuseof.com/tag/4-best-starter-kits-arduino-beginners/ ).
Building the controller will follow this circuit diagram:
Once you have your circuit built as described above, open the code
StandardFirmata<Firmata<Examples found in files of your IDE.
10K resistor
Breadboard and Arduino UNO
Connecting wires and three LEDs (green, red and yellow)
A pushbutton switch
Six 220Ω resistor
Below is the circuit diagram we will be using for this project.
The resistors will connect to the LEDs cathode on one end and to D8 to D10 on
the other end. The LEDs on the other end are connected to both the resistor and
ground (cathode), and also connected to the 5V pin on the anode leg.
Once we have our circuit up and running, you can find the code here:
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
As can be seen from the code, it is very similar to blink a single LED.
With the exception of the “changelights() ” function, the rest of the code is
almost the same.
The traffic lights can be changed in several ways to satisfy our own timing by
simply changing the values in the code.
And now, we have our traffic light controller.
A fairly nice way to round off right? Wrong .
Why don’t we alter the code to allow someone else to choose when it turns
RED without altering the code?
You would have noticed from the above that you did not use all the hardware
you were told to get.
Follow the circuit below:
The difference between the two circuits is academic. The button in this circuit is
connected to pin D12 and the switch now has a resistor attached to it (10K).
The code can be found here:
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
What the new code does is wait for 15 seconds after the button is pushed before
the light changes. This allows someone to control the lights by pushing the
button.
Why don’t we also add a junction to our traffic lights controller?
Just follow the circuit below:
The original LEDs are connected as in the previous examples and the
pushbuttons have been removed. The new LED sets are connected to D11- D13
using a similar method to the earlier examples.
Upload the following code:
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
Unlike the previous examples, when one set of lights is red, the other will turn
green and vice versa.
This is the same method that most street traffic controllers use.
However, since they do this over a large area without any wired input, they must
be communicating over the web.
Arduino can also do this. We will explore this avenue in our next chapter.
Chapter 7: Smart Appliances and The Power of the
Web
Hardware Install
Connect the Arduino 5V pin to the positive rail on the breadboard,
and ground the board by connecting the ground pin to the negative
rail.
Place the CC300 board and the DHT sensor on the breadboard.
Connect pin 1 of DHT to the positive rail on the breadboard and pin 4
to the negative one.
Connect the sensor’s pin 2 to Arduino’s pin 7, and connect the 4.7K
resistor between pin1 and pin 2 of the sensor to complete that part of
the circuit.
Connect the cell in series with the 10K resistor on the breadboard and
connect the ground the other end of the resistor.
The common pin on the photocell should then connect to analog pin
A0.
Connect the Wi-Fi module by linking it’s IRQ pin to Arduino pin 3,
CS to pin 10 and VBAT to pin 5.
Connect SPI pins to Arduino by linking MOSI to pin 11, MISO to pin
12 and CLK to pin 13.
Finally connect Vin to Arduino 5V (positive rail) and ground to
ground (negative rail).
Testing the sensors:
// Libraries
#include "DHT.h"
// DHT sensor
#define DHTPIN 7
#define DHTTYPE DHT11
// DHT instance
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
// Initialize the Serial port
Serial.begin(9600);
// Init DHT
dht.begin();
}
void loop()
{
// Measure from DHT
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Measure light level
float sensor_reading = analogRead(A0);
float light = sensor_reading/1024*100;
// Display temperature
Serial.print("Temperature: ");
Serial.print((int)temperature);
Serial.println(" C");
// Display humidity
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Display light level
Serial.print("Light: ");
Serial.print(light);
Serial.println("%");
Serial.println("");
// Wait 500 ms
delay(500);
}
The above code is a simple one designed to test if the sensors are working or not.
As you can see, the code is explained using comments. The complete code is in
the library mentioned earlier.
Upload the sketch and the data will display something like:
Temperature: 25 C
Humidity: 36.00%
Light: 83.79%
Now that the sensors are working, we need to make it capable of connecting
electronically to Wi-Fi. Dweet has “things”, this is a place where you upload
data through http requests. Should you upload data to a new thing that has not
been created before, it would be instantly created.
The code below automatically connects to the freeboard server and uploads the
data.
data.
Serial.println(F("\nInitializing..."));
if (!cc3000.begin())
{
Serial.println(F("Couldn't begin()! Check your wiring?"));
while(1);
}
// Connect to local WiFi network
Serial.print(F("Connecting to WiFi network ..."));
cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
Serial.println(F("done!"));
// if the sketch hangs, this code will reset it. It is called a watchdog
wdt_reset();
/* Wait for DHCP to complete */
Serial.println(F("Request DHCP"));
while (!cc3000.checkDHCP())
{
delay(100);
}
}
void loop(void)
{
// Measure from DHT
float t = dht.readTemperature();
float h = dht.readHumidity();
float h = dht.readHumidity();
temperature = (int)t;
humidity = (int)h;
// Measure light level
float sensor_reading = analogRead(A0);
light = (int)(sensor_reading/1024*100);
Serial.println(F("Measurements done"));
// Start watchdog
wdt_enable(WDTO_8S);
// Get IP
uint32_t ip = 0;
Serial.print(F("www.dweet.io -> "));
while (ip == 0) {
if (! cc3000.getHostByName("www.dweet.io", &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
cc3000.printIPdotsRev(ip);
Serial.println(F(""));
// Reset watchdog
wdt_reset();
// Check connection to WiFi
Serial.print(F("Checking WiFi connection ..."));
if(!cc3000.checkConnected()){while(1){}}
Serial.println(F("done."));
wdt_reset();
// Send request
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected()) {
Serial.print(F("Sending request... "));
client.fastrprint(F("GET /dweet/for/"));
client.print(thing_name);
client.fastrprint(F("?temperature="));
client.print(temperature);
client.fastrprint(F("&humidity="));
client.print(humidity);
client.fastrprint(F("&light="));
client.print(light);
client.fastrprintln(F(" HTTP/1.1"));
client.fastrprintln(F("Host: dweet.io"));
client.fastrprintln(F("Connection: close"));
client.fastrprintln(F(""));
Serial.println(F("done."));
} else {
Serial.println(F("Connection failed"));
return;
}
// Reset watchdog
wdt_reset();
Serial.println(F("Reading answer..."));
while (client.connected()) {
while (client.available()) {
char c = client.read();
Serial.print(c);
}
}
Serial.println(F(""));
// Reset watchdog
wdt_reset();
wdt_reset();
// Close connection and disconnect
client.close();
Serial.println(F("Closing connection"));
Serial.println(F(""));
// Reset watchdog & disable
wdt_reset();
wdt_disable();
// Wait 60 seconds until next update
wait(60000);
}
// Wait for a given time using the watchdog
void wait(int total_delay) {
int number_steps = (int)(total_delay/5000);
wdt_enable(WDTO_8S);
for (int i = 0; i < number_steps; i++){
//Serial.println(F("Waiting for 5 seconds ..."));
delay(5000);
wdt_reset();
}
wdt_disable();
}
Let’s now go into the details of the code. It starts by importing the required
libraries:
#include
#include
#include
#include "DHT.h"
#include
The above code can be modified to suite our own needs as noted by the
The above code can be modified to suite our own needs as noted by the
comments scattered through it. Now that the data has been sent to freeboard,
Arduino will consistently send code over to the server.
To display the data graphically, we use freeboard.io to create a new dashboard
and display our data in human understandable visuals.
Cut the power strip to determine which of the three wires in it connect
to each prong on its plug (ground, live and neutral). You may use a
continuity tester to determine this.
Remove a knock out plugs from the outlet box, and install the NM/SE
connector in its place.
Remove some of the outer sheathing of the cord and feed it into the
electric outlet box through the connector (3-4”).
Carefully off 4” of the live wire and remove about ¼” of the cut off
live wire insulator and insert it in the NO terminal of the relay, and
connect the ground, signal and VCC wires to the relay.
Connect the remaining live wire into the C terminal of the relay and
ensure it is a fit.
Secure all the wires and the relay in the box and make sure they can
all fit well.
Secure the live wire from the NO relay terminal to the hot terminal of
the power outlet (the one with the smaller slot) with the gold screws.
The neutral wire from the power cord should also be secured to the
neutral terminal of the outlet (left side with larger slots) with the
silver screw.
Also, secure the ground wire to the ground terminal outlet (D-shaped)
with the green screw.
Screw the outlet into the box and ensure it fits, then cover it up and
screw in the cover.
We now have an outlet that can be easily controlled by Arduino. All that
remains, is to connect the pins to your Arduino and upload code, and we are
done.
The connections should follow the above design. The USB will lead to the
computer, or you may attach a battery to it using one of the examples given
previously. The bulb can be anything, from your coffee machine to your washing
machine.
dht DHT;
#defines DHT11_PIN 7
int pinOut = 8;
void setup(){
Serial.begin(9600);
pinMode(8, OUTPUT);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
// DHT.humidity can be changed to DHT.temperature
if (DHT.humidity <= 40){
// the value <= 40 can be changed to any humidity or temperature
digitalWrite(pinOut, HIGH);
} // tells the pin to allow current flow. The bulb turns on
else {
digitalWrite(pinOut, LOW);
} // tells the pin to prevent current flow. The bulb goes off
delay(500);
}
The above code is similar to the one we uploaded previously to send data to the
web. It takes in the humidity and temperature data and tells the power outlet to
switch on when humidity reaches 40%. This can also be done to tell the bulb to
turn on when temperature is below 300K by changing the values as noted in the
turn on when temperature is below 300K by changing the values as noted in the
code.
An Arduino robot
HC-05 Bluetooth Module
Android with OS 2.2 or 2.1 and above.
A Google account and a Bluetooth controller App.
The Bluetooth Module will have its 5V pin connected to Arduino’s
5V pin and it’s ground pin connected to that of Arduino.
You may connect the Bluetooth TX pin to Arduino’s RX pin only
since there is no data to be received from Arduino.
You may completely remove the distance sensor from the Arduino if
you wish and connect pin 9-12 of Arduino to IN1-IN4 of the Motor
module as above, and the Enable pins should connect to 5V using a
jumper.
The Bluetooth module may be placed above or below the chasis.
The following code will then be uploaded.
You may download the code here .
The code is explained using comments. From what we had done above and a
little experimentation, the code becomes clearer still.
The next step is to open the Bluetooth controller application. The application can
be gotten on google play.
Configure the control keys in app paying attention to how you configured it in
code.
When say the forward key is pressed, Arduino receives the data through
Bluetooth communication as 1 and Arduino will thus make IN1 and IN3 HIGH
while IN2 and IN4 will become LOW. This achieves a forward motion. The
same system will be used for the other motions, granting free command over the
same system will be used for the other motions, granting free command over the
motions of the robot.
This is unfortunately not as useful as a Wi-Fi module because, the range is 10
meters. There must also be sufficient power provided to the Bluetooth module to
prevent it from shutting down.
Connect a red jumper to the 3.3V power pin, a brown one to the 3.3V
pin (enables chip), a white one to TX, a grey one to RX and a black
one to ground.
The TX jumper cable will be connected to RX1 on ArduinoMega and
the RX cable will lead into TX1 on ArduinoMega.
Since nunchuk communicates using i2c, most Arduino will come
with an inbuilt i2c bus (they also have their own connection plugs,
but you can just use jumper wires and A breadboard or jumper wires
only). Connect the nunchuk. SDA pin - analog 4 and SCK - analog 5.
(Do not buy off-brand ones, stick to Nintendo nunchuk.
To set up a server to communicate with the ESP8266, we use the code on this
instructable page (https://github.com/splatspace/esprelay/ ). It allows the
communication of two devices to log on to any computer that is running the
code.
You will need to install Python 2.7 on your PC in order to run the code.
AT+RST
AT+CWJAP="this will be occupied by your Wi-Fi’s SSID", "This
will be occupied by the password of your Wi-Fi"
AT+CIPCLOSE
Type the codes below to enable communication with the transmitter of the
nunchuk;
Ensure you correctly selected the right board in the Tools > Board
menu. This is because of differences in the ATmega chips in differing
Arduino types. See (https://www.arduino.cc/en/Guide/Environment )
for more information on properly selecting your Arduino type.
Make sure that you selected the correct port to which you connected
Arduino. As I had mentioned earlier, unplug and re-plug Arduino to
the computer and carefully monitor the option that appears, if you did
not initially see your Arduino listed under Tools > Serial Port .
If you cannot find Arduino still, then follow the next steps.
Drivers
Drivers are what allows the IDE on your computer to communicate with the
Arduino. What happens when a USB cable is plugged into a system for the first
time is that, the computer accepts drivers that are stored on the board and installs
time is that, the computer accepts drivers that are stored on the board and installs
them. These drivers provide a virtual serial port. Most Arduino use USB CDC
(standard drivers) provided by the operating system while some use FTDI.
If your Arduino type does not appear in the Tools > Serial port menu, then the
driver was not installed.
For windows 7, connect the board again, open the device manager
and update your drivers for Arduino. Right click on the board and
point windows to the “.inf” file. It will be in the drivers/directory of
the IDE file.
For Linux, symlink from /dev/tty/ACM0 to dev/tty/USB0. Then you
may run
Crash
Should the software crash at launch or work unnaturally slowly, or the Tools
menu seems to open too slowly.
Disable Bluetooth serial ports and that of any other networked COM
ports using Device Manager. Since Arduino IDE scans all the COM
ports on the computer upon startup and whenever the Tools menu is
open, these networked ports often cause delays and crashes
Ensure that the only program that scans all serial ports currently open
on your task manager is Arduino IDE. Some Applications that do this
are; virtual daemon tools, BlueSoleil, PDA sync apps…
Ensure the computer is not running a firmware that disables access to
serial ports (ZoneAlarm)
Quit processing, vvv… should you be using them to read data from
the USB cable to Arduino
For Linux, you can try to run the IDE as a root file, and see what
changes
If this doesn’t fix the issue, proceed to the next step.
Direct Connection
Sometimes, the problem arises from physical disconnections from the
board.
Ensure that the Arduino LED is on.
Ensure you are connected directly to both Arduino and the computer.
It there is a USB hub connection, please connect the two directly and
test for changes.
Change the USB cord. Sometimes, this works.
While the code is uploading, disconnect digital pins 0 and 1, and
reconnect them after the upload.
Try disconnecting everything else from the board and uploading the
code.
Ensure Arduino is not touching anything metallic or conductive. As
we had earlier explained, it may ground the board.
The above steps should solve your problems. If they do not, proceed to the next
step.
Cygwin conflicts
6 [main] ? (3512) C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe: *** fatal
error - C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe: *** system shared
memory version mismatch detected - 0x75BE0084/0x75BE009C.
The above error displays when you have “Cygwin ” running while you are using
Arduino. You can also just delete “cygwin1.dll ” from your Arduino directory
and then replace it with “c:\cygwin\bin\ ”.