You are on page 1of 209

The basics on Arduino compatible

hardwares and with code comment

Guide
Book
No guide gets easier than this

BY STEMANGO
ELECTRONICS
Arduino Guide www.stemango.com

About the Guide Book

We realized a good tutorial means a lot to Arduino users, especially for beginners has
zero experience either with Arduino or C programming language which Arduino use.

Mostly you would find the tutorial come with the other kit out there on market has
very little explanation on either hardware or Arduino code.

But we rewritten and do plenty of research work to meet the requirement as a


beginner or advance user to Arduino.

You will find everything you need to begin working with your favorite projects. Each
tutorials include: technical characteristics, operating principles, instructions on how
to connect the module with Arduino and basic code. Even more we try to attach as
much code comment as we can to let user understand the code.

So the structure of each tutorial maily in 3 sections:

Hardware
Basic knowledge tells waht hardware do and how it works
Wiring
Shows how to connect all parts with Arduino
Sketch
We try to add code comment

But this book will not guide you through from programming, you can learn about
programming from this book “arduino_notebook_v1-1” stored in SD flash disk we
provided in package.

So everything else is up to you and your imagination.

Thanks for choosing us and please feel free to contact us.

Copyright © 2017 by Shenzhen FengGu Technology Co.,Ltd. All rights reserved.

- 28 -
Arduino Guide www.stemango.com

TERMS OF USE
This is a copyrighted work and Shenzhen Feng Gu Technology Co.,Ltd. And its
licensors reserve all rights in and to the work. Use of this work is subject to these
terms. You may use the work for your own noncommercial and personal use; any
other use of the work is strictly prohibited. Your right to use the work may be
terminated if you fail to comply with these terms.

“Arduino” is a trademark of Arduino team.

THE WORK IS PROVIDED “AS IS.” Shenzhen Feng Gu Technology Co.,Ltd MAKE NO
GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR
COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,
INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA
HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Shenzhen Feng Gu Technology Co.,Ltd do not warrant or guarantee that the functions
contained in the work will meet your requirements or that its operation will be
uninterrupted or error free. Neither Shenzhen Feng Gu Technology Co.,Ltd nor its
licensors shall be liable to you or anyone else for any inaccuracy, error or omission,
regardless of cause, in the work or for any damages resulting therefrom. Shenzhen
Feng Gu Technology Co.,Ltd has no responsibility for the content of any information
accessed through the work. Under no circumstances shall Shenzhen Feng Gu
Technology Co.,Ltd be liable for any indirect, incidental, special, punitive,
consequential or similar damages that result from the use of or inability to use the
work, even if any of them has been advised of the possibility of such damages. This
limitation of liability shall apply to any claim or cause whatsoever whether such claim
or cause arises in contract, tort or otherwise.

- 29 -
Arduino Guide www.stemango.com

Contents
00. Get started

What is Arduino? ......................................................................................................

What to prepare? .....................................................................................................

About our UNO ...........................................................................................................

Arduino Enviroment installation guide .......................................................................

Arduino sketch ...........................................................................................................

Test your Arduino board.............................................................................................

01. Heloworld! .................................................................................................................

02. Let it blink ...................................................................................................................

03. Push button ................................................................................................................

04. Analog read in Arduino...............................................................................................

05. PWM control LED brightness ......................................................................................

06. Toggle switch control LED ...........................................................................................

07. Tilt sensor Debounce ..................................................................................................

08. Color RGB LED.............................................................................................................

09. IR remote control LED .................................................................................................

10. One-digit 8-segment LED display ................................................................................

11. Shift register 74HC595 drive 8-segment LED display...................................................

12. MAX7219 drive dot matrix display .............................................................................

13. Alarm ..........................................................................................................................

14. Temperature alarm ....................................................................................................

15. MQ-2 gas sensor alarm ...............................................................................................

16. PIR motion detector ...................................................................................................

17. Make a fan..................................................................................................................

18. Transistor control toy motor ......................................................................................

19. Reed swtich control toy motor ...................................................................................

20. L293D 2WD robot .......................................................................................................

21. Moving a servo ...........................................................................................................

22. Password door lock ....................................................................................................

- 30 -
Arduino Guide www.stemango.com

23. Stepper motor ............................................................................................................

24. Rotary encoder control stepper motor .......................................................................

25. Light sensor ................................................................................................................

26. Flame sensor ..............................................................................................................

27. Voice recognition........................................................................................................

28. Temperature and humidity sensor .............................................................................

29. Liquid crystal display 1602 ..........................................................................................

30. Temperature and humidity monitor ...........................................................................

31. Real time clock ...........................................................................................................

32. Four digit 7 segment display clock ..............................................................................

33. Barometric temperature altitude monitor .................................................................

34. Driving Nokia 5110 LCD ..............................................................................................

35. Loading graph on Nokia 5110 LCD ..............................................................................

36. Ultrasonic distance sensor ..........................................................................................

37. Distance meter ...........................................................................................................

38. BH1750 Light sensor ...................................................................................................

39. Light meter .................................................................................................................

40. Soil moisture sensor ...................................................................................................

41. Soi moisture meter .....................................................................................................

42. Read RFID ...................................................................................................................

43. Display RFID UID on OLED ..........................................................................................

44. Loading graph on I2C OLED .........................................................................................

45. Display text on SPI OLED.............................................................................................

46. OLED temperature and humidity monitor ..................................................................

47. Driving 1.8 inch TFT SPI display...................................................................................

48. Image slideshow on 1.8 inch display...........................................................................

49. Digital spirit level ........................................................................................................

50. Indoor climate monitor ..............................................................................................

51. Bluetooth control DC motor on Android.....................................................................

- 31 -
Arduino Guide www.stemango.com

00. Get Started

What is Arduino?

Arduino is an open source electronics prototyping platform, including hardware


(various types of Arduino boards) and software (Arduino IDE). Developed by a
European team in 2005.Its members include Massimo Banzi, David Cuartielles, Tom
Igoe, and Gianluca Martino, and David Mellis and Nicholas Zambetti.

Hardware

Arduino boards allow you make circuit conections through pins to control things,for
example turn lights on and other sensing devices to feedback, impact on the
environment. You can take Arduino as a physical computer communicate with your
computer via universal serial bus (USB),or use the Arduino as an interface board to
control those same electronics from your computer.

Based on Arduino projects can contain only the Arduino, and can also contain the
Arduino and other software running on the PC, communication between them (such
as Flash, Processing, MaxMSP) is to be achieved.

Below projects completed by Arduino may help you to have some idea of what
Arduino can do .

A password lock,press right password then green LED light on green and servo
steering arm turn to certain angle.

- 32 -
Arduino Guide www.stemango.com

An indoor climate monitor, use 1.8inch TFT color display shows


date,time,temperature, humidity,pressure.

4WD smart robot car can avoid obstacle,follow lines,controlled via smartphone.

- 33 -
Arduino Guide www.stemango.com

Software

The above projects can’t be done without the software --- the sketch (or can be
called code, program) using Arduino C language and Arduino IDE.

The programming language used in Arduino is Arduino C. It is called Arduino C as it is


much like a lite version of standard C( also called ANSI C or ISO C), but it still powerful
enough to handle the task you can throw at it. You will learn Arduino C based on
projects.

Below picture shows all process from coding to running sketch on Arduino.

Generally, you just have to write code in the IDE, upload program sketch to the
Arduino board, the program will tell the Arduino board to do something.
What to Prepare?

Microcontroller

The brain of Arduino is an integrated circuit IC microcontroller. It can use the Arduino
programming language to write programs, compiled into a binary file, burned into
the microcontroller. It is a tiny computer has a processor,static random access
memory (SRAM) for data storage - lost after power removed, electrically erasable
programmable read-only memory (EEPROM) for holding your programs and it has
input and output pins. These input/output (I/O) pins link the microcontroller to the
rest of your electronics.

- 34 -
Arduino Guide www.stemango.com

Arduino mostly use Atmel family controllers, you should consider purchasing an
Arduino board based on one of those listed in below table.

ATMEGA Flash SRAM EEPROM Clock Digital Analog Voltage Arduino Board
MCU Memory (bytes) (bytes) Speed I/O Input
(bytes) pins Pins
168 16k 1k 512 16Mhz 14 6 5v Nano/Pro/Lilypad
328 32k 2k 1k 16Mhz 14 6 5v UNO/Mini/Nano/Pro/
Lilypad
2560 256k 8k 4k 16Mhz 54 16 5v MEGA2560

So which one to purchase? It really depends on what you want to do with the
microcontroller.

Arduino UNO is the most used and documented product among Arduino products, it
certainy is the best option for beginner just exploring the Arduino platform. If you are
building smart home project using several sensors, then you will probably want to
use a version that has a lot of digital I/O pins and an extra stack-on sensor shield. If
your project has a lot of program code associated with it, then obviously you should
pick one with more flash memory.

Note:
The built-in bootloader take 2K–8K of Flash memory.
The higher price it is the more I/O or memory the board has.

External Devices (electronic components and modules)

Some electronic parts are necessary for doing experiment while learing Arduino as
that would not dilute your interest if you just read a book, so we developed couple of
starter kits targeted at Arduino beginners and advanced users, programmable robot
hobbyist along with our guide book.

Click below online platform to view our products.


eBay Amazon Aliexpress

- 35 -
Arduino Guide www.stemango.com

About Our UNO


We use the DIP ATMega328P and ATmega16U2 USB FTDI chip version which is similar
to the official UNO R3 board.

We will soon update our UNO by changing PCB board color, adding pin label and our
logo on like following picture.Please bookmark our online stores for return visit.

- 36 -
Arduino Guide www.stemango.com

Specification

Microcontroller :ATmega328P
Operating Voltage :5V
Input Voltage :7-12V
Input Voltage (limit) :6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
PWM Digital I/O Pins 6
Analog Input Pins :6
DC Current per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
Flash Memory :32 KB (ATmega328P) of which 0.5 KB used by bootloader
SRAM :2 KB (ATmega328P)
EEPROM:1 KB (ATmega328P)
Clock Speed :16 MHz
Length :68.6 mm
Width :53.4 mm
Weight :25 g

Power Pins

-VIN (sometimes labelled "9V"). The input voltage to the Arduino board when it's
using an external power source (as opposed to 5 volts from the USB connection or
other regulated power source). You can supply voltage through this pin, or, if
supplying voltage via the power jack, access it through this pin. Note that different
boards accept different input voltages ranges, please see the documentation for your
board.
-5V. The regulated power supply used to power the microcontroller and other
components on the board. This can come either from VIN via an on-board regulator,
or be supplied by USB or another regulated 5V supply.
-3V3. (Diecimila-only) A 3.3 volt supply generated by the on-board FTDI chip.
GND. Ground pins.
-I/OREF Pin above reset Pin,this pin on the Arduino board provides the voltage
reference with which the microcontroller operates. A properly configured shield can
read the IOREF pin voltage and select the appropriate power source or enable
voltage translators on the outputs for working with the 5V or 3.3V.

- 37 -
Arduino Guide www.stemango.com

Arduino Enviroment (IDE) Installation Guide


Go to http://arduino.cc/en/Main/Software to download the installation file
according to your operate system.

Mac and Linux users, please directly open the Arduino sketch by simply clicking on the
file with .ino extended name. For MacOS please click here for instruction.

Install the driver

Open the Device Manager window and expand Ports (COM & LPT) and you should
see a COM port which will be your Arduino as shown in the image below.

- 38 -
Arduino Guide www.stemango.com

Right-click the COM port and Select “Update Driver Software”

Select “Browse my computer for driver software.”

Click “Browse” and find the directory location of the Arduino IDE (where the
installation files are located.)

Attention: If your board is the other version using CH340 USB chip, then please
download the CH340 driver for windows here and Select it then click “OK”.

- 39 -
Arduino Guide www.stemango.com

Inside this director will be another director named“Drivers” . Select it and click“OK” .

- 40 -
Arduino Guide www.stemango.com

In the Windows Security dialog box that pops up, click “Install”.

Below window indicates successful installation. Hopefull this is what you will see! If
not double check our steps and try again.

Go to “Device Manager” >“Ports (COM & LPT)”. You should see “Arduino
UNO(COM#) /USB Serial – Arduino UNO(COM#)”. This is the COM port that your
computer uses to transfer data to your Arduino. In our example the computer
communicates with the Arduino on COM36. Remember your COM number as you
will need it later.

- 41 -
Arduino Guide www.stemango.com

Before you test your board, you will get to know some most used functions in
Arduino IDE first to avoid any confusion in your future projects.

When you move your mouse over the button, it will show what it does in the middle
of the menu bar. In below picture the example is Verify button. From left to right it is
Verify,Upload,New,Open and Save.

In source code window you can edit,copy and paste code on the other code
window.If you edit the example codes come with Arduino and try to save it.You
would see a pop up message window says “Some files are marked read-only so you
will need to save this sketch in a different location.” Just accept the default location,
but change the filename to the other name like Test sketch.

- 42 -
Arduino Guide www.stemango.com

- 43 -
Arduino Guide www.stemango.com

Arduino Sketch

Arduino sketch is like documents in word,excel. You can see there are
Open,Save,Save as under file menu.

Mostly we open the file-for instance a file named“sketch”directly downloaded online,


if you did so or use Open option under file menu, you would see a pop up message
window says “The file "sketch.ino" needs to be inside a sketch folder
named"sketch".Create this folder,move the file and continue?”

What will happen if you click “Ok” on above pop up message window? The sketch
will be stored in the new folder named same as sketch name and located where you
opened. Unlike word,excel, Arduino application been designed with the concept of a
Sketchbook where all your sketches are kept carefully organized into folders.
Skethbook folder located here “C:\Users\xxxxx\Documents\Arduino”, on Mac or
Linux,they are in Documents/Arduino.

So we recommend keep all sketch organized under sketh book folder to find your
sketch easily next time. All the sketches used in this guide book can be found in our
SD card provided in package. Copy folder “sketches” and paste it under sketchbook
folder. This is convenient while you do experiment in this guide book.Below picture
shows how it look.Restart IDE if you could not see it.

- 44 -
Arduino Guide www.stemango.com

Test your Arduino board

Our UNO board preinstalled a very basic sample Blink program to go through the
whole process and test whether the microcontroller is working.You should see the
onboard LED(as below picture shown) light-emitting diode flash when you plug in the
board.

Open the LED blink example sketch. You will find it under File > Examples > 01.Basics >
Blink .

Click “Verify” to compile your code. The IDE changed the code from text into binary
that the microcontorller can understand. This process called compiling.
Verifying

- 45 -
Arduino Guide www.stemango.com

Done Compiling

The code we are using should not have errors since it is an example code. If a code
does have errors in it it will fail to verify.

Select your microctroller by selecting “Board>Arduino/Genuino UNO”.

- 46 -
Arduino Guide www.stemango.com

Then select your COM port by selecting “Serial Port” and selecting the COM port
number you saw earlier. In our example COM3 is in use.

On windows machine you should see COM3 in serial port unless you have other
device occupy the USB port. On Macs and Linux machines, you will see a much
longer list of serial devices. The device will normally be the top selection in the list,
with a name similar to /dev/tty.usbmodem621.

- 47 -
Arduino Guide www.stemango.com

Click “Upload” to send the sketch to Arduino.

The onboard LED will be furious blinking while the sketh is transferred, then it will
blink on and off. Meanwhile you would see “Done Uploading” at the bottom of
Arduino IDE and a message similar with “Binary sketch size: 1018 bytes (of a 14336
byte maximum).” You would know how many bytes your program took in flash
memory of your Arduino board in the future.

- 48 -
Arduino Guide www.stemango.com

Project 01 Helloworld!

The first project we would simply use Arduino and PC to see and feel the process. We
will let Arduino say “Hello World!” This experiment allows Arduino to communicate
with computer. In this program, we use character “R” as order to make Arduino
Display”HelloWorld!” and the Led will be on at the meantime.

Parts Required
-Arduino UNO or other compatible board x 1
-USB Cable x 1
-Computer x 1

How to do
Start Arduino. Program to make Arduino accept order say “Hello World! ”, and you
could make it work by simply using “if() ”.Use the “L” led on Arduino to make a blink
then display “Hello World! ”

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 01.Helloworld

- 49 -
Arduino Guide www.stemango.com

Project 02 Blink A LED

This project we will wire external device to Arduino!

Input and Output

The Arduino has various options for your connection pins, also known as I/O.(input
interface / output interface).Outputs can be digital or analog, digital output allow
you to set the voltage to be either 0V or at 5V, analog ouput allows you to set the
voltage to any voltage between 0V and 5V—althouth it is far more than this as we
shall see. Likewise, inputs can either be digital (for example, determining whether a
button pressed or not) or analog (such as from a potentiometer).

First we start with digital output in Arduino and digital write ( ) command in code.
We will use a LED as external device connected to Arduino digital output pin and
issue digital write ( ) command. The physical result is a LED turn on for 1 sec. and
turn off 1 sec repeatly.

In the code section you would see our comments so you can get to know what is
going on inside the invisible process among the external device, Arduino and PC.

Note :
We will name digital pins from pin 0 -13 on Arduino as D0 – D13, analog pins 0-5 as
A0 – A5 in coming projects sketches.

Parts Required

- 50 -
Arduino Guide www.stemango.com

Note:
In all the fritzing wiring image we included in this guide book doesn’t show battery or
usb cable, but you do need them. We tested all projects by using the computer’s 5V
USB port. You can use the external power too.

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 02.Blink A LED

Result
Upload the code you will see the led flickering repeatly every 1 second, so our small
lights flashing experiment is done.

- 51 -
Arduino Guide www.stemango.com

Hardware

Breadboard
An electronics breadboard (as opposed to the type on which sandwiches are made)
is actually referring to a solderless breadboard. These are great units for making
temporary circuits and prototyping, and they require absolutely no
soldering.Components are pushed into socket and extra jumper wires to make
connection.

Prototyping is the process of testing out an idea by creating a preliminary model


from which other forms are developed or copied, and it is one of the most common
uses for breadboards. If you aren’t sure how a circuit will react under a given set of
parameters, it’s best to build a prototype and test it out.

For those new to electronics and circuits, breadboards are often the best place to
start. That is the real beauty of breadboards–they can house both the simplest circuit
as well as very complex circuits.

Jumper wires

Jumper wires are used for making connections between electronics on your
breadboard and your Arduino’s header pins. Use them to wire up all your circuits!
Normally red Jumper wire indicates power supply (Vcc), black wire indicates ground
(GND), green wire indicates digital pins, blue wire indicates analog pins, and white is
other.The jumper wires come with our kit has two types.

- 52 -
Arduino Guide www.stemango.com

F-M (male to female) M-M(male to male)

LED

A light-emitting diode (LED) is a two-lead semiconductor light


source. It is a p–n junction diode, which emits light when
activated. When a suitable voltage is applied to the
leads, electrons are able to recombine with electron
holes within the device, releasing energy in the form
of photons. This effect is called electroluminescence, and the color of the light
(corresponding to the energy of the photon) is determined by the energy band gap of
the semiconductor.A LED symbol in a schematic as above picture shown, current flow
from anode to cathode.

You can also find LEDs with 4 leads which will be explored later.

- 53 -
Arduino Guide www.stemango.com

Resistors

Resistors resist the flow of electricity. The higher


the value of the resistor, the more resistance it has
and the less electrical current will flow through it.
The unit of resistance is called the Ohm, which is
usually ( Greek letter Omega / “R”). Unlike LEDs,
resistors are not polarized (do not have a positive and negative lead) – they can be
connected either way around. A resistor symbol in a schematic as above picture
shown.

The resistor value will be marked on the on the outer package of


your resistors, but what should we do in case the label gets lost and
there are no measuring tools at hand? The answer is to read the resistor value. This is
a group of colored rings around the resistor. Details are available online for those
who are interested in having a try.

Click Here go to an online calculator for five-color-ring resistor value calculating:

- 54 -
Arduino Guide www.stemango.com

What resistor we need?

In this case we use digital interface #10 outputing 5V DC at 40mA according to


Atmega datasheet. Normally a LED needs 2V of voltage and 20 mA or less current to
be lit, so with a resistor of would be able to reduce 5v to 2v and 40mA to 20mA to
control the flow you might risk burning it out. Be careful of this because resistors can
get hot! If we want the LED to be dimmer we could use a higher value of resistance
and vise vesa.

Here we do some math to figure out what resistor value use for the LED we use here.
The formula use here is ohm’s law
I = V/R
In order to get resistance in a circuit we need this: R=V/I or, more relevant to what
we're doing:

(Source Volts - LED Volts) / (Current / 1000) = Resistance*

So if we have a DC 5v powering a 2V 20mA LED our formula becomes:

(5- 2) / (20/ 1000) = 150ohms.

*
milliamps(mA) = 1/1000th of an amp.

220 ohm resistor is not costed that much than 150ohm and much common used. So
just use the nearest one you can easily find.

In the future projects you will use Ohm’s law to calculate the resistor value needed.

- 55 -
Arduino Guide www.stemango.com

Project 03 Push Button

This experiment we will try to use a button as the digital input (i.e read the value
from external device ---a button) to control a led light. We will give digital read ( )
command to read the value from button and digital write ( ) command to assign
what voltage ( 0v or 5v ) applied on the LED.

Hardware
Push button is a two leg normally open switch, means it
stays off and circuit is open when unpressed. Likewise,
circuit closed and working when pressed. Below picture
shows diagram of a button. For example, circuit
connected when you connect A to C or D, but A to B
won’t work.

Parts Required

- 56 -
Arduino Guide www.stemango.com

Wiring

As above wireing picture shown, the pin D of button is connected to ground through
the 10KΩpull-down resistor. Why put a resistor here? If you disconnect resistor, the
LED may blink erratically. This is because the input is "floating" - that is, it will
randomly return either HIGH or LOW. That's why you need a pull-down or pull-up or
resistor in the circuit.

The pull-down resistor here to pull down the current and the result is we read a LOW.
The next question is why the value is 10K? We still use Ohm’s law R = V/I, let’s say
you want to limit the current to 1mA for button, the result is
5V/0.001A=5000Ω.Again we selected the common used 10K to replace 5k. You can
use 5K6 if you like. But higher value will bring stronger pull-down(less current flow).

When the button is pressed, it makes a connection between its two legs, connecting
the pin to 5 volts, so that we read a HIGH.

Note:
You can also wire this circuit the opposite way, the behavior of the sketch will be
reversed, with the LED normally on and turning off when you press the button.If so
the pull-up resistor MUST NOT be removed as VCC would connect to GND and casue
short.

- 57 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 03.Push Button

Result
You should see the LED turn on if you press button,like wire LED off if you release
button.
Not working?
1.Upload the code again and see if uploaded successfully.
2.Double check wiring base on code or fritz illustration schematic.
3.Check if you put button in the wrong way, try to twist it 90 degree twist and see if it
starts working.
4.Check LED positive and negative ends.

- 58 -
Arduino Guide www.stemango.com

Project 04 Analog Read in Arduino

From previous projects we know about digital input and output. This project we will
use a potentiometer as analog input and give command analog read ( ), in other
words the Arduino read the raw analog value from external device --- a
potentiometer. Arduino analog Read( ) of Arduino UNO is a 10 bit analog to digital
converter(ADC) to converts the input voltage range, 0 to 5 volts, to a analog value
between 0 and 1023.

In this example, that analog value will be displayed on serial monitor. When the shaft
of potentiometer is turned all the way in one direction, there are 0 volts going to the
pin, and we read 0. When the shaft is turned all the way in the other direction, there
are 5 volts going to the pin and we read 1023.

Below picture shows progress

Note:
The result you would get maybe a number (for example --- 2) closed to 0 or close to
1023 when you turn the shaft to either end due to the tolerance of the
potentiometer.

Hardware
A potentiometer, also referred to as trimpot or pot, known as variable resistor, may
come in a wide variety of shapes and are used in many applications in your daily life,
for example to control the audio volume of the radio, normally they has a nice cap on
top, but the inner part is what you see in our package like below picture.

- 59 -
Arduino Guide www.stemango.com

Potentiometers with linear taper are marked with a B, the relationship between the
resistance and the potentiometer position is linear. 10K refer to the resistance value,
it allows you to adjust the resistance from minimum 0Ω to maximum 10KΩ.

Potentiometers can be used as voltage dividers or rheostat. To use the potentiometer


as a voltage divider, all the three pins are connected, only outer pin and middle pin
connected as rheostat. The pot we provided has No polarity. Any of the outer pins is
connected to the GND, the other to Vcc and the middle pin is the voltage output.

If you have different potentiometer from other supplier, please make sure the
resistor value is high enough to limit the current to Arduino, otherwise it may
damage the Arduino board.
Parts Required

- 60 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 04.Analog Read

Result
This program use #13(LED light) digital interface of Arduino,the led will flash every
time it got the reading. Open the serial monitor on Arduino IDE. Below is the
readings. You can see the data on the screen is changing while you twist the
potentiometer.

- 61 -
Arduino Guide www.stemango.com

Serial Monitor
Serial monitor is a communication “tool” between Arduino and computer. You can
debug Arduino software sketches, sending command to Arduino or to view data sent
by a working Sketch. All Arduino boards have at least one serial port (also known as a
UART or USART): Serial. You must have the Arduino connected by USB, that is how
the Arduino communicate with the computer.Arduino serial ports are 0 and 1,
marked as RX(0) and TX(1).When you upload code to Arduino these serial ports are
occupied, if you connected these ports to a device say like a bluetooth module, the
code wou’t be uploaded to Arduino. So leave 0 and 1 eampty during you are
uploading the code.

Note: Don't connect these pins directly to an RS232 serial port; they operate at +/-
12V and can damage your Arduino board.

In this example we want to view the data sent from analog read sketch. When you
click the top right button named “serial monitor” it will pop up a new window. If you
set the right baudrate at the bottom left of the pop up window, you should see the
result as below in this example.

Baud Rate
The baud rate specifies how fast data is sent over a serial line. It’s usually expressed in units of
bits-per-second (bps). If you invert the baud rate, you can find out just how long it takes to
transmit a single bit. This value determines how long the transmitter holds a serial line high/low
or at what period the receiving device samples its line. Baud rates can be just about any value
within reason. The only requirement is that both devices operate at the same rate. One of the
more common baud rates, especially for simple stuff where speed isn’t critical, is 9600 bps. Other
“standard” baud are 1200, 2400, 4800, 19200, 38400, 57600, and 115200.

- 62 -
Arduino Guide www.stemango.com

Project 05 PWM Control LED Brightness

As you learned from last project, Arduino analogRead read analog input pin from
potentiometer, value range from 0 to 1023.Arduino also has an analogWrite range
only from 0 to 255. This example will show you how to scale the analog read value to
a integer value range from 0 to 255, then use that result to set the pulse width
modulation (PWM) of an output pin to dim or brighten an LED and print the values
on the serial monitor of the Arduino IDE .

Below graphic shows whole process.

Pulse Width Modulation(PWM)

PWM is a technique for getting analog results with digital means. Digital control in
this example is a pot used to create a square wave, a signal switched between on
and off. This on-off pattern can simulate voltages in between full on (5 Volts) and off
(0 Volts) by changing the portion of the time the signal spends on(Ton) versus the
time that the signal spends off(Toff). The duration of "on time" is called the pulse
width.To get varying analog value, you change, or modulate, that pulse width. If you
repeat this on-off pattern fast enough with an LED for example, the result is as if the
signal is a steady voltage between 0 and 5v controlling the brightness of the LED.

For better understanding the relationship between pulse width and analog value, we
set the duty cycle to 75% by twisting the konb of the potentiometer in this
program.Before we go to wiring section, let’s do some math to figure out some
terms ossociated with pulse width.

- 63 -
Arduino Guide www.stemango.com

In the graphic below, the orange lines represent a regular time period. This duration
or period is the inverse of the PWM frequency. In other words, with Arduino's PWM
frequency at about 500Hz, the orange lines would measure 2 milliseconds each.

Frequency − Arduino's PWM frequency at about 500Hz except pin D5 and D6 on


Arduino UNO have a frequency about 980Hz. On most Arduino boards (those with
the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and
11. This example we use D9 which has about 500Hz.
= 2ms
Period (Ttotal) − It is represented as the sum of on-time and off-time of PWM signal
and can be calculated as shown in the following equation −

Duty Cycle − It is represented as the percentage of time signal that remains on during
the period of the PWM signal,duty cycle is calculated as −

A call to analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a


100% duty cycle (always on), and in this example analogWrite(191) is a 75% duty cycl
e (75% of the time). As mentioned early you can adjust the pot to about 191.
D=75%=

Toff = Ttotal – Ton = 2 – 1.5 =0.5ms


So a pulse width result came out like that.

But now you probably have doubt with getting the analog write value? Basically, we
need to scale our read values from the potentiometer, which will be between 0 and

- 64 -
Arduino Guide www.stemango.com

1023 to suitable write values, which should be between 0 and 255. As we know the
voltage is linear with either analog write or analog read value, which means analog
write value linear with analog read value too.

The analog write value can be calculated as –

255 = (255/1023)*1023

To change the values from 0-255 to a range that corresponds to the voltage the pin is
reading, you'll need to create a variable float in code.

The equation as below

- 65 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 05.PWM control LED
Brightness

- 66 -
Arduino Guide www.stemango.com

Result
The led will go dim or brighter while you twisting the shaft of the pot as you changing
the resistance. You will see content like below picture shown in serial monitor.

Not working?
The terminal of the potentiometer is bigger than insert holes on breadboard, make
sure they contact well with breadboard.

- 67 -
Arduino Guide www.stemango.com

Project 06 Toggle Switch Control LED

In project push button we learned how to use a push button as digital input to
control LED to be state ON or OFF. From this project we will start to know more
switches. Fortunatelly Switches don’t require any fancy equations to evaluate. It has
simple states, on and off. The on state closes the circuit, in this case the switch act as
a conducting wire to allow current get through the system. There are tons of switch
out there. You learned how to use a push button and today we will get to know the
toggle switch.

Hardware

When you hear toggle switch, think “fire ze missiles!”.


Toggle switches have a long lever, which moves in a rocking
motion. As they move to a new position, toggle switches
make a really satisfying “snap”.

Toggle switches are commonly SPST (two terminals) or SPDT (three terminals),
though you can find them in other flavors as well. As usual, you can find them in
through-hole, surface-mount, or – probably most commonly – as panel-mountable.

This project we shows how to wire and control two LEDs.

Parts Required

- 68 -
Arduino Guide www.stemango.com

Wiring
In this example we used 1k resistors, if the LED gets too soft spot try using LEDs 220
Ohms.

Sketch
No codes require for this experiment. Just connect all parts.

Result
Turn the switch to left, you will see that the red LED will light, move to the right the
green LED illuminates.

- 69 -
Arduino Guide www.stemango.com

Project 07 Tilt Sensor

This project we still use tilt sensor as switch but as we shall see in sketch, we use
debounce(check twice if switch on). That is why they were called tilt sensor as they
are NOT immune to small vibration.

This project works in this way. When the sensor detects movement, which means the
contacts inside tilt sensor are NOT CONDUCTED the LED is HIGH (on), likewise when
no movement detected the LED is LOW (off).

Hardware

The tilt sensor can detect inclination and orientation. It contains two contacts and
two small metal balls or a blob of mercury ball. Once sensor is oriented, the balls
conduct the two contacts and complete the circuit. You can install the tilt sensor
angle

This project we use a LED as output and serial monitor will show if the tilt sensor on
state of tilted or not tilted. In realy world application you should see some product
with tilt sensor –for example to set an alarm at snooze, tilt it over and it will do that.

- 70 -
Arduino Guide www.stemango.com

Parts Required

Wiring
A pulldown resistor have to be connected to the tilt sensor to ensure the circuit is
disconnected when no signal is detected (even the tilt swich ON). You also need to
add a current-limiting resistor to the LED. In below graphic shows 10K and 220R are
connected for saving wires, you can separate them and add wires too.

- 71 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 07.Tilt Sensor
Debounce

Result
Assume you installed the tilt sensor with pins pointing down, the LED is HIGH (on)
when you turn the board upside down. Open the serial monitor you would see the
state changed once tilt sensor being turned.

- 72 -
Arduino Guide www.stemango.com

Project 08 RGB LED

If you get bored with the single color LED, don’t lost interest. You can have more fun
with Red Green Blue (RBG) LED. This component combines red, blue and green LEDs
and can display various colors by adjusting the different values of each light. The
common product you would see in daily life is a computer monitor which uses many
RBG LEDs to display an image. We will learn how to create different colors and
combine colors randomly in this project --- for example, if you turn on the red pin
and green pin, the RGB will light up as yellow.

Below graphic shows how to identify different pins. The longer pin of the RGB is the
common ground pin. You can create a custom colored LED by turning different colors
on and off to combine them. For example, if you turn on the red pin and green pin,
the RGB will light up as yellow.

Parts Required

- 73 -
Arduino Guide www.stemango.com

Wiring

Note: When wiring the RGB LED, each colored pin still needs a current-limiting
resistor in-line with the I/O pin connected to.

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 08.RGB LED

Result
You should see the RGB LED blinking with random colors after uploading this code.

5050 SMD RGB LED


You may see the 5050 SMD(surface-mount device) type of
RGD LED in package. 5050 means the size of the LED chip,
5mm x 5mm.No need extra resistor as they are already
mouted on board. People used these LEDs to decorate their
house, bike and car etc.Normally they came as strip.

This project we use only one SMD LED module to see the
effect. The schematic of the LED module as below

- 74 -
Arduino Guide www.stemango.com

Parts Required

Wiring
1. R - Red output
2. G - Green output
3. B - Blue output
V connect to GND on UNO R3 board
Sketch
This sketch same as the one used for RGB led.
To open the code go to: File > Sketchbook >STEManGo Electronics > 08.RGB LED

- 75 -
Arduino Guide www.stemango.com

Project 09 IR Remote Control LED

This project we get into a wireless way to control LED,infrared(IR) communication.


Infrared is normal light, but it has stronger wave length than visible light, it is
undetected by human eyes, however it can still be reflected by objects such as glass
and walls. There are lots of IR source in our daily life---for example the sun,light bulbs
or anything very bright in IR spectrum.

The most common used is the TV remote, you change the volume and channel
control by pushing the keys on remote controller.

Now the question is how the TV recognize the singal from the TV controller rather
than other IR source?

There are rarely natural IR sources that have the regularity of a 38kHz signal, so an IR
transmitter sending data at that frequency would stand out among the IR source.
38kHz modulated IR data is the most common, but other frequencies can be
used.When you use IR LED as IR transmitter, it turns on and off 38,000 times per
second to transit information to IR receiver input pin, output pin of IR receiver
demodulated into binary waveform that Arduino can read.So modulation and
demodulation completed the whole process.

Below graphic (quoted from sbprojects.com) shows how IR transmitter, receiver and
Arduino work together.

Hardware
The Transmitter
What you should receive in our kit is a clear 5mm IR LED
which has 940nm wavelength, almost all devices can
detect it. The working range estimated 8meters. Like
normal LED, longer leg is positive end. You can drive them
continuously with 100mA and for IR remote application
they can take up to 1 Amp pulses(power MOSFET suggested with this used with high
power).

- 76 -
Arduino Guide www.stemango.com

Normally you would see it built in the top of your TV remote. It can’t work without
power and controller.

The picture below shows our mini IR remote controller.

Note:The power used for this controller is a button battery with CR2025 model
number. The battery maybe removed as some of the kits were shipped via air and
battery is restricted according to air flight policy. You need to buy one to get the
controller work. If you got it with battery, just pull out the insulation film.

- 77 -
Arduino Guide www.stemango.com

The Receiver

The VS1838B IR receiver also known as photo


detector, the photo sensor diode and preamoplifier
IC are assembled in leadframe against the electric
filed disturbance. You probably see it prodcuded as
module type too. The mark on the module G R Y
refer to Ground, VCC and Signal.

Warm Up Exercise A– Receiving Signal

Before we get to controling device, we do some basic practices first to know each
part first.

First we will do the receiving singal. You can use any IR remote controller --- for
example your TV remote as IR transmitter, but we use the one included in our kit in
this project. The target is decoding the key code of the IR controller’s button and
display the code to the Arduino serial monitor.

First you need to load the library called “IR Remote”. Below instruction shows how to
do it.

What is library?

There are lots of talented Arduino user wrote many codes. Some of them developed
libraries to save other user’s time on wring codes from scratch and make the final
sketch neat and simple. For example, the IRremote library include the major files
named “IRremote.cpp” and “IRremote.h”. If you open these two files with Notepad
++, you would see there are more than 200lins of code to finish multiple task.

How to load library

There are two way to load/install library.


First one can be done without internet. Just do the copy and paste job.
Find the library named “IRremote” in SD card we provided, under folder Arduino
Compatible Starter Kit Guide Book >STEManGo Electronics >09.IR Remote Control
RGB LED>Library

- 78 -
Arduino Guide www.stemango.com

Copy and paste the library to the libraries directory inside the Arduino IDE directory
on your computer. In our example, the location is C:\Program Files
(x86)\Arduino\libraries.

Beware that inside the folder will be a .cpp file, a .h file and often a keywords.txt file.
Be sure that these are within the same directory otherwise the Arduino IDE will not
recognize the library.

The other way to do so you need internet. Open Arduino and go to : Sketch > Include
Library >Manage Libraries

Then you would see a window as following.

- 79 -
Arduino Guide www.stemango.com

Then you can see the serach bar is editable after library index loaded completed.
Try search by the library name in this case “irremote” and it will show result.
Click install and it would automatically install in a few seconds. I had it installed
before so it shows “INSTALLED”.

Parts Required

Wiring

- 80 -
Arduino Guide www.stemango.com

Sketch
After the IRremote library loaded, open Arduino IDE and go to File > Examples >
IRremote > IRrecvDemo ,then upload to Arduino.

Result
When everything is wired correctly and code uploaded, you should see “Enabling IRin”
on serial monitor.

The sketch will automatically decode the type of remote you are using and identify
which button on your remote is pressed. Open the serial port in the Arduino IDE at
9600 bps and press different buttons on your remote.

- 81 -
Arduino Guide www.stemango.com

IR Remote Controller Protocol

The data value received and shown in serial monitor was the 32-bit hexadecimal
value –fore example FFA25D. It refers to the power button from our IR controller.
Each IR remote contoller manufacturer used different chip, so the protocol for
encoding data varies and do not pair with another device. The IRremote library has
other example shows the protocol.

Open Arduino IDE and go to File > Examples > IRremote > IRrecvDump.After you
uploaded the code and open serial monitor, set the baud rate at 9600.If you push
power button you should see result as below image shown. The first line is the hex
value of the power button been pressed, second line tells you the protocol name
which is NEC and value type. The third line includes varity of numbers stand for the
raw timing data of the actual mark and spaces received.

After you know the hex code of each button, you can put these values in other
project –for example, IR control robot car, you can design the function of each button
in your program as below picture shows.

- 82 -
Arduino Guide www.stemango.com

Warm Up Exercise B– Transmitting Signal


* Below instruction Excercies B qutoed from SparkFun Electronics Website, click here to visit.

This exercise we will try to use Arduino work with the IR LED to imitate the IR
controller to control your home applicance --- for example a TV. First you need to
figure out the protocol of your TV, the easiest way to find out is finding out the
protocol of your TV remote. We don’t have a TV remote at hand, so this example we
use the other type of mini IR remote as TV remote, let’s give it a tag - RC2.

In below example VS1838B IR receiver receives a signal from RC2 when any key
pressed, receiver copies the data, then sends it out of the IR LED.

- 83 -
Arduino Guide www.stemango.com

Parts Required

- 84 -
Arduino Guide www.stemango.com

Wiring

Sketch

First go to your Arduino IDE open File -> Examples -> IRremote -> examples ->
IRrecord. Upload the sketch to your Arduino. After you have loaded the sketch, open
the Arduino serial monitor to 9600bps. Point your remote directly at the VS1838B
and hit a button on RC2. You should see specific codes in the serial monitor,
identifying the button you hit on RC2.

- 85 -
Arduino Guide www.stemango.com

In this example, we got FF22DD from RC2.

Result

Now, if you point the LED at your appliance and hit the push button that is connected
to your Arduino, the code for the button press on your remote will be sent. Once you
know which codes correspond to each button, you can create your own remote with
the Arduino and IR LED.

If you saw the serial monitor displayed characters “Receive unknown codes, saving as
RAW …..” and still want to send it, use line #154 in sketch (IRrecord).

irsend.sendRaw(rawCodes, codeLen, 38);

- 86 -
Arduino Guide www.stemango.com

After previours warm up excercies, let’s control a device – LED. When the power
button is pressed, the LED will be on or off.
Parts Required

Wiring

- 87 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 09.IR Remote
Control LED

Result
Point the IR Remote controller to IR receiver, press power button on IR remote, you
should see the LED status change.

- 88 -
Arduino Guide www.stemango.com

Project 10 One-Digit 8-segment LED Display

You can see segement led display in bike speed monitor,count down device, alarm.
Today we will introduce a new device, start with 1-digit 8-segment LED display.

Hardware
The 1-digital 8-segment LED is a formed LED bars for displaying
decimal numerals. Each LED bar/point refer to each segment
connected to a digital pin, all segment’s status turn to high that would
be number “8.” . For numbers, it can display from 0 – 9. That is why it
is 1-digit.Later we will show you how to use 4-digit one.

The graphic shows 10pins assignment for 1-digit


8-segment LED display. Each pin has dedicated name a-g
and dp stand for decimal point.

Note: the com pin refers to common anode or cathode.


When you get the common anode one, connect the
com pin to Arduino 5V, whereas cathode to GND.

It is important to know whether you get is common


anode or cathode. The must-do step is wiring all pins to
current limited resistor.

Part A: Test 8-Segment LED Display Module

Let’s test it if all segments display as it should. The example will display numbers
from 0 -9 in order.

- 89 -
Arduino Guide www.stemango.com

Parts Required

Wiring
Note: All pins MUST connect through a 220R resistor to limit current!
Connect “b a f g e d c dp“ to D2 - D9
The LED display we privded is common cathode
Connect both middle com pins to Arduino GND

- 90 -
Arduino Guide www.stemango.com

Sketch (1)
To open the code go to: File > Sketchbook >STEManGo Electronics > 10.One-digit
8-segment LED Display > eight_segment_led_display_1

In code you will find this line.

int n0[8]={1,1,1,0,1,1,1,1};

It is an array to collect and orgazied all values. Without the array, the code for light
up all segements would be as below.

digitalWrite(2,1)
digitalWrite(3,1)
digitalWrite(4,1)
digitalWrite(5,1)
digitalWrite(6,1)
digitalWrite(7,1)
digitalWrite(8,1)
digitalWrite(9,1)

The theory is assign different values ( 0 or 1 ) to digital pins, finally turns


corresponding segment to be off or on.

Note: As we use common cathode one in this project, com pin connect to GND, 1
means the digital pin connect to VCC, which is HIGH and turn segment on.

So in above example, n0[8] “0” means number 0 that you want to display. Number 8
means there are 8 values in this array, the question is how to tell program to pick up
correct value and in order? Here we used a concept, an index number that is not
shown in code. Index number start with 0, then the first value’s index number is 0,
not 1. For example, in order to display number 0, the array is 1,1,1,0,1,1,1,1, then
n0[0] can pick up the first value 1,n0[4] can pick up 5th value.

Now how this function assign the picked up value to Arduino digital pins status? In
other words, how to get the value to turn corresponding segment on or off?

It has to work with for loop as below.

for(int pin = 2 ; pin <= 9 ; pin++)

The whole procedure as below:

- 91 -
Arduino Guide www.stemango.com

pin=2 → n0[0] =1 → digitalWrite(2,1) → b segment on


pin=3 → n0[1] =1 → digitalWrite(3,1) → a segment on
pin=4 → n0[2] =1 → digitalWrite(4,1) → f segment on
pin=5 → n0[3] =0 → digitalWrite(5,0) → g segment off
pin=6 → n0[4] =1→ digitalWrite(6,1) → e segment on
pin=7 → n0[5] =1 → digitalWrite(7,1) → d segment on
pin=8 → n0[6] =1 → digitalWrite(8,1) → c segment on
pin=9 → n0[7] =1 → digitalWrite(9,1) → dp segment on
Sketch(2)
In the sketch above, we created 10 arrays, n0[8] to n9[8] to display number 0 to 9.
That 10-arrary is a one-dimensional array. Now we are going to create a
two-dimensional array to make the code simpler and look nicer.

To open the code go to: File > Sketchbook >STEManGo Electronics > 10.One-digit
8-segment LED Display > eight_segment_led_display_2

int number[10][8] =
{
{0,0,0,1,0,0,0,1}, //display 0
{0,1,1,1,1,1,0,1}, //display 1
{0,0,1,0,0,0,1,1}, //display 2
{0,0,1,0,1,0,0,1}, //display 3
{0,1,0,0,1,1,0,1}, //display 4
{1,0,0,0,1,0,0,1}, //display 5
{1,0,0,0,0,0,0,1}, //display 6
{0,0,1,1,1,1,0,1}, //display 7
{0,0,0,0,0,0,0,1}, //display 8
{0,0,0,0,1,1,0,1} //display 9
};
void numberShow(int i){ //call this function to display numbers
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin, number[i][pin - 2]);
}
}
void setup(){
for(int pin = 2 ; pin <= 9 ; pin++){ // define digital pins 2 to 9 as output

- 92 -
Arduino Guide www.stemango.com

pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
}
void loop() {
for(int j = 0; j <= 9 ; j++){
numberShow(j); // call numberShow() function to
display 0-9.
delay(500);
}
}

You would notice there is two-dimensional array.

int number[10][8]{
{0,0,0,1,0,0,0,1}, //display 0
{0,1,1,1,1,1,0,1}, //display 1
{0,0,1,0,0,0,1,1}, //display 2
{0,0,1,0,1,0,0,1}, //display 3
{0,1,0,0,1,1,0,1}, //display 4
{1,0,0,0,1,0,0,1}, //display 5
{1,0,0,0,0,0,0,1}, //display 6
{0,0,1,1,1,1,0,1}, //display 7
{0,0,0,0,0,0,0,1}, //display 8
{0,0,0,0,1,1,0,1} //display 9
};
What is array number [4][3] refer to? That would be the 3rd element in 4th line.
Answer is 1 in blue background as below graphic shown.

- 93 -
Arduino Guide www.stemango.com

The theory is same as sketch (1). Turn each segment on or off by assigning value 1 or
0 to Arduino digital pins.

Part B: IR Remore Control 8-Segment LED Module

This project we combined the IR remote control LED and 8-segment LED display.
When key number 0-9 on IR remote controller pressed, the 8-segment LED display
the corresponding number. When increase button ( + ) pressed, the number will
increase, whereat decread when decrease ( - ) button pressed.
Parts Required

- 94 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 10.One-digit 8-segment
LED Display

The key functions in this project is the first step which recognize what IR codes
received from IR remote controller. There are 3 different situations. We use “if…else
if” as below.

if (results.value == codes[i]&& i <= 9)


if (results.value == codes[10]&& currentNumber != 0)
if (results.value == codes[11]&& currentNumber != 9)

Result
Try to press button on remote controller and check the LED display shows
corresponding numbers.

- 95 -
Arduino Guide www.stemango.com

Not working?
Sometimes the wiring to one or two segments could be losen.
Double check the wiring to each pins of the 8-segment LED display.
Double check the IR receiver pins, note the left pin is signal pin when components
front face toward user.

- 96 -
Arduino Guide www.stemango.com

Project 11 Shift Register 74HC595 Drive 8-segment LED


Display

Last project the 8-sgement display took 8 I/O on Arduino. Is there a way to save I/O
so that you can put other components in party? The solution is using a shift register
as a “master on/off switch” to control indivisual segment. We need to understand
what the shift register do first then we would understand what the code mean.

Hardware
Introduction
Integrated Circuit(IC) stands for "Integrated Circuit". An IC is a tiny circuit made up of
resistors, diodes and transistors and placed in a single package. Each IC has a part
number and is created for a specific purpose. ICs are available in different packages.

The photo below shows from left to right – an IC that contains logic gates packaged
in a 14 pin package, a timer IC in an 8 pin package and a voltage regulator IC in a 3

pin package.

Transistors are also available in the 3 pin package shown above. This specific package
is known as a TO-220 package. The part number will tell you whether it is a IC or a
transistor in this package. This is done by looking up the part number using a search

- 97 -
Arduino Guide www.stemango.com

engine on the Internet or entering the part number into a search box on the
manufacturer's website.

All ICs are marked with a part number, no matter in which type of package they are
packaged. For electronics beginners, most of the ICs that are used will be packaged
as DIP (Dual In-line Package).

Today we start with IC 74HC595 shift register.


IC 74HC595 shift register belong to DIP type. It
has an 8-bit shift register and an 8-bit storage
register. IC pins are all numbered.Take a look at
below graphic shows the pins out of a 74HC595
chip. There are 16pins, Q0-Q7 are output pins, in
this project we will use these pins to connect to
eight segments through resistor. The other pins
can be considered as controller pins.

PINS 1-7, 15 Q0 " Q7 Output Pins

PIN 8 GND Ground, Vss

PIN 9 Q7" Serial Out

PIN 10 MR Master Reclear, active low

PIN 11 SH_CP Shift register clock pin

PIN 12 ST_CP Storage register clock pin (latch pin)

PIN 13 OE Output enable, active low

PIN 14 DS Serial data input

PIN 16 Vcc Positive supply voltage

Below procedure shows how this “Master on/off switch” work.


Pin14 DS ---> Pin11 SH_CP ---> Pin12 ST_CP
Receive serial data Shift the data by bit Storage register
Q0 to Q1,Q1 to Q2….etc

- 98 -
Arduino Guide www.stemango.com

*Pin 13 OE (output enable) pin, this is used to enable or disable the outputs all at
once,normally it is connected to GND.
*Pin 10 MR(SRCLR) is serial clear pin, it will empty the whole shift register if
pulled low,normally it is connected to VCC.
*Pin 9 Q7’ is cascading output, used for connecting multiple 74HC595 chips,connect
to next chip’s DS pin if used.

The following project we use it to display numbers from 0-9 and letters A b c d E F.
The sketch would allow one segment illuminated at once, but that would cycle
between the segments so quickly it would look like they were all on at once,which is
multiplexing.

Parts Required

- 99 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 11. Shift Register
74HC595 Drive 8-Segment LED Display
Result
The 8-segment display would strart displaying number 0 with decimal point, end with
letter F.

- 100 -
Arduino Guide www.stemango.com

Project 12 MAX7219 Drive Dot Matrix Display

So far you should be familiar with the array. This project we introduce a more
complicated one, dot matrix, which is a two dimensional patterned LED array.It is
widely used to represent characters, symbols, and images.

Hardware

It combines 64 LEDs,the I/Os of Arduino are not enough if we light up all of LEDs. The
easier way to do this is like we did in last project, we used a chip as controller to
switch them on/off or indivisual. Today we introduced MAX7219 LED driver chip. This
is known as driver on serial connected segment displays.

Basically, it support SPI serial interface, so the control pins connect to Arduino I/O
would require just 5 included 3 power and ground pins.You would see the assemble
type as below picture shown. It has circuit board with 0.1uf,10uf capacitor and
10kohm resistor. We will build one base on breadboard from scratch.

- 101 -
Arduino Guide www.stemango.com

Parts Required

Wiring
First let’s wire the max7219 and dot matrix display. We use female to male jumper
wires to connect dot matrix pins to breadboard.

Below graphics shows the pin assignment of MAX7219 and its connection with 8*8
dot matrix display.

Note: MAX7219 is used to driver common cathode.

- 102 -
Arduino Guide www.stemango.com

- 103 -
Arduino Guide www.stemango.com

Capacitor

Capacitor is like a small rechargeable battery store an


electrical charge for a short time. It helps filter the dips
and spikes in an electrical signal. Since MAX7219 IC
drawn the current drawn drastically as it multiplexes, it
will draw from the power supply, causing the voltage to
start drooping until power supply realizes that it needs to compenstae the drooping
voltage. So a decoupling capacitor needed here as a fast “charge storage” near the IC.
We connect 2 capacitors in parallel to ground. This includes a 100nF capacitor and a
10μF capacitor. They make sure the power supply is steady. Ceramic capacitor is
unpolarized,the electrolytic capacitor is usually polarized, the negative leg is marked
with a minus sign.
Sketch
We need to load a library called "LedControl" first.

To open the code go to: File > Sketchbook >STEManGo Electronics > 12.MAX7219 Drive Dot
Matrix Display

In code you should see below arrays.

byte s[8]={B00111100,B00111100,B00100000,B00111100,B00111100,B00000100,B00111100,B00111100};
byte t[8]={B11111111,B11111111,B00011000,B00011000,B00011000,B00011000,B00011000,B00011000};
byte e[8]={B11111111,B11111111,B11000000,B11111111,B11111111,B11000000,B11111111,B11111111};
byte m[8]={B11000011,B11000011,B11100111,B11111111,B11111111,B11011011,B11011011,B11011011};
byte a[8]={B00111100,B01111110,B11000011,B11111111,B11111111,B11000011,B11000011,B11000011};
byte n[8]={B11000011,B11100011,B11110011,B11111111,B11011111,B11001111,B11000111,B11000011};
byte g[8]={B11111111,B11111111,B11000000,B11011111,B11011111,B11000011,B11111111,B11111111};
byte o[8]={B11111111,B11111111,B11000011,B11000011,B11000011,B11000011,B11111111,B11111111};

Good news is we don’t have to edit array on by one, you can use a software to
convert the pixel to matrix array.You can find the software in folder named “PC
Software” under folder “12. MAX7219 Drive Dot Matrix Display”.

It is easy to use,you would see “Form1” window after double click, then you can
draw the graphic or letters by clicking the pixels. Click generat and a new windows
shows array will pop up. Below example shows character “S”.

- 104 -
Arduino Guide www.stemango.com

Not working?

If the pixel display in mess, make sure the Wiring for the dot matrix is started from
pin1 is from left side, pin9 at right side when dot matrix’s top face to you.
In same case the jumper wires to breadboard or dot matrix could be loosen.

- 105 -
Arduino Guide www.stemango.com

Project 13 Alarm

Let’s try a new component: the buzzer! It is used for making sounds of different
frequencies using sinusoidal waves. They are widely applied in alarm system,
computer,call bells etc. Besides alarms, buzzers can also be used as musical
instruments using different frequencies to form different notes.

This project we begin with interfacing the buzzer with Arduino to make sound. In
code we used float sinVal to store sinusoidal waves’ value and exchanged the value
to sound frenquency. Ultimately you will hear high and low beep.

Hardware
There are two types of buzzers, piezo and solenoid. Piezo require higher voltage to
generate sound.For beginner we recommend using the solenoid one which needs
lower power consumption.

Piezo and solenoid buzzers are categorized in to two types: active and passive
buzzers. The “active” and “passive” do not refer to power sources, but oscillation
sources.

An active buzzer will generate a tone using an internal oscillator, so a DC voltage can
power it and make sound by changing DC current into a pulse signal of a certain
frequency. Active buzzers are polarized, long lead (anode) and short lead (cathode) .

A passive buzzer has no oscillator, like a speaker. It needs signal, a square wave from
2khz - 5khz then convert the signal to sound. Passive buzzers are are non-polarized

- 106 -
Arduino Guide www.stemango.com

Parts Required
Note:The buzzer doesn’t need a resistor since it can cause attenuation.

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 13.Alarm

Result
You should hear alarm of high and low pitches after uploading the code.

- 107 -
Arduino Guide www.stemango.com

Project 14 Temperature Alarm

From this project we start to adding sensors to sense the environment and active the
digital device as actuator. This project we will use a temperature sensor LM35dz to
switch the buzzer and LED on when the temperature reaches a certain range.

Hardware
LM35DZ is a temperature sensor with TO-92 package.
It outputs anlog voltage linearly proportional to the
Centigrade temperature, from the datasheet you can know
the scale factor is linear 10mV/ °C, which means each 10
milivolts are equals to 1 Celsius. So the equation to convert
anlog voltage to centigrade temperature is

In project 4 - analog read you learned Arduino ADC has a definition of 1024 values
(10bits) . The UNO board is powered by 5V, so first we need to let the Arduino ADC
convert the obtained analog value into analog milli volt(mv). So to get the centigrade
temperatue we need to use this conversion equation

Parts Required

- 108 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 14.Temperature Alarm

You can revise the temperature range in code according to your living environment.

if(Fahrenheit <= 85){


digitalWrite(13, HIGH);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}

- 109 -
Arduino Guide www.stemango.com

Result
Open the serial monitor and you can observe the temperature shown in Celsius and
Fahrenheit.
Try to rasie the temperature to see the buzzer and LED’s response.

- 110 -
Arduino Guide www.stemango.com

Project 15 MQ-2 Gas Sensor Alarm

When gas is leaking, people normally hear a speaker playing a nosiy tone. This alarm
system can be completed by the gas sensor module with Arduino. Today we will
introduce the MQ-2 gas sensor.

Hardware
This analog gas sensor - MQ2 is used in gas leakage detecting
equipment in consumer electronics and industrial markets.
This sensor is suitable for detecting LPG, I-butane, propane,
methane, alcohol, Hydrogen and smoke. It has high
sensitivity and quick response. In addition, the sensitivity can
be adjusted by the potentiometer on the back of the module.

The output is an analog signal and can be read with an analog input of the Arduino.
The back of the module has a blue trimpot, you can twist it to adjust the gas
sensitivity level.

- 111 -
Arduino Guide www.stemango.com

Parts Required

Wiring
Like other sensors to Arduino, we will work only with digital and analog ports,
reading the values sent by the sensor. In our circuit tests, we use the digital port for
connection to the 7 pin D0 module, and the A2 analog port connected to the module
pin A0. The digital ports 8, 9 and 10 will be used to drive a red LED and buzzer
(detected gas), and a green LED in normal operation (no alarm).

- 112 -
Arduino Guide www.stemango.com

Sketch
In the program, the value read from the analog port (valor_analogico), is compared
with the nivel_sensor variable to determine at what point will trigger the buzzer and
also the red led. You can adjust the nivel_sensor value according to the desired level
of detection.

To open the code go to: File > Sketchbook >STEManGo Electronics > 15.MQ-2 Gas Sensor
Alarm

Result
You can check in real time the value of valor_digital variables (port D0)
and valor_analogico (A0 port) in the serial monitor

- 113 -
Arduino Guide www.stemango.com

Project 16 PIR Motion Detector

This project we introduce the widely used PIR moition sensor. When a person
approach or left the detected area the sensor will send signal to Arduino and Arduino
will trigger the buzzer on. In order to imitate the realy life alarm, we use a piezo as
actuator.

Hardware

PIR (Passive Infrared)motion sensor is a pyroelectric sensor developed for detecting


level of infrared radiation. As project 09 introduced, everything emit certain level of
infrared radiation,human body generate heat so it gets picked up by the PIR sensor.

An integrated PIR sensor combined with a metal can and a rectangle crystal(model#
RE200B in below image refer to the PIR sensor), and has a fresnel lens mounted on a
compact PCB.

As below picture shown, the orange areas are two pieces sensing material. The
reason for that is that we want the sensor to detect motion (change) not average IR
levels. The two pieces are connected so that they can cancel each other out. If one
half sees more or less IR radiation than the other, the output will swing high or low.

- 114 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 16.PIR Motion Detector

- 115 -
Arduino Guide www.stemango.com

Project 17 Make A Fan

One of the most useful thing you can do with an Arduino is control higher voltage
(120-240V) devices like fans, lights, heaters, and other household appliances. The
Arduino only operates at 5V, so it can’t control these higher voltage devices directly,
but you can use a 5V relay to switch the 120-240V current and use the Arduino to
control the relay. There is no connection between the low voltage circuit operated by
Arduino and the high power circuit - the relay isolates the circuits from each other.

This project we will make a fan powered by DC power. When button pushed the fan
will start working and LED turn on. The fan and LED will stop working when button is
pushed again.

Hardware
Introduction

Relay is an electrically operated switch. Standard and generally used relay use an
electromagnet to mechanically operate the switch and provide electrical isolation
between two circuits.

This project we use a SPDT(single pole double throw)relay. Below pictures show the
inside and outside’s pin out of a relay.

- 116 -
Arduino Guide www.stemango.com

Relay’s Terminals

COIL(3)- This is one end of the coil


COIL(4)- This is the other end of the coil. These are the terminals where you apply
voltage to in order to give power to the coils (which then will close the switch).
Polarity does not matter. One side gets positive voltage and the other side gets
negative voltage. Polarity only matters if a diode is used.
NO(1)- This is Normally Open switch. When voltage applied, current flows in the coil
and generates a magnetic field, attract the pole from COM(common) to connect the
throw NO (Normally Open).
NC(2)- This is the Normally Closed Switch. When no voltage apply, no current runs in
the coil, the pole stay contact with the throw NC (Normally Closed).
COM- This is the common of the relay. If the relay is powered and the switch is closed,
COM and NO have continuity. If the relay isn't powered and the switch is open, COM
and NC have continuity.

This experiment we won't use high-power electrical appliances for safety, we use LED
lights and DC motors to complete the demonstration experiment instead.

- 117 -
Arduino Guide www.stemango.com

WARNING:Mishandling or incorrect or improper use of relays could result in


 serious personal injury or DEATH
 possible physical damage of the product
 faulty operation
 create serious/dangerous hazards.

Please seek professional and qualified assistance BEFORE you undertake ANY high
power projects using a relay. If you choose to follow the instructions in this tutorial,
you do so at your own risk.

Parts Required

Wiring

- 118 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 17.Make A Fan

Result
Relay stay off after code uploaded.
Relay jump to NO pin,DC motor and LED turn on when button pressed.

- 119 -
Arduino Guide www.stemango.com

Project 18 Transistor Control Toy Motor

In last project we actuated the motor by a relay. Why the DC motor can’t be directly
powered and control by Arduino ? The answer is the DC motor is likely to use more
power than an Arduino can only provide 40mA at 5V on its digital pins. We need to
insert a switch between Arduino and DC motor, this switch should be able to
switch the small current from Arduino digital output to high current and meet the
motor’s electrical requirement. In this project a Bipolar Junction Transistor (BJT) can
act as this digital switch we need.

There is other must-have electronic component wire to the DC motor.We will discuss
it later after we get to know some basics about DC motor first. The coming projects
we will have further introduction regarding interfacing with Arduino in different
ways.

In this project we used the 130 size bushed DC1-6V toy motor.

 Operating Temperature: -10°C ~ +60°C


 Rated Voltage: 6.0VDC
 No-load Current: 70 mA max
 No-load Speed: 9100 ±1800 rpm
 Loaded Current: 350 mA max
 Loaded Speed: 4500 ±1500 rpm
 Starting Voltage: 1.0
 Block/Stall Current: 400mA max

Hardware
Direct Current(DC) Motor is a two wire continuous rotation motor and
the two wires are power and ground. DC motor basically consist two
main parts. The rotating part is called the rotor and the stationary part
is also called the stator(case). When electric current flow through the
commutator, then pass through the windings(coil) in magnet field, the
energized winding and the magnets are misaligned and the rotor will
turn until it is very nearly straightened with the stator’s field magnets,
in other words, the magnet force generate a torque which turns rotor
to rotate with repect to the stator. As the rotor reaches alignment, the
brushes move to the next commutator contacts and energize the next
winding.

- 120 -
Arduino Guide www.stemango.com

Parts Required

As mentioned we need a transistor.But how to determin which type we use? The


important factors in our case are that its maximum voltage(40v) and its maximum
current (600 milliamp) are both high enough for our toy motor(for more detail please
check Datasheet –NPN Transistor MPS2N2222A)

- 121 -
Arduino Guide www.stemango.com

Transistor

Transistor is an active component and that is establishing in all over electronic


circuits. They are used as amplifiers and switching apparatus. There are exactly
thousands of different types.In this project we use a Bipolar Junction Transistor (BJT)
for only switch function,the other function amplify analog singal in analog circuit is
not used in this case. For current up to 500mA,the 2N2222A(NPN type) is a widely
choice,for current up to 5A you need a TIP120.

A diagrammatic form of n-p-n and p-n-p transistor is shown.

Diode

When a motor stops, there is the potential for a small


amount of current to be generated as the shaft
continues spinning. A diode placed in parallel with the
motor leads will keep any generated electricity from
damaging your circuit.

1N4001 diode is a rectifier diode allows only the flow of electrical current in one
direction. 1N4001 belongs to the series of 1NXXXX devices. Its an American standard
numbering system standard used for semiconductor devices. It can safely pass 1A
average current continuously, can protect against up to DC 50V reverse voltage.

In this case it is ideal for reverse polarity protection.

Wiring

- 122 -
Arduino Guide www.stemango.com

Battery
The above image shows 2pcs AA(1.5v) external
battery as external power. What we really tried while
writing this tutorial is 2pcs 3.7v li-on batteries in
series to directly power toy motor and the motor
turns very fast. You can try any 4pcs 1.5v battery in
series which makes 6v to test. In circuit the battery
symbol as right picture shown. IF YOU USE 9V-12V
external battery directly power Arduino,make sure to move the power wire from
Arduino 5V to Arduino VIN port. Otherwise it could burn the Arduino board. Or you
can use 9v battery with DC jack connect to Arduino power jack as the Arduino has 5v
regulator.

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 18.Transistor Control Toy
Motor

Result
The motor start spinning from minimum speed to max then slow down after button
pressed.

Not working?
Double check the transistor’s pinout with datasheet
Check the DC motor’s leads contact to breadboard well

- 123 -
Arduino Guide www.stemango.com

Project 19 Reed Switch Control Toy Motor

Is there a way to control the fan wireless? Before we get to the high tech and
expensive one like Bluetooth,IOT and so on.We would like to introduce the old and
useful way, magnetically actuation with reed switch.

Hardware
Introduction

Reed Swtich usually consists of two or three


reed ferrous contacts and filled with an inert
gas (e.g. nitrogen, helium, etc.) or a vacuum
glass tube, the glass tube parallel contact’s
end portions and left some space in order to
maintaine the switch in either normally open
or normally closed state. Most common used
reed switch are shown at the right picture.

How it works?

When the permanent magnet or a energized magnetic


field near the reed switch, the contacts will be pull
together and currnet can flow. Compared with the
electronic switch, reed has strong anti-shock load
capacity and other characteristics, high reliability. When we
want to start using the reed switch circuit, just take a small
magnet near the reed on it

- 124 -
Arduino Guide www.stemango.com

Parts Required

1N4007 Diode

1N4007 belong to 1NXXXX series, compare with 1N4001 they are meant for totally
different purposes especially for,
Maximum Forward current
Maximum Forward Voltage drop
Switching speed (applicable when data transfers involved, sometimes schottky diodes
preferred for this)
Maximum Reverse voltage.
In our project a 1N4001 is enough but 1N4007 is very common used one so we
would rather to use it for your other future projects.

MOSFET
As explained in last project, BJT is current-controlled
device. Where MOSFET (metal–oxide–semiconductor
field-effect transistor) is voltage-controlled, both used
for switching and amplification appliction. When
choosing which one to use in your project, one needs
to consider some of the main factors: circuits,power
level ,switching speed, efficiency, cost etc.

- 125 -
Arduino Guide www.stemango.com

Difference between BJT and MOSFET

BJT MOSFET
Digital and analog circuit Commonly used More commonly used

Power Level Low current High voltage

Switch speed Fast Faster

Draw Current Little Very little

Cost Cheaper Costlier

The MOSFET has “gate“, “Drain” and “Source” terminals instead of a


“base”, “collector”, and “emitter” terminals in a bipolar transistor. When gate applied
with voltage, it generates an electrical field to control the current flow through the
channel between drain and source, and there is no current flow from the gate into
the MOSFET as it has very high input impedance.

A diagrammatic form of p channel and n channel transistor is shown.

- 126 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 19.Reed Switch Control
Toy Motor

Result
Put the magnet close to the reed switch, the motor start spinning at certain speed.

Not working?
Double check the transistor’s pinout

- 127 -
Arduino Guide www.stemango.com

Project 20 L293D 2WD Robot

Porbably creating a robot with Arduino is one of the most popular projects. Good
news is there is easy way to build one with current knowledge you have after you
learn previours tutorials.Sure you need to make the case or body for your robot, our
ultimate goal in this project is control two motors’ speed and direction with
joystick,Arduino PWM pins,plus a L293D motor driver chip, an easy understand
motor driver chip.

When joystick pushed up, the robot move forward whereas move backward when
pushed down.It turn left when joystick push to left, the logic is right motor’s speed is
increased while left motor’s decreased.

Hardware
Arduino’s digital pins can’t reverse the voltage, whihch means the motor would go
only one direction. So one of the solutions is using a H-Bridage motor driver chip to
allow the current flow back and force. You can make a H-Bridge by using two
transistors and other components (please google for further detail). In this case we
use L293D chip for easier circuit and less components.

Below graphic shows how a H-bridge chip work.

- 128 -
Arduino Guide www.stemango.com

L293D Motor Driver Chip

The L293D is designed to provide bidirectional drive currents


of up to 600 mA (per channel) at voltages from 4.5 V to 36 V
(only at pin 8!). It can control two DC motors indenpently or
one four-wire stepper motor. For two DC motors you can
control the direction and speed of the motors by using six Arduino pins.

The logic can be expressed in following tabular form.

Motor Enable A Enable B IN1 IN2 IN3 IN4 Rotate

Motor A H / L H / / Backward

H / H L / / Forward

Motor B / H / / L H Backward

/ H / / H L Forward

Remember that if you use other motors instead of ours, make sure the motor’s stall
current is under L293D max draw current 600mA.Otherwise it could burn the
electronics. The IC Sometimes turns extremely hot, you can put a heat sink on the
chip if you concern about the heat.

Joystick

Joystick is mainly instructed with two 10k potentiometer


and a key switch is activated when you press down on
the joystick handle.The module has 5 pins: Vcc, Ground, X,
Y, SW.

- 129 -
Arduino Guide www.stemango.com

Parts Required

Wiring
First you need to wire the L293D chip to Arduino and motors. Check below graphic
for L293D pin assignment.

- 130 -
Arduino Guide www.stemango.com

1. Enable (1) connected to 5V


2. Input (1) connected to Motor logic pin 1
3. Output (1) connected to Motor terminal 1
4. Ground
5. Ground
6. Output (2) connected to Motor terminal 2
7. Input (2) connected to Motor logic pin 2
8. Vs connected to motor power supply (ex. 5V or higher power like 9V, up to 36V)
9. Enable (2) connected to 5V
10. Input (3) connected to Motor logic pin 3
11. Output (3) connected to motor terminal 3
12. Ground
13. Ground
14. Output (4) connected to Motor terminal 4
15. Input (4) connected to Motor logic pin 4
16. Vss connected to 5V for chip’s logic

- 131 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 20.L293D 2WD Robot

The raw value Arduino read from joystick is in range of 0-1023 as Arduino ADC took
part in.In project 5 we show PWM control LED brightness which means we can
control the speed of the motor also, we need to apply analogWrite function on
L293D enable pins. The speed of the motor depends on value that was passed to the
analogWrite function. Remember the value can be between 0 and 255. If you pass 0,
then the motor will stop and if you pass 255 then it will run at full speed. If you pass
a value between 1 and 254, then the speed of the motor will vary accordingly. In
code you can see we used map function to convert the 0-1023 range to 0-255 range.
Result
Joystick in home positon(center) the motors will be disabled.
Pushing the joystick forward (up) should move forward.
Pulling the joystick backward (down) should move backward.
Push the joystick to one side the car should respond by moving in that direction.
Not working?
While prototyping on breadboard, the leads from DC motors could be loosen, check
and insert them into breadboard harder.

Sometimes Arduino board will disconnect from the computer, try push the reset
button on Arduino board after plug into computer USB port or un-plugging and then
re-plugging it into your USB port.

- 132 -
Arduino Guide www.stemango.com

Project 21 Moving A Servo


DC motor runs continuously at a high RPM (revolutions
per minute). These revolutions of the motor shaft can
not be controlled to a specific angle, but you can
control the speed. A servo is also a motor. It controls
the position of the motor by a feedback system. The
servo motor position can be controlled more precisely
than typical DC motors, that is why they are designed for more precise tasks where a
motor position needs to be clear precisely like moving a robotic arm or controlling
the door bolt on a doorlock or robot leg within a particular range.

Hardware

Generally, the servo motor is an association of four things, namely a DC motor, a


control circuit, a gearing set, and also a potentiometer usually a position sensor. As
the motor rotates, the potentiometer's resistance changes, so the control circuit can
precisely regulate how much movement there is and in which direction

They have three wires like power, GND, and control(signal).


Power to these motors continually applied, with the servo
motor control circuit changing the draw to drive the servo
motor.

- 133 -
Arduino Guide www.stemango.com

PWM is used to control the signal of a servo motor. But, unlike DC motors it’s the
period of the positive pulse that controls the position, somewhat than speed, of the
servo shaft. There is a minimum pulse, a maximum pulse, and a repetition rate. A
servo motor can usually only turn 90° in either direction for a total of 180°
movement. The servo control pulse is typically recurrent every 20 ms, fundamentally
telling the servo motor where to go, even if that means remaining in the similar
position. For example, a 1.5ms pulse will make the motor turn to the 90° position.
Shorter than 1.5ms moves it in the counter clockwise direction toward the 0°
position, and any longer than 1.5ms will turn the servo in a clockwise direction
toward the 180° position.

Parts Required

- 134 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 21.Moving A Servo

Result
After uploading the sketch, turn the pot and you will see servo sweeping to 150
degrees.
Not working?
The color of the servo wires could be mess between organge and red sometimes.

- 135 -
Arduino Guide www.stemango.com

Project 22 Password Door Lock

This project we’ll see how to use a


membrane keyPad to prototyping(yes, do
not try to use this as your home lock) a
lock system with a servo and Arduino.

Keypads are largely used in security and


keyless lock system, or everything that
needs a numeric combination. This lock
system will activate a servo when the
right password combination is pressed on
the KeyPad.

Hardware

The KeyPad used in this guide is made of membrane. The


characters are printed onto a flexible polymer film that
covers the entire keyboard, upon which a soft rubber
dome is produced. To select a key, the dome is depressed
through perforations in the middle layer to contact the
bottom membrane layer, where a short circuit is completed and registered by the
device and associated controllers or hardware. It’s very cheap and very simple to
interface with Arduino, but also with other microcontrollers.

- 136 -
Arduino Guide www.stemango.com

Parts Required

Wiring

- 137 -
Arduino Guide www.stemango.com

Sketch
Keypad library need to be installed first.

This sketch is very simple, it will take an input from the user, and if the password
entered is wrong, the red led will turn on and the servo won’t move. Instead, if the
password is right, the green led will turn on and the servo will rotate.

To open the code go to: File > Sketchbook >STEManGo Electronics > 22.Password Lock

Result
Press 123 on keypad and servo switch to certain angle,green led turn on.
Try anyother number instead of 123,red led turn on and servo no resonse.
Not working?

Check with code and follow image, make sure the pins on keypad to Arduino is right.

- 138 -
Arduino Guide www.stemango.com

Project 23 Stepper Motor

A stepper motor is fundamentally a servo motor that


uses a different method of motorization. As its name
implies, the stepper motor does not rotate in a
continuous fashion like a conventional DC motor but
in discrete steps. It is also an electromechanical
actuator that converts a pulsed digital input signal
into a discrete (incremental) mechanical movement.

Hardware

It is important to understand the inside of a steppter motor,you would easily


understand how it works. Like any electrical motor, stepper motor has a stator and
rotor. Here we take 28BJY-48 as example. Stator is mainly made of two copper coils
and teeth,coil 1 has four leads which wire to yellow and blue and two leads wire to
common 5V DC pink, so as the coil 2 except two leads wire to pink and orange. That
means there are totally four half coils wire to four colors’ wire. Each half coil also
called “phase”.

28BJY-48 has 4 layers of teeth, the layer 1 2 and 3 teeth are surrounded by coils,
layer 4 teeth build with the bottom of the housing. Each layers has eight teeth which
makes the whole stepper motor 32 teeth.The rotor is constructed with 16 North pole
and 16 South pole permanent magnets on a plastic body. The last part is the gear
plate that holds four gears sits over the rotor and under the cap.

28BJY-48 has 64:1 ratio.But what does it mean and what it stands for? The first and
in the center gear is the rotor shaft has 9 teeth.

- 139 -
Arduino Guide www.stemango.com

Gear 1: 9 teeth coupled with Gear 2: 32 teeth


Gear 2: 11 teeth coupled with Gear 3: 22 teeth
Gear 3: 9 teeth coupled with Gear 4: 26 teeth
Gear 4: 8 teeth coupled with Gear 5: 24 teeth

So gear ratio as below:

32/9 = 3.55
22/11 = 2
27/9 = 3
24/8 = 3

Multiply the gear ratios together:

3.55 x 2 x 3 x 3 = 63.9 ≈ 64.

That means the rotor shaft must turn sixty four full rotations for the keyed motor
shaft to turn once.

By energizing each phase(coil) in sequence, the teeth on stator and rotor’s magnet
tips(one of the 16 north/south pole) generate a strongest magnet field. The trick to
turn this alignment into a rotation is by aligning the stator teeth in a way that each of
them is certain tooth distance. The misalignment allows to pulls the rotar certain
tooth distance forward if we applied the magnetic filed to the next magnet.

- 140 -
Arduino Guide www.stemango.com

The certain tooth distance depends on PWM singal Arduino send to the stepper
motor. For example, when Arduino tells the stepper motor in full stepping mode, it
takes 32 steps for the magnetic rotor to complete a full 360° rotation, In this case,
the certain tooth distance is 1 tooth distance which is 1 step, rotor rotate 11.25° each
step, the rotor shaft turs 64 times/step. So it takes 32 x 64 = 2048 steps to turn keyed
motor shaft finish a rotation.Each step turns 360/2048=0.18°.

So as in half stepping mode, it takes 64 x 64 = 4096 steps, each step turns


360/4096=0.08°.

This is where the accuracy of a stepper motor comes into effect.

ULN2003A Module

There are two types of steppers, Unipolars and Bipolars, and it is very important to
know which type you are working with. For each of the motors, there is a different
circuit.What we used here is a 5 wire unipolar stepper motor which DO NOT require
a h-brigde to reverse polarity.

Instead,we use a transistor for each phase and a block current diode to prevent
voltage spikes as explained early in DC motor project. There is an IC we can use that
have all the required components on board. This example uses an ULN2003A chip to
drive a unipolar 5 wire stepper motor.The ULN2003A is an array of seven NPN
Darlington transistors capable of 500mA, 50V output. It features common-cathode
flyback diodes for switching inductive loads.

- 141 -
Arduino Guide www.stemango.com

Parts Required

- 142 -
Arduino Guide www.stemango.com

Wiring

Sketch
To better understand the stepping method,the sketches show three different ways
to control the stepper motor.

First one is wave driving.When delay time set to like 250ms, you can clearly see each
phase work at a time. The improved version of code use arrays.

To open the code go to: File > Sketchbook >STEManGo Electronics > 23.Stepper Motor

wave_drive
wave_drive_with_arrays

Second method is full stepping which generate strongest torque,runs two phases at
a time.Code is

full_steppping_with_arrays

Third method is half stepping generate smallest step angle and medium torque, one
or two phases at a time.Code is

half_stepping_with_arrays

- 143 -
Arduino Guide www.stemango.com

Result
Observe the speed and direction you should find motor shaft rotates 360 degree and
then reverse.

When you apply the wave_drive code, try to revise the delay time to 250ms and you
should see the corresponding LED on the motor driver module blink in order.
Not working?
Check the wiring from stepper motor to Arduino.

- 144 -
Arduino Guide www.stemango.com

Project 24 Rotary Encoder Control Stepper Motor


Since stepper motor is an good option for accuracy control,when we need digital
device to control the stepper motor,first thing you may come to mind is a switch or
potentiometer. That is good option too but not as accurate as a rotary encoder.Let’s
build one to control the movement along with turning the rotary encoder, and will also keep
track of how much steps we have taken.

Hardware
Introduction

A rotary encoder, also called a shaft encoder, is an electro-mechanical device that


converts the angular position or motion of a shaft or axle to an analog or digital
signal.

There are two main types: absolute and incremental (relative). The
output of incremental encoders provides information about the
motion of the shaft, which is typically further processed elsewhere
into information such as speed, distance and position.

The particular rotary encoder that we will use in this tutorial is an


incremental quadrature rotary encoder and it’s the simplest position
sensor to measure rotation.

There are alos other types encoders use sensing technology. Below image shows the
difference in case you mistake any of them to another.

Quadrature Encoder
Incremental
Relative Rotary Encoder
Output
Signal
Absolute

Rotary
Encoder
Magnetic

Sensing
Technology Optical

Laser

- 145 -
Arduino Guide www.stemango.com

Rotary encoders are used in many applications that require precise shaft unlimited
rotation—including industrial controls, robotics, special purpose photographic lenses,
computer input devices (such as optomechanical mice and trackballs), controlled
stress rheometers, and rotating radar platforms.

How it works?

The typical assembly of an incremental encoder consists of a spindle assembly, PCB, and cover.
The PCB contains a sensor sense movement in either direction, by detecting holes or marks as
they move past 2 positions. The encoder has a disk(grey color) with evenly spaced contact
zones(white color) that are connected to the common pin C and two other separate contact pins
A and B, as illustrated below.

When the disk will start rotating step by step, the pins A and B will start making contact with the
common pin and the two square wave output signals will be generated accordingly. The output
can be a single line of pulses (an “A” channel) or two lines of pulses (an “A” and “B” channel) that
are offset in order to determine rotation.

When the grey disc spins clockwise, the changes are first detected by pin A, and then by pin B.
When it spins counterclockwise, pin B is first to detect changes. This scheme is called "quadrature
encoding" because the waveforms detected by the 2 pins are 90 degrees out of phase.

- 146 -
Arduino Guide www.stemango.com

Pins out
CLK (Data Output A) - Generating interrupts using CLK signal which is PinA in our
example
DT(Data Output B) - Reading DT signal which is PinB in our example

Encoders have 2 signals, which must be connected to 2 pins. There are three options.

1. Best Performance: Both signals connect to interrupt pins.


2. Good Performance: First signal connects to an interrupt pin, second to a non-interrupt
pin. ( what we use in this example)
3. Low Performance: Both signals connect to non-interrupt pins, details below.

Our encoder module will activate the on-chip pullup resistors with two 10Kohm pullup resistors
may provide a better signal.

- 147 -
Arduino Guide www.stemango.com

Parts Required

Wiring

- 148 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 24.Rotary Encoder
Control Stepper Motor

Result
After code uploaded, rotate the knob and observe the shaft motor of the stepper
motor, it move while you keep rotating.

Press the switch on the rotary encoder module, you should see the motor move back
to the starting position

- 149 -
Arduino Guide www.stemango.com

Project 25 Light Sensor

In this project, we will make an LED light that can adjust itself flash speed according
to the light dependent resistor (LDR) or photo resistor around it. When it is dark, the
photo resistor detects the change and flashes the light slower, and vice versa.
Hardware
A photo resistor is a semiconductor device has a (variable)
resistance that changes with the light intensity that falls
upon it. This allows them to be used in light sensing
circuits and that is why it is also named light sensor. An
LDR initially has a very high resistance. But, as light falls
on it, the resistance will drop, allowing more current
through.

The resistance of an LDR may typically have the following resistances:

Daylight= 5000Ω
Dark= 20000000Ω

In this circuit, the input voltage Vin(5V) is connected to 2 resistors. Our LDR is connected
in series with a 1KΩ Resistors and the input into Analog Pin 0 is between these 2 resistors. This is what
is known as a voltage divider.

In project 5 we leanred that how potentiometer work as a voltage divider.Similarly a voltage divider
which is a circuit consisting of two resistances across a voltage supply.In our circuit, R1 is the 10k
resistor and R2 is the LDR. We are providing 5 volts into the circuit so letʼs work
out what values we will get out.

To work out the Vout value we use following equitation:

Vin

- 150 -
Arduino Guide www.stemango.com

For this project it is better to use a fixed resistor ranging from 1k to 10k, otherwise
the voltage dividing ratio is not obvious. This is why in this project we used a 10k
resistor for R1.
You can use a multimeter to measure the resistance from the LDR in different conditions.
When LDR covered by finger,the measured resistance reach 8000 Ω.So

Vout=8000/9000 x 5 Vout=4.4V

When LDR has light fall on it,the measured resistance reach 200Ω.So

Vout=200/1200 x 5 Vout =0.83V

As you can see, as the resistance of the R2 decreases, the voltage out of the voltage divider decreases
also, making the value read in from the Analog Pin lower and therefore decreasing the delay making
the LED flash faster.

Parts Required

- 151 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 25.Light Sensor

Result
After uploading the code, you can cover your finger on LDR, the LED flash slower. If
you set a flashlight on the LDR the LED should flash fater.

- 152 -
Arduino Guide www.stemango.com

Project 26 Flame Sensor

We continue to play with sensors, this project we will work with the flame sensor.

Hardware
Flame sensor (i.e., the infrared receiving triode) are specially used to search for the
fire source in robot, this sensor is particularly sensitive to the flame.

Infrared is very sensitive to flame, use special infrared receiving tube to detect fire,
and then turn the flame brightness into high and low
level signal, input the signal to the central processor,
the central processor will react according to the
change of signal. The angel of the flame sensor we
use in this experiment is 60°

The voltage value from analog port is changing by the


distance between flame and sensor. A AVO meter
read about 0.3v without flame approached. When
flame is approaching,voltage reading is about 1.0 V,
closer to the flame, the bigger the voltage is.Before
we start, we can store a value (voltage) i.e “I”, then
keep reading the voltage value from analog port, i.e
“j”,make the differential as “k” = j-I and compare with 0.6v. Set the buzzer to make a
sound when the differential >0.6v, if not, buzzer not make sounds.
Parts Required

- 153 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 26.Flame Sensor

Result
Upload the sketch and make a flame over the sensor top in 60°range, and the buzzer
will make sound.

- 154 -
Arduino Guide www.stemango.com

Project 27 Voice Recognition


Virtual assistant is getting involved in more and more mobile device nowadays. We
will build one simple voice recognition project with the microphone or sound sensor
module, simply working like this, say specific command “on” and “off” to turns led on
or off.
Hardware

Introduction

Voice or speech recognition is the ability of a machine or program to


receive and interpret dictation, or to understand and carry out spoken
commands.Similar with computer, for use with Arduino analog audio
must be converted into digital signals. This requires analog-to-digital
conversion. In order to get voice input you need a condenser mic with
an operational amplifier (op-amp). The microphone module will use is
the module with LM393 Op-amp chip and electret condenser.

Specification:
Analog Output
Power by DC 5V
With 3mm screw hole
With power indicator
With indicator for comparator
With sensitivity adjust trimpot
Parts Required

- 155 -
Arduino Guide www.stemango.com

Wiring

Sketch
This code require library”uSpeech.h”

To open the code go to : File > Examples>uSpeech>27.Voice recognition

- 156 -
Arduino Guide www.stemango.com

Code Explanation

signal voice(A0);

This line creates a new µspeech signal object. The signal object is where all of
µspeech's logic resides.

voice.calibrate();

This line calibrates the voice object so as to remove noise and interference from the
system.

char p = voice.getPhoneme();

This returns the closest phoneme guess to the real phoneme, if it is too quiet the
system will return ' ' and 'm' if there was an error. The rest of the code goes on to tell
if there was the "sh" sound in the word, if there was its time to turn off the LED, if
there wasn't it means the person said "on".

Go to the uSpeech library wiki to check more info.


https://github.com/arjo129/uSpeech/wiki

Result
After code loaded, say “on” toward the microphone module, the LED should be
turned on, say “off” to turn it off.
Disclaimer
This is just a simple project with less accuracy, not recommend for professional
usage…

- 157 -
Arduino Guide www.stemango.com

Project 28 Temperature and Humidity Sensor

We are going to build something smarter and useful in this project. We start with a
temperature and humidity sensor,ultimately we will build one indoor climate
monitor with color display as we shall see.
Hardware

Introduction

The DHT11 measures relative humidity and temperature. Relative humidity is the
amount of water vapor in air vs. the saturation point of water vapor in air. At the
saturation point, water vapor starts to condense and accumulate on surfaces
forming dew.

The saturation point changes with air temperature. Cold air can hold less water
vapor before it becomes saturated, and hot air can hold more water vapor before it
becomes saturated.

Relative humidity is expressed as a percentage. At 100% RH, condensation occurs,


and at 0% RH, the air is completely dry.

How it works?

The DHT11 detects water vapor by measuring the electrical resistance between two
electrodes. The humidity sensing component is a moisture holding substrate with
electrodes applied to the surface. When water vapor is absorbed by the substrate,
ions are released by the substrate which increases the conductivity between the
electrodes. The change in resistance between the two electrodes is proportional to
the relative humidity. Higher relative humidity decreases the resistance between the
electrodes, while lower relative humidity increases the resistance between the
electrodes.

The DHT11 measures temperature with a surface mounted NTC temperature sensor
(thermistor) built into the unit.

The DHT11 uses just one signal wire to


transmit data to the Arduino. Power comes
from separate 5V and ground wires. A 10K
Ohm pull-up resistor is needed between the
signal line and 5V line to make sure the signal
level stays high by default.

- 158 -
Arduino Guide www.stemango.com

Specification
 Humidity Range: 20-90% RH
 Humidity Accuracy: ±5% RH
 Temperature Range: 0-50 °C
 Temperature Accuracy: ±2% °C
 Operating Voltage: 3V to 5.5V

The DHT22 is similar to the DHT11 and has greater accuracy. However, this library is
not suitable for the DHT21 or DHT22 as they have a different data format. Check
DHTlib for support of these sensors.

Parts Required

Wiring

- 159 -
Arduino Guide www.stemango.com

Sketch
Important: Install the library dht.h with this version, it located In project 28 folder.
// AUTHOR: Rob Tillaart
// VERSION: 0.1.25

To open the code go to: File > Sketchbook >STEManGo Electronics > 28.Temperature and
humidity sensor>DHTtester

Result

Upload example sketch

1. Open the DHTtester example in the DHT category of examples


2. Upload example sketch
3. Open Serial Monitor
4. Exhale on the sensor to increase humidity and verify that the humidity level
rises

- 160 -
Arduino Guide www.stemango.com

Project 29 Liquid Crystal Display 1602

Last project we read dht11 sensor value from serial monitor on computer. This
project we introduce one of the most common used liquid crystal display 1602 to
show the sensor value.

First we will test the display. This test use Arduino direct drive LCD1602.
Hardware

Introduction

LCD1602 belong to Character LCDs, they are extremely common and a fast way to
have your project show status messages. They are ideal for displaying text. They can
also be configured to display small icons but the icons must be only 5x7 pixels.
Here is an example of our character LCD, 16 characters by 2 lines with icon.

The 1602 display use HD4480 controller, most of the manufacturers use the
compatible IC, so they are basically same.

Specification
Display Capacity : 16 x 2 characters
Chip Working Voltage : 4.5~5.5V
Working Current : 2.0mA(5.0V)
Module Best Working Voltage: 5.0V
Character Size : 2.95×4.35(W×H)mm

- 161 -
Arduino Guide www.stemango.com

Pin Description
VSS power supply for the module,use 5v.
VDD ground pin for the module.
VO is for adjusting contrast ratio by a 10kΩ potentiometer in this case.
RS(Register Select) selects command register when low; and data register when high
RW(read/write) Low to write to the register; High to read from the register
E(Enable) Sends data to data pins when a high to low pulse is given
D0—D7 Eight-bit two-way parallel bus data pins for sending command and data
A is backlight positive pole.
K is backlight negative pole.

Which interface you should choose?

The LCD soldered with I2C module save I/O and wiring, if you have many other
external devices connect to Arduino board you should consider this one. The one
with no I2C module solder on is not a good idea for kids as it involve in using a
soldering iron. And consider the cost if you don’t have one.

I2C (IIC) Protocol

In order for Arduino and external device to swap information, they must share a
common communication protocol. There are many protocols such as USART, UART,
RS232, USB, SPI, I2C, TTL, they all serial protocols, each of these serial interfaces can
be sorted into one of two groups: synchronous or asynchronous. Examples of
synchronous interfaces include SPI, and I2C.
We will talk about these two as we would use deivces using these protocols in
coming projects. Plus there are many I2C and SPI libraries reday for use online.Both
requires two signal wires to exchange information.

I2C(Inter-Integrated Circuit)

If you got the display with IIC module, that would be


save I/O from Arduino and with potentiometer on the
back of the IIC module. Because I2C bus physically
consists of only 2 active wires – SDA(serial data line)
and SCL(serial clock line).Arduino board use analog pin
A5 for SCL which provide clock signaland analog pin A4
for SDA which transfer data. Every device connected to
the bus has its own unique device address, no matter
whether it is an MCU or RTC module. Each of these
chips can act as a receiver or transmitter, depending
on the functionality.
With this I2C interface LCD module, you only need 2 lines (I2C) to display information.
The module has a control IC pcf8574a.You can find datasheet in project #27 folder.

- 162 -
Arduino Guide www.stemango.com

Parts Required

Wiring(with no I2C module)


LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD VCC pin to 5V
10K Potentiometer:
ends to +5V and ground ,the other end to LCD VO pin (pin 3)

- 163 -
Arduino Guide www.stemango.com

Wiring(with I2C module)


LCD IIC module GND – Arduino GND
LCD IIC module VCC – Arduino 5V
LCD IIC module SDA – Arduino A4
LCD IIC module SCL – Arduino A5

Sketch(with no I2C module)


LCD1602 require library “LiquidCrystal” but it is built in Arduino IDE so no need to
install.

To open the test code go to : File > Examples>LiquidCrystal>Helloworld

Sketch(with IIC module)


If you have the LCD with IIC module soldered on the back, you should install and use
library “LiquidCrystal_I2C”.

Step1: Run the code I2C Address scanner first


To open the code go to : File > Examples>LiquidCrystal_I2C>I2C_Address_Scanner

Step2: After you found the I2C address, copy it and open another example sketch.
To open the code go to : File > Examples>LiquidCrystal_I2C>Helloworld
*My example shows address 0x3F.

Step3: replace the I2C address by pasting the copied characters.


LiquidCrystal_I2C lcd(0x3F,20,4); // set the LCD address to 0x3F for a 16 chars and 2 line
display

- 164 -
Arduino Guide www.stemango.com

Result
Upload the code and you should see it display character
“Hello! STEManGo I ♥ Arduinos”, if not press the reset button on Arduino and you
will see in 2 seconds.
Note: If you can hardly see the characters on screen, twist the potentiometer like
below picture shown for contrast adjustment. Use a screwer to twist the blue
trimpot on the back if you have a IIC module on the display.

- 165 -
Arduino Guide www.stemango.com

Project 30 Temperature and Humidity Monitor


Now let’s get the DHT11 sensor and LCD1602 together to make a temperature and
humidity monitor. You can read the sensor value via the display!
Parts Required

Wiring

- 166 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics >30.Temperature and
Humidity Monitor

Result
Upload the code and you should see it display character” Humidity & temp”, then
“Starting.....”,finally you would see the temperature and humidity data.

Not working?

If you try to Verify and you see this:


error: 'LiquidCrystal_I2C' does not name a type
this means you do not have the library installed correctly.
If display is not lit up check the wiring to Arduino power.
If lit up but not show anything on the display, run the I2C scanner

- 167 -
Arduino Guide www.stemango.com

Project 31 Real Time Clock


A real-time clock(RTC) is a a battery-powered clock that keeps track of the current
time and that can be used in order to program actions at a certain time.

Althought Arduino’s brain ATMEGA328P has built-in internal clock called millis(), but
most Arduino projects are designed to be used away from a computer. Once the
computer connection isn’t there, your unpowered Arduino don’t know the current
time. And the time needs to be reseted after power on again.

If your project has anything to do with needing the time you would need a real time
clock chip to keep and sync the time with your computer even unplug from
computer.

To do so, we use the DS1307 Tiny RTC module to set the time base on computer and
check back the time if match computer after Arduino unplug from compute for
certain time.

Hardware

DS1307 real time clock I2C module(Tiny RTC I2C Module) is a simple breakout board can
accurately keep track of seconds, minutes, hours, days, months, and years for almost a decade, so
your microcontroller doesn’t have to. It’s the perfect component for clocks, calendars, or any
other time-keeping project.

There are different kinds of RTC modules available in the market. We are using the most common
RTC module comes named DS1307 IC. The other IC version is DS3231. DS3231 and DS1307 are
functionally the same, except that DS3231 has a built-in temperature compensated crystal, which
makes it more accurate, but also the chip is much larger. They both use the same I2C address and
libraries that work forDS1307 should work for DS3231 too.

- 168 -
Arduino Guide www.stemango.com

Note: It is illegal to ship battery via air so our provided module came with no battery. The battery
type is CR2032 button battery.You can easily find it in local store.

*This module needs a soldering iron to weld the male header on the module.Please
seek professional help or under adsult supervisor if you are a kid.

Parts Required

Wiring

- 169 -
Arduino Guide www.stemango.com

Sketch
*This project require library“RTClib”.

Step 1: Setting the Time


To open the code go to: File > Sketchbook >STEManGo Electronics > 31.Real Time Clock
Set_time_on_DS1307_RTC

Result
Once code uploaded, open serial monitor and you should see the time is sync with
computer. A few seconds delay is normal.

- 170 -
Arduino Guide www.stemango.com

Step 2: Verifing the Time


Here is the key step to test if the RTC module works as it should and the battery as
well.
To open the code go to: File > Sketchbook >STEManGo Electronics > 31.Real Time
Clock>Verify_time_on_DS1307_RTC

Result

Uploaded the code and unplug the Arduino from computer for like 5 minutes or

more. Plug it back and open serial monitor. You should see the time is still updating
with computer!

Not working?
If the code with errors when uploading, make sure the library “RTClib” is installed.
If the code has no issue but serial monitor has nothing to display, check if the SCL and
SDA pin connect to Arduino A5 and A4.

- 171 -
Arduino Guide www.stemango.com

Project 32 Four Digit 7 Segment Display Clock


This project we use the Arduino and DS1307 RTC module to set time on a four digital
common anode display. In project 5 we

Hardware

4-digit display has 12 pins. When the dot down and stay put, left bottom
one is #1, the others are in counterclockwise order, top left corner one is
#12.

Below pictures shows the pin assignment.

- 172 -
Arduino Guide www.stemango.com

Parts Required

- 173 -
Arduino Guide www.stemango.com

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > Four Digit 7 Segment Display
Clock

Result
After code uploaed, you should see the time sync with computer.
Not working?
Be aware of the pins’ order,the pin#1 start from most left down side, the pin#7 is the
most right up side.

- 174 -
Arduino Guide www.stemango.com

Project 33 Barometric Temperature Altitude Monitor

Today we will interface a 3 in 1 barometric,temperature, altitude sensor with Arduino


and display data with a 2004(20 by 4 line)character LCD. In order to display all 4
measurements with completed information from the sensor, we use LCD2004 with
I2C interface in this project. You can use the LCD1602 if you want, we do this also for
adding the varity in case someone already has the 2004 one.
Hardware

The BMP180 is the new digital barometric pressure sensor of Bosch Sensortec, with a
very high performance, which enables applications in advanced mobile devices, such
as smartphones, tablet PCs and sports devices. It follows the BMP085 and brings
many improvements, like the smaller size and the expansion of digital interfaces.

The ultra-low power consumption down to 3 μA makes the BMP180 the leader in
power saving for your mobile devices. BMP180 is also distinguished by its very stable
behavior (performance) with regard to the independency
of the supply voltage.

Applications
- Indoor navigation
- GPS-enhancement for dead-reckoning, slope detection, etc.
- Sport devices, e.g. altitude profile
- Weather forecast
- Vertical velocity indication (rise/sink speed)

- 175 -
Arduino Guide www.stemango.com

Parts Required

Wiring

- 176 -
Arduino Guide www.stemango.com

I2C is a bus, so like-named signals are connected together. The addressing scheme
allows the microcontroller to select which device it's talking to. In this case the
BMP180 and LCD2004 has different I2C address, they can connected together to
UNO.

Sketch

*This sketch require”Adafruit_BMP085” library.


To open the code go to: File > Sketchbook >STEManGo Electronics > 33.Barometri Temperature
Altitude Monitor

Result

You can get a more precise measurement of altitude, if you know the current sea
level pressure which will vary with weather and such. If it is 1015 millibars that is
equal to 101500 Pascals.

- 177 -
Arduino Guide www.stemango.com

Project 34 Driving Nokia 5110 LCD

You probably tired of the LCD1602 if you get serious about displaying
information.Nokia 5110 LCD can do a lot more than a 1602. It can display SIX lines of
data, with a minimum of 12 characters, and even has a graphic ability.

Hardware

Introduction

These displays are small, only about 1.5" diameter, but very readable due and comes
with a backlight. This display is made of 84x48 individual pixels, so you can use it for
graphics, text or bitmaps. These displays require only a few digital I/O pins and are
fairly low power as well.

Nokia 5110 LCD Pin Function

DIN/MOSI = Serial data in


DC/MISO= Serial data out.Mode select, select between command mode (low) and data mode
(high).
CE/SCE/SS/CS= Chip select
CLK/SCLK/SCK= serial clock
RST=Reset
BL/LED=Backlight
GND=Ground
VCC=Positive power suppley range from 3-5v

- 178 -
Arduino Guide www.stemango.com

To drive the display, you will need 3 to 5 digital output pins (depending on whether
you want to manually control the chip select and reset lines). Another pin can be
used to control (via on/off or PWM) the backlight.*More details please check
datasheet” Datasheet - Nokia5510LCD.pdf”

Built into this LCD is a Philips PCD8544 display controller, which converts the massive
parallel interface of the raw LCD to a more convenient serial one. The PCD8544 is
controlled through a synchronous serial interface similar to SPI and dose require
exclusive access to the pins used. There are clock (SCLK) and data (DN) input lines,
and an active-low chip select (SCE) input as well.

SPI(Serial Peripheral Interface) Protocol

Nokia 5110 LCD use SPI interface.SPI is quite straightforward – it defines features any
digital electronic engineer would think of if it were to quickly define a way to
communicate between 2 digital devices. Compare with I2C, the SPI runs at a higher
rate.And it has separately input and output connection, so it can send and receive
data at the same time.It use one additional line per device to select the active device.

SPI is a protocol on 4 signal lines .Below shows the pin functions.


DIN/MOSI = Serial data in
DC/MISO= Serial data out.
CE/SCE/SS/CS= Chip select
CLK/SCLK/SCK= serial clock

Parts Required

- 179 -
Arduino Guide www.stemango.com

Wiring
RST -- D12 / CE -- D11 / DC -- D10 / DIN -- D9 / CLK -- D8

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > 34.Driving Nokia 5110 LCD
>Driving

- 180 -
Arduino Guide www.stemango.com

Project 35 Loading Graph on Nokia 5110 LCD

This program will show you how to load custom graphics on 5110 display. Used
hardwares same as last projects,but you will need some softwares, paint.net for
making custom graphic and LCDAssitant for transfer the graphic into data arrays and
NotePad++ for opening the array.Program creates files that can be used with any C
compiler for AVR, ARM, PIC, 8051 and other microcontrollers.

Make BMP image


Open paint.net to create new file

Set pixel width and height 84x48.

You can create any shape and character. Here we show how to use text to create our
product logo STEManGo.

- 181 -
Arduino Guide www.stemango.com

Save file as xxx.bmp format then BMP image is done.

- 182 -
Arduino Guide www.stemango.com

Convert BMP image to data arrays


Open LCD Assistant software and click File --- Load image
The software located in folder “35.Loading Graph on Nokia 5110 LCD”

- 183 -
Arduino Guide www.stemango.com

Use default setting and save output.

Open the logo file with NotePad++.

- 184 -
Arduino Guide www.stemango.com

Open graphic.c which is empty.

Copy the data arrays from logo and paste on graphic.c, and add “PROGMEM” in front
of “=” to store data in flash (program) memory instead of SRAM.

- 185 -
Arduino Guide www.stemango.com

Include avr/pgmspace.h library ( built-in features of AVR-GCC and AVR-LIBC which


underlie Arduino. )

Make sure graphic.c file and Arduino sketch is under same folder.

- 186 -
Arduino Guide www.stemango.com

Wiring

Sketch
This project require library ”LCD5110_Graph”.
To open the code go to: File > Sketchbook >STEManGo Electronics > 35.Loading Graph on Nokia
5110 LCD

Result
The final output looks like below,you can design much better graphic in the future.

- 187 -
Arduino Guide www.stemango.com

Project 36 Ultrasonic Distance Sensor

This project we introduce a HC-SR04 ultrasonic distance sensor, it can find out the
exact distance between object and sensor, then display the distance value on
Arduino serial monitor.

Hardware
Introduction

The HC-SR04 ultrasonic sensor is a very affordable


proximity/distance sensor that has been used mainly for
object avoidance in various robotics projects.(click me to
check this 4wd robotic car use this module) It essentially
gives your Arduino eyes / spacial awareness and can
prevent your robot from crashing or falling off a table. It has also been used in turret
applications, water level sensing, and even as a parking sensor. This simple project
will use the HC-SR04 sensor with an Arduino and a Processing sketch to provide a
neat little interactive display on your computer screen.

How it works

The sensor emits an 8 cycle ultrasonic sound at 40,000 Hz which travels through the
air and if there is an object or obstacle on its path It will bounce back to the module.
Considering the travel time and the speed of the sound you can calculate the
distance.

A short ultrasonic pulse is transmitted by Trig pin at the time 0, reflected by an object
on its path if there is one. The senor Echo pin receives this signal and converts it to
an electric signal. The next trig pulse can be transmitted when the echo is faded away.
If no obstacle is detected, the output pin will give a 38ms high level signal.

In order to generate the ultrasound you need to set the Trig on a High State for 10
µs.That will send out an 8 cycle ultrasonic sonic burst at 40,000 Hz which will travel at
the speed sound and it will be received in the Echo pin. The Echo pin will output the
time in microseconds(μs) the sound wave traveled.

Check below sequence chart

- 188 -
Arduino Guide www.stemango.com

For example, if the object is 5 cm away from the sensor, and the speed of the sound
is 340 m/s or 0.034 cm/µs (1s=1000000μs) the sound wave will need to travel about
147μs. But the distance you will get from the Echo pin will be double as the orginal
sound wave travels forward and reflected back. So in order to get the distance we
need to multiply the received travel time value from the echo pin by 0.034 and divide
it by 2. The following image shows the procedure and formula.

*More detaisl about HC-SR04 please check datasheet.

- 189 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics > Ultrasonic Distance Sensor

Result
Upload the code and open serial port, you should see the measurement begin.

- 190 -
Arduino Guide www.stemango.com

Project 37 Distance Meter

This project we learn how to build an easy and low cost distance meter with popular
HC-SR04 ultrasonic module and LCD5110.

Parts Required

Wiring

- 191 -
Arduino Guide www.stemango.com

Sketch
To open the code go to: File > Sketchbook >STEManGo Electronics >37.Distance Meter

Result
After code uploaded you should see the distance display on the
lcd, try to move the lcd around and distance will keep changing.

- 192 -
Arduino Guide www.stemango.com

Project 38 BH1750 Light Sensor

You may have noticed that our smartphones are changing the screen backlight
depending on the brightness of the light source, but they do it as they have a light
sensor built inside. Let’s do get to know this sensor module.

Hardware

Introduction

BH1750FVI is a digital ambient light sensor IC with a


built-in 16 bit AD converter generating digital signal.This
IC is the most suitable to obtain the ambient light data
for adjusting LCD and Keypad backlight power of
smartphones. It is possible to detect wide range 1 -
65535 lx at High resolution.

lux [lx] is the SI unit of measurement of illumination. It is equal


to one lumen per square meter,

illuminance is a measure of how much luminous flux is spread over a given area. One can think of
luminous flux (measured in lumens) as a measure of the total "amount" of visible light present,
and the illuminance as a measure of the intensity of illumination on a surface

Lumen : The unit for the quantity of light flowing from a source in any one second (the luminous
power, or luminous flux) is called the lumen.

Specification
Voltage: 3-5v ( 5v power supply is fine as the module has voltage limit circuit)
Detect Range : 1 - 65535 lx
Resolution:0.5lx
Interface:I2C bus
Dimensions: 14 x 19mm

*More details please check datasheet.

- 193 -
Arduino Guide www.stemango.com

Typical Lux values

These were taken from Wikipedia


Illuminance Surfaces illuminated by:
0.0001 lux Moonless, overcast night sky (starlight)
0.002 lux Moonless clear night sky with airglow
0.27–1.0 lux Full moon on a clear night[3][4]
3.4 lux Dark limit of civil twilight under a clear sky
50 lux Family living room lights (Australia, 1998)
80 lux Office building hallway/toilet lighting]
100 lux Very dark overcast day
320–500 lux Office lighting
400 lux Sunrise or sunset on a clear day.
1000 lux Overcast day; typical TV studio lighting
10000–25000 lux Full daylight (not direct sun)
32000–100000 lux Direct sunlight

How it works?
Let’s take a look at the block diagram of the IC BH1750FVI.
Below image quoted from datasheet.

Start from the left you can see a photodiode (PD) has a sensitivity about the
sensitivity of the human eye.The operational amplifier (AMP) intensify the signal and
convert it from analog to 16-bit digital signal with ADC. The procedure ends with IIC
logic that uses an internal oscillator (serves as CLK).

The duration of this process depends on the accuracy of the readings we want.
According to the datasheet,we have three measurement mode that give accuracy of
0.5lx, 1 lx or 4LX, and the duration time is in the order of 120ms, 120ms and 16ms.

- 194 -
Arduino Guide www.stemango.com

The manufactuer recommend to use H-Resolution mode due to kind of


noise( including in 50Hz / 60Hz noise ) is rejected.

Pins Function

The ADD pin is used to set the sensor I2C address. By default (if ADD voltage less
than 0.7 * VCC) the sensor address will be 0x23. If it has voltage greater or equal to
0.7VCC voltage (e.g. you've connected it to VCC) the sensor address will be 0x5C.

- 195 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Sketch

To open the code go to: File > Sketchbook >STEManGo Electronics > 38.BH1750 Light Sensor

Result
You should see the lux value on serial monitor after code uploaded.

- 196 -
Arduino Guide www.stemango.com

Project 39 Light Meter

We will make a light meter, which display the LUX values directly to an LCD in this project.

Parts Required

Wiring

- 197 -
Arduino Guide www.stemango.com

Sketch

This project will use the UI (bulb icon), make sure below 3 files are in
same folder.

To open the code go to: File > Sketchbook >STEManGo Electronics > 39.Light Sensor

Result

Serial monitor will show different lux value if you put the sensor under different
brighterness environment.

- 198 -
Arduino Guide www.stemango.com

Project 40 Soil Moisture Sensor

You got a notice from your smartphone says your plant is thirsty, the next step is
press a button on the phone and your plant will be watered automatcilly at home.
This is cool and there are already some ecoplant kits available in market. We are not
doing this today. But soon in the future we will develop similar one with more excited
features.

In this project we focus on the must-have sensor of the ecoplant kit.

Hardware
Introduction

This is a simple soil humidity sensor aims to detect the soil humidity. If the soil is in
lack of water, the analog value output by the sensor will decrease, otherwise, it will
increase. If you use this sensor to make an automatic watering device, it can detect
whether your botany is thirsty to prevent it from withering when you go out. Using
the sensor with Arduino controller makes your plant more comfortable and your
garden smarter.

- 199 -
Arduino Guide www.stemango.com

How it works?

The sensor is set with two electrodes(probes) inserted into the soil, when there is
water,more electricy past the probe means resistance reduced. With the help of the
AD converter module, convert such resistance value into moisture content. The
higher moisture (less resistance), the higher conductivity the soil has.

Specification:

This sensor work with a AD converter module with LM393 comparator and
potentiometer for adjusting the threshold in order to set the digital output at a
certain moisture level.

Voltage: 3.3V or 5V
Working Current: ≤ 20mA
Output Voltage: 0-2.3V (When the sensor is totally immersed in water, thevoltage will be 2.3V) 5V
power supply,the higher humidity, the higher the output voltage
Sensor type: Analog and Digital available

Pin Out

The FC-28 soil moisture sensor has four pins:


VCC: Power
A0: Analog Output
D0: Digital Output
GND: Ground

- 200 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Sketch(calibration)
Before we upload the code, you might have below question.

How the sensor define wet or dry if I have different plants require different soil?

In other words, we need to get the data USEFUL. So we need to do some calibration
first.

Step 1: System Calibration

First we will calibrate the sensor to whatever soil you plan to monitor. Different
types of soil can affect the sensor, and you may get different readings from one
composition to the next.Before you start storing moisture data or triggering events

- 201 -
Arduino Guide www.stemango.com

based on that value, you should see what values you are actually getting from your
sensor.

To open the sketch go to: File > Sketchbook >STEManGo Electronics >40. Soil Moisture Sensor

Using the above sketch, note what values your sensor outputs when the sensor is
completely dry vs when the sensor is completely submerged in a shallow cup of
water.

Step 2: Soil Calibration

Once you have an idea what values your sensor is outputting in completely dry and
completely wet situations, it’s time to calibrate your sensor for the specific soil you
want to monitor. Do the same test above, only this time test your soil when it is as
dry as possible, then measure it when the soil is completely saturated with moisture.
Getting these values and comparing them to the ones from the previous calibration
will give you the best insight into what values mean for your specific plant and soil.
This test may take some trial and error and patience. Be careful not to over-water (or
under-water) your plants during these tests.

Once you have a good handle on the values you can expect, you can use the map()
function to adjust your code accordingly.

Step 3: Threshold

Here are the examples of setting two threshold value in map() function, both threshold tested
under the same environment, the probes with a bit water on my finger.

Set 256

- 202 -
Arduino Guide www.stemango.com

Set 512

So 7% for very little water is fine to me.

Above sketch uses only analog output. To use the module comprehensively we now
read the sensor value by using both digital and analog output.

Parts Required

- 203 -
Arduino Guide www.stemango.com

Wiring

Sketch
This sketch’s threshold value setting is different range.

To open the sketch go to: File > Sketchbook >STEManGo Electronics > Soil Moisture Sensor
> soil_moisture_sensor

Result
Serial monitor comes out four different results when the soil moisture in different level.

Analog value reach or out of threshold value


"I feel comfortable"
" I need some water"
Digital pins signal go to high(1)
"ALARM!I am very dry..."
Otherwise
"I am fine"

- 204 -
Arduino Guide www.stemango.com

Project 41 Soil Moisture Meter

As old tradition, adding a Nokia 5110 LCD display makes things more professional since we can
visually check the moisture levels of the soil.

Parts Required

Wiring

- 205 -
Arduino Guide www.stemango.com

Sketch
To open the sketch go to: File > Sketchbook >STEManGo Electronics >41.Soil Moisture Meter

Result

It should display as below image shown. ( percent vary according to your own soil)

- 206 -
Arduino Guide www.stemango.com

Project 42 Read RFID

This project we will read an RFID tag and respond to specific IDs, the ID will be shown
on serial monitor.

Hardware
Introduction

RFID (Radio Frequency Identification) is a non-contact ID system for identification


and tracking purposes. They are broadly used in many industries for tasks such as
office secure system, personnel tracking, access control, supply chain management,
books tracking in libraries, tollgate systems and so on.

How it works?

An RFID system consists of two main components, a transponder or a tag, a


read/write device which is located on the object that we want to be identified, and a
transceiver or a reader for data collection, processing, and transmission.

S50 electromagnetic card and keychain are commonly used tags

RFRC522 Radio Frequency Module

- 207 -
Arduino Guide www.stemango.com

The RFRC522 radio frequency module build with a control IC RC522 and an antenna
coil which generates high frequency electromagnetic field. On the other hand, the
tag is usually a passive component, which consist of just an antenna and an
electronic microchip.

When transceiver(RFRC522 module) get powered, it generated electromagnetic field,


when the tag or card get near to it, a voltage is generated in its antenna coil and this
voltage serves as power for the microchip in tag which has not battery inside to get
power.

- 208 -
Arduino Guide www.stemango.com

Now as the tag receive power,it can extract the transmitted data from the reader,
and for sending data back to the reader, it uses a technique called load manipulation.
Switching on and off a load at the antenna of the tag will affect the power
consumption of the reader’s antenna which can be measured as voltage drop. This
changes in the voltage will be captured as ones and zeros and that’s the way the
data is transferred from the tag to the reader.

Parts Required

Wiring

- 209 -
Arduino Guide www.stemango.com

Sketch
This sketch use library”MFRC522.h” and example code “Dumpinfo”

To open the example go to: File > Examples>MFRC522 >Dumpinfo

Result
After code uploaed, when you present the bule keychain tag at reading distance of
the MFRC522 Reader/PCD, the serial output will show the ID/UID(unique ID), type
and any data blocks it can read.

The result from the card

- 210 -
Arduino Guide www.stemango.com

Not working?
If you put your tag closed to module and the serial monitor has nothing else to
display, like below result, check Wiring between module and Arduino.

- 211 -
Arduino Guide www.stemango.com

Project 43 Display RFID UID on OLED

This project we will build one UID reader which reads the Unique ID (UID) of each RFID tagand
displays it on this OLED display.

Hardware

Introduction:

OLED Displays are great in many ways. They use very little power, are bright, easy to
read with large viewing angle and have high resolution considering their small size.
The OLED we will use today is a beautiful Dual Color yellow blue 0.96″ inch size,
features 128×64 pixels and uses the IIC bus.

Pin out:

Interface: IIC/I2C
GND: Power Gound
VCC: 2.2V-5.5V
SCL: CLK clock (High level 2.2V-5.5V)
SDA: MOSI data (High level 2.2V-5.5V)

Specification:

Color: Dual Color Yellow Blue LED


Resolution: 128x64
Power: 0.06W
Wide power supply range: DC 3V-5V
Temperature: -30°C to 70°C
Dimension: 29.28 x 27.1 mm (LW)
Compatible with 3.3V and 5V control chip I / O level
OLED internal drive chip: SSD136

- 212 -
Arduino Guide www.stemango.com

Parts Required

Wiring

- 213 -
Arduino Guide www.stemango.com

Sketch
This sketch use below libraries

<MFRC522.h>
<Adafruit_GFX.h>
<Adafruit_SSD1306.h>

To open the sketch go to: File > Sketchbook >STEManGo Electronics >43. Display RFID UID On
Oled

Result
The OLED display RFID LOCK after code uploaded.
If any tag closed to the module, the OLED will display two types of message either
RFID LOCK with UID value following or UNLOCK and jump back to RFID LOCK status if
right tag closed to.

In order to recognize the tag, you need to set up the UID allowed to opwn the lock. In
our example we set the stored UID value(68 176 61 217) from the blue tag. You can
edit the code to add more tags.

- 214 -
Arduino Guide www.stemango.com

Project 44 Loading Graph on I2C OLED

We don’t want to waste the nice color a dual color OLED can display. Now we will
learning how to load graphic on this oled. We will try two popular libraries from
Adafruit and U8glib runs two sketches shows the graphic and text effect.

Parts Required

Wiring

- 215 -
Arduino Guide www.stemango.com

Sketch

This sketch we will use the library “Adafruit_SSD1306.h”

As this oled has I2C interface we need to find out the I2C address first, run the below
example to scan the I2C address for your oled.
Step1: Run the code I2C Address scanner first
To open the code go to : File > Examples>LiquidCrystal_I2C>I2C_Address_Scanner
Step2: Run the example code from “Adafruit_SSD1306”
To open the code go to : File > Examples> Adafruit_SSD1306> ssd1306_128x64_i2c
Step3: Revise the I2C address on example code ssd1306_128x64_i2c
Go to line 61 and you will see the defautl i2c address set by Adafruit is 0x3D, replace it with the
i2c address you got. .In my example my one is 3c as below image shown.

- 216 -
Arduino Guide www.stemango.com

Now try the other example from library “U8glib.h”

To open the sketch go to: File > Sketchbook >STEManGo Electronics > 44.Loading Graph on I2C
OLED>Space Invader Game Logo

If you would like to experiment and learn more about this library, you can google:
U8GLIB Wiki.

Result

You should see the color display in yellow and blue in different parts of the shown
graphic.

- 217 -
Arduino Guide www.stemango.com

Project 45 Display Text on SPI OLED


You probably have one OLED with SPI interface. So we made another tutorial shows
how to interface it with Arduino. The chip is same, still SSD1306.

Hardware

This SPI oled is 0.96″ inch in size, features 128×64 pixels, the major difference is the
pin out compare with the I2C version. Since the SPI Bus is faster than I2C, this will
make our display very responsive.Of course there’s a tradeoff, the SPI Bus uses more
pins on our UNO (5 compared to 2).But for our project this is not a problem.

Pins assigment:

Gnd ----------------------> Gnd


VCC-----------------------> 5V or 3.3V
SCL [SCK]----------------> D13
SDA[MOSI] or [DIN]-> D11
RST[RESET]------------> D8
D/C[A0]--------------- -> D9

Few Important Points

 Despite the pins being labelled “SCL” and “SDA” this is not an I2C device, this is
an SPI device
 Other OLED displays using the SSD1306 controller can be configured for I2C or
SPI via jumpers / solder bridges
 Vcc can be connected to 3.3V or 5V and the controller is listed as supporting 5V
 There is no CS (Chip Select), “U8G_PIN_NONE” is used
 The reset line must be connected and pin specified
Parts Required

- 218 -
Arduino Guide www.stemango.com

Wiring

*DO NOT wire according to the order from oled pins, connect as above pins
assignment.

Sketch

Step1: Remove the uncomment “//” in U8glib code that makes it work
U8GLIB_SSD1306_128X64 u8g(13, 11, U8G_PIN_NONE, 9, 8);// SW SPI Com: SCK = 13, MOSI = 11, CS =
10, A0 = 9, RESET = 8
Step2: Run the text display sketch
To open the sketch go to: File > Sketchbook >STEManGo Electronics > 45.Display Text on SPI OLED

Result

You will see two row of text shows our trademark name “STEManGo Electronics”
after code uploaded.

- 219 -
Arduino Guide www.stemango.com

Project 46 OLED Temperature and Humidity Monitor

In this tutorial we will use the DHT11 Temperature and Humidity sensor again and display those
value on the OLED Display.

Parts Required:

Wiring

- 220 -
Arduino Guide www.stemango.com

Sketch

The library dht.h used same as project 28.

To open the sketch go to: File > Sketchbook >STEManGo Electronics > 46.OLED Temperature and
Humidity Monitor

Result
After code uploaded, it will display below value with a graphic.

- 221 -
Arduino Guide www.stemango.com

Project 47 Driving 1.8 inch TFT SPI Display

If you need more capability on displaying info such as an image in normal jpg format,
you probably need s TFT display with bigger size. In this project we instroduce a color
display nice color and deliver sharp image! This project we will simply test the display
with library built in sketch.

Hardware
Introduction

TFT stands for thin-film-transistor, and is used with


LCD to improve image quality over older technologies.
Each pixel on a TFT LCD has its own transistor on the
glass itself, which offers more control over the images
and colors that it renders. The TFT has a resolution of
128 x 160 pixels. This particular tutorial shows you
exactly what what you will need to do to get this
display to operate perfectly.

Pin out

VCC : 5V power input ( our module has voltage regulater IC so 5v is fine,if you short circuit
the JP1 and JP2 postion under the module, you should use 3.3v)
GND : Power Ground
NC: no connect
NC: no connect
NC: no connect
RESET : LCD controller reset, active low
A0: RS/DC : Command/Data Selection
SDA : LCD Data for SPI
SCK : SCLK for TFT Clock
CS : Chipselect for LCD
SCK (SD-Clock): SCLK for TF card
MISO (SD-DO) : SPI Master in Slave out
MOSI (SD-DI) : SPI Master out Slave in
CS (SD-CS) : Chipselect for TF card
LED+: power input for backlight (recommend use 3.3v
to keep the service life)
LED-: power ground for backlight

- 222 -
Arduino Guide www.stemango.com

Parts Required

Wiring

Arduino UNO 1.8 SPI ST7735 Display


GND LED-
3.3V LED+
D10 CS (pin closed to SCK)
D13 SCK
D12 SDA
D8 AO
D9 Reset
5V VCC
GND GND

- 223 -
Arduino Guide www.stemango.com

Sketch
You will require two libraries
“Adafruit_GFX.h” and a library “Adafruit_ST7735.h” for the ST7735 TFT Controller.
To open the sketch go to: File > Sketchbook >STEManGo Electronics > 47.Driving 1.8 inch TFT SPI
Display

Result
After code uploaded, the display would blink and display word”STEManGo!”.

- 224 -
Arduino Guide www.stemango.com

Project 48 Image Slideshow on 1.8 inch Display

This project we will show an image slideshow on a 1.8 inch tft module with SD card support.

Prepare the BMP Image


Resize image you want to display to size 128 x 160 pixel.
Restore as format BMP in 24 bits
Copy and paste them to the SD card root, do not create folder and put them in.

Parts Required

Wiring

- 225 -
Arduino Guide www.stemango.com

Arduino UNO 1.8 SPI ST7735 Display


GND LED-
3.3V LED+
D4 CS
MOSI (connect to SDA)
D12 MISO
SCK(connect to other SCK)
D10 CS
D13 SCK
D11 SDA
D9 AO
D8 Reset
VCC VCC
GND GND

Sketch
To open the sketch go to: File > Sketchbook >STEManGo Electronics > 48.Image Slideshow on 1.8
inch Display

Result
The program automatically searches all files in the root directory of the SD card and
slideshows them.Then it restarts with the first picture. In addition it displays status
messages over the serial port, which may be helpful when something goes wrong.

- 226 -
Arduino Guide www.stemango.com

Project 49 Digital Spirit Level

This project shows how to build a simple spirit level with ADXL345 accelerometer sensor module.

Hardware
Introduction

An accelerometer is an electromechanical device used to measure acceleration


forces. Acceleration is the measurement of the change in velocity, or speed divided
by time. They measure in meters per second squared (m/s 2) or in G-forces (g). For
example, a car accelerating from a standstill to 60 mph in
six seconds is determined to have an acceleration of 10
mph per second (60 divided by 6).

The ADXL345 acceleration sensor is a 3-axis accelerometer


with high resolution (13-bit) measurement at up to ±16
g,I2C or SPI interface to output a digital signal directly. In 1g
under acceleration, the output value of 256.

How it works?

It works by sensing the acceleration of the gravity.But how an electronic component can
sense something mechanical? The answer is MEMS(Micro Electro-Mechanial System) which
similar with IC but they are mechanical in nature.Inside the ADXL345 IC there are tiny
mechanical structures that can interface to electronics, mainly there are two types of
structures, the piezoelectric effect and the capacitance sensor. According to the page 13 of
ADXL345 datasheet, we can know it belong to capacitance sensor type.

The MEMS structure is suspended by polysilicon springs which allow it to deflect smoothly in
any direction when subject to acceleration in the X, Y and/or Z axis,which means it can sense
either static or dynamic forces of acceleration. Static forces include gravity, while dynamic
forces can include vibrations and movement.

- 227 -
Arduino Guide www.stemango.com

Deflection causes a change in capacitance between fixed plates (Plate A) and plates
attached to the suspended structure(Plate B). This change in capacitance on each
axis is converted to an output voltage proportional to the acceleration on that
axis,finally the acceleration can be determined.

Parts Required

- 228 -
Arduino Guide www.stemango.com

Wiring

Sketch

This code require library “ADXL345.h”


To open the sketch go to: File > Sketchbook >STEManGo Electronics > 49.Digital Spirit Level

Result
After code uploaded, the display shows the spirit level as below image.

- 229 -
Arduino Guide www.stemango.com

Project 50 Indoor Climate Mornitor

This project we will put a few sensors and a RTC module together to make a simple
indoor climate monitor, it can measure the temperature, humidity and air pressure,
saving maximum and minimum values of our measurements and show it on 1.8inch
color TFT display.

Parts Required

- 230 -
Arduino Guide www.stemango.com

Wiring

Sketch

Important: Library DHT and RTClib used here are NOT same version as project 28,46
and project 31 ,remember to replace with those in folder project 50 Indoor climate
monitor.

Install the libraries in project 50 folder.

To open the sketch go to: File > Sketchbook >STEManGo Electronics >50.Indoor Climate Monitor >

Result

After code uploaded, the display shows the spirit


level as below image.

- 231 -
Arduino Guide www.stemango.com

Project 51 Bluetooth Control DC Motor on Android

In this project we will control a DC motor with a Android smartphone via bluetooth.
We will use an Android device as master to send command to HC-06 bluetooth
module interface with Arduino.When type in certain commands on Android, the
motor will respond.

Hardware

Introduction
We're all use to wireless communication by now, you might
use bluetooth to download photos from a digital camera to a
PC, to hook up a wireless mouse to a laptop, to link a
hands-free headset to your cellphone so you can talk and
drive safely at the same time, and so on. Bluetooth is a
similar radio-wave technology, but it's mainly designed for
communicating over short distances less than about 10m or
30ft.

How it works?

Bluetooth sends and receives radio waves in a band of 79 different frequencies


(channels) centered on 2.45 GHz, set apart from radio, television, and cellphones etc.
Bluetooth network use a master/slave model to control when and where devices can send data.
In this model, a single master device can be connected to up to seven different slave devices,
called piconet(as below graphic shown). Any slave device in the piconet can only be connected to
a single master. Other devices can join or leave an existing piconet at any time. One device
(known as the master) acts as the overall controller of the network, while the others (known as
slaves) obey its instructions and not allow to talk to each other. Two or more separate piconets
can also join up and share information forming

- 232 -
Arduino Guide www.stemango.com

Few Important Points

-Paring

Bluetooth devices automatically detect and connect to one another.When devices


pair up, they share their addresses, names, and profiles, and usually store them in
memory. The also share a common secret key, which allows them to bond whenever
they’re together in the future. Pairing usually requires an authentication process
where a user must validate the connection between devices.In our example we use
HC-06 slave module, its access pin number is 1234 by default.You need to type in the
pin number to get access to hc-06 module on your Android smartphone. (If you device
operate iOS, search on ebay/amazon for HM-10 module to pair with.)

-Wiring to Arduino

a) HC-06 use serial bus commucation to send and receive data. A serial bus consists
of two serial pins: the receiver, RX, and the transmitter, TX. It’s important to note
that those RX and TX labels are with respect to the device itself. So the RX from one
device should go to the TX of the other, and vice-versa. The transmitter should be
talking to the receiver, not to another transmitter.

b)Disconect the Bluetooth module TX and RX pins from Arduino while uploading the
code to Arduino.The Arduino uses the serial communication so the pins RX (digital
pin 0) and TX (digital pin1) are busy. We can avoid this step if we use the other TX
and RX pins of the Arduino Board, but in that case we will have to use the
SoftwareSerial.h library for the serial communication.

-Communicate with Android smartphone


Find and install the application “BlueTerm V2.0” on your Android smartphone.
The apk file located in project folder.

- 233 -
Arduino Guide www.stemango.com

Parts Required
*HC-05 or 06 both fine for this project.

Wiring

- 234 -
Arduino Guide www.stemango.com

Pin Assignment

Sketch
To open the sketch go to: File > Sketchbook >STEManGo Electronics > 51.Bluetooth Control DC
Motor on Android

Result

Upload the code,open blueterm app on Android phone,search for Bluetooth module
HC-05 and connected.
Press "0" : no rotation "STOP"
Press "1" : rotation in right dir.
Press "2" : rotation in left dir.
Check here to see the video shows how it work.

- 235 -

You might also like