Unit 4 Arduino and Raspberry (1)
Unit 4 Arduino and Raspberry (1)
Physical device – Arduino Interfaces, Hardware requirement for Arduino, Connecting remotely
over the network using VNC, GPIO Basics, Controlling GPIO Outputs Using a Web Interface,
– Programming, APIs / Packages- Quark SOC processor, programming, Arduino Boards using
GPIO (LED, LCD, Keypad, Motor control and sensor)
BOARD DETAILS:
ARDUIN0 UN0
Power Supply:
Feature Value
USB or power barrel jack
OperatingVoltage 5V
Voltage Regulator
ClockSpeed 16MHz
LED Power Indicator
Digital I/O 14
Tx-Rx LED Indicator
AnalogInput 6
Output power,
PWM 6
Ground
UART 1
Interface USB via ATMega16U2 Analog Input Pins
Digital I/O Pin
SET UP:
2. LilyPad Arduino
3. RedBoard
5. Arduino Leonardo
Fig. 1 Arduino Board
Every Arduino board needs a way to be connected to a power source. The Arduino
UNO can be powered from a USB cable coming from your computer or a wall power supply
(like this) that is terminated in a barrel jack. In the picture above the USB connection is
labeled (1) and the barrel jack is labeled (2). The USB connection is also how you will load
code onto your Arduino board.
NOTE: Do NOT use a power supply greater than 20 Volts as you will overpower (and thereby
destroy) Arduino. The recommended voltage for most Arduino models is between 6 and 12
Volts.
The pins on your Arduino are the places where you connect wires to construct a circuit
(probably in conjunction with a breadboard and some wire. They usually have black plastic
‘headers’ that allow you to just plug a wire right into the board. The Arduino has several
different kinds of pins, each of which is labeled on the board and used for different functions.
GND (3): Short for ‘Ground’. There are several GND pins on the Arduino, any of which can
be used to ground your circuit.
5V (4) & 3.3V (5): As you might guess, the 5V pin supplies 5 volts of power, and the 3.3V pin
supplies 3.3 volts of power. Most of the simple components used with the Arduino run happily
off of 5 or 3.3 volts.
Analog (6): The area of pins under the ‘Analog In’ label (A0 through A5 on the UNO) are
Analog In pins. These pins can read the signal from an analog sensor (like a temperature sensor)
and convert it into a digital value that we can read.
Digital (7): Across from the analog pins are the digital pins (0 through 13 on the UNO). These
pins can be used for both digital input (like telling if a button is pushed) and digital output (like
powering an LED).
PWM (8): You may have noticed the tilde (~) next to some of the digital pins (3, 5, 6, 9, 10,
and 11 on the UNO). These pins act as normal digital pins, but can also be used for something
called Pulse-Width Modulation (PWM). We have a tutorial on PWM, but for now, think of
these pins as being able to simulate analog output (like fading an LED in and out).
AREF (9): Stands for Analog Reference. Most of the time you can leave this pin alone. It is
sometimes used to set an external reference voltage (between 0 and 5 Volts) as the upper limit
for the analog input pins.
Reset Button
Just like the original Nintendo, the Arduino has a reset button (10). Pushing it will temporarily
connect the reset pin to ground and restart any code that is loaded on the Arduino. This can be
very useful if your code doesn’t repeat, but you want to test it multiple times. Unlike the
original Nintendo however, blowing on the Arduino doesn’t usually fix any problems.
Just beneath and to the right of the word “UNO” on your circuit board, there’s a tiny LED next
to the word ‘ON’ (11). This LED should light up whenever you plug your Arduino into a power
source. If this light doesn’t turn on, there’s a good chance something is wrong. Time to re-
check your circuit!
TX RX LEDs
TX is short for transmit, RX is short for receive. These markings appear quite a bit in
electronics to indicate the pins responsible for serial communication. In our case, there are two
places on the Arduino UNO where TX and RX appear – once by digital pins 0 and 1, and a
second time next to the TX and RX indicator LEDs (12). These LEDs will give us some nice
visual indications whenever our Arduino is receiving or transmitting data (like when we’re
loading a new program onto the board).
Main IC
The black thing with all the metal legs is an IC, or Integrated Circuit (13). Think of it as the
brains of our Arduino. The main IC on the Arduino is slightly different from board type to
board type, but is usually from the ATmega line of IC’s from the ATMEL company. This can
be important, as you may need to know the IC type (along with your board type) before loading
up a new program from the Arduino software. This information can usually be found in writing
on the top side of the IC. If you want to know more about the difference between various IC’s,
reading the datasheets is often a good idea.p
Voltage Regulator
The voltage regulator (14) is not actually something you can (or should) interact with on the
Arduino. But it is potentially useful to know that it is there and what it’s for. The voltage
regulator does exactly what it says – it controls the amount of voltage that is let into the Arduino
board. Think of it as a kind of gatekeeper; it will turn away an extra voltage that might harm
the circuit. Of course, it has its limits, so don’t hook up your Arduino to anything greater than
20 volts.
DATA TYPES:
Void ,Long, Int ,Char ,Boolean, Unsigned char ,Byte, Unsigned int, Word ,Unsigned long
,Float, Double, Array ,String-char array, String-object, Short
Delay() function is one of the most common time manipulation function used to provide a delay
of specified time. It accepts integer value (time in miliseconds)
EXAMPLE BLINKING LED:
Requirement:
Arduino controller board, USB connector, Bread board, LED, 1.4Kohm resistor, connecting
wires, Arduino IDE
Connect the LED to the Arduino using the Bread board and the connecting wires
Connect the Arduino board to the PC using the USB connector
Select the board type and port Write the sketch in the editor, verify and upload
Connect the positive terminal of the LED to digital pin 12 and the negative terminal to the
ground pin (GND) of Arduino Board
void setup()
{
pinMode(12, OUTPUT); // set the pin mode
} void loop()
{
digitalWrite(12, HIGH); // Turn on the LED delay(1000);
digitalWrite(12, LOW); //Turn of the LED delay(1000);
}
Set the pin mode as output which is connected to the led, pin 12 in this case.
Use digitalWrite() function to set the output as HIGH and LOW
Delay() function is used to specify the delay between HIGH-LOW transition of the output
2. RASPBERRY PI:
Raspberry Pi is a credit card sized micro processor available in different models with
different processing speed starting from 700 MHz. Whether you have a model B or model B+,
or the very old version, the installation process remains the same. People who have checked
out the official Raspberry Pi website, But using the Pi is very easy and from being a beginner,
one will turn pro in no time. So, it's better to go with the more powerful and more efficient OS,
the Raspbian. The main reason why Raspbian is extremely popular is that it has thousands of
pre built libraries to perform many tasks and optimize the OS. This forms a huge advantage
while building applications.
Fig. 4 Raspberry Pi Elements
You will be needing an image writer to write the downloaded OS into the SD card (micro SD
card in case of Raspberry Pi B+ model). So download the "win32 disk imager" from the
website.
Insert the SD card into the laptop/pc and run the image writer. Once open, browse and select
the downloaded Raspbian image file. Select the correct device, that is the drive representing
the SD card. If the drive (or device) selected is different from the SD card then the other
selected drive will become corrupted. SO be careful.
After that, click on the "Write" button in the bottom. As an example, see the image below,
where the SD card (or micro SD) drive is represented by the letter "G:\"
Fig. 5 OS Installation
Once the write is complete, eject the SD card and insert it into the Raspberry Pi and turn it on.
It should start booting up.
3 Setting up the Pi
Please remember that after booting the Pi, there might be situations when the user credentials
like the "username" and password will be asked. Raspberry Pi comes with a default user name
and password and so always use it whenever it is being asked. The credentials are:
login: pi
password: raspberry
When the Pi has been booted for the first time, a configuration screen called the "Setup
Options" should appear and it will look like the image below.
If you have missed the "Setup Options" screen, its not a problem, you can always get it by
typing the following command in the terminal.
sudo raspi-config
Once you execute this command the "Setup Options" screen will come up as shown in the
image above.
Now that the Setup Options window is up, we will have to set a few things. After completing
each of the steps below, if it asks to reboot the Pi, please do so. After the reboot, if you don't
get the "Setup Options" screen, then follow the command given above to get the
screen/window.
The first thing to do:
select the first option in the list of the setup options window, that is select the "Expand
Filesystem" option and hit the enter key. We do this to make use of all the space present
on the SD card as a full partition. All this does is, expand the OS to fit the whole space on
the SD card which can then be used as the storage memory for the Pi
The second thing to do:
Select the third option in the list of the setup options window, that is select the "Enable
Boot To Desktop/Scratch" option and hit the enter key. It will take you to another
window called the "choose boot option" window that looks like the image below.
After the reboot from the previous step, if everything went right, then you will end up on the
desktop which looks like the image below.
sudo rpi-update
Updating the firmware is necessary because certain models of the Pi might not have all the
required dependencies to run smoothly or it may have some bug. The latest firmware might
have the fix to those bugs, thus its very important to update it in the beginning itself.
5 Conclusion
So, we have covered the steps to get the Pi up and running. This method works on all the
different models of Raspberry Pi (model A, B, B+ and also RPi 2) as Raspbain was made to be
supported on all models. However, while installing other software or libraries, the procedure
might change a bit while installing depending on the model of the Pi or the version of Raspbian
itself. The concept of Raspberry is to keep trying till you get the result or build that you want.
This might involve a lot of trial and error but spending the time will be worth it. The actual
usage doesn't end here. This is just the beginning. It is up to you to go ahead to build something
amazing out of it.
GPIO:
Open terminal
This will open the nano editor where you can write your code
time.sleep(1)
GPIO.output(11,False)
time.sleep(2)
GPIO.output(11,True)
GPIO.cleanup()
Power Pins
The header provides 5V on Pin 2 and 3.3V on Pin 1. The 3.3V supply is limited to 50mA. The
5V supply draws current directly from your microUSB supply so can use whatever is left over
after the board has taken its share. A 1A power supply could supply up to 300mA once the
Board has drawn 700mA.
Basic GPIO
The header provides 17 Pins that can be configured as inputs and outputs. By default they are
all configured as inputs except GPIO 14 & 15.
In order to use these pins you must tell the system whether they are inputs or outputs. This can
be achieved a number of ways and it depends on how you intend to control them. I intend on
using Python.
SDA & SCL: The 'DA' in SDA stands for data, the 'CL' in SCL stands for clock; the S stands
for serial. You can do more reading about the significance of the clock line for various types
of computer bus, You will probably find I2C devices that come with their own userspace drivers
and the linux kernel includes some as well. Most computers have an I2C bus, presumably for
some of the purposes listed by wikipedia, such as interfacing with the RTC (real time clock)
and configuring memory. However, it is not exposed, meaning you can't attach anything else
to it, and there are a lot of interesting things that could be attached -- pretty much any kind of
common sensor (barometers, accelerometers, gyroscopes, luminometers, etc.) as well as output
devices and displays. You can buy a USB to I2C adapter for a normal computer, but they cost
a few hundred dollars. You can attach multiple devices to the exposed bus on the pi.
UART, TXD & RXD: This is a traditional serial line; for decades most computers have had a
port for this and a port for parallel.1 Some pi oriented OS distros such as Raspbian by default
boot with this serial line active as a console, and you can plug the other end into another
computer and use some appropriate software to communicate with it. Note this interface does
not have a clock line; the two pins may be used for full duplex communication (simultaneous
transmit and receive).
PCM, CLK/DIN/DOUT/FS: PCM is is how uncompressed digital audio is encoded. The data
stream is serial, but interpreting this correctly is best done with a separate clock line (more
lowest level stuff).
SPI, MOSI/MISO/CE0/CE1: SPI is a serial bus protocol serving many of the same purposes
as I2C, but because there are more wires, it can operate in full duplex which makes it faster and
more flexible.
Raspberry Pi Terminal Commands
[sudo apt-get update] - Update Package Lists
[sudo apt-get upgrade] - Download and Install Updated Packages
[sudo raspi-config] - The Raspberry Pi Configuration Tool
[sudo apt-get clean] - Clean Old Package Files
[sudo reboot] - Restart your Raspberry Pi
[sudo halt] - Shut Down your Raspberry Pi
VNC: stands for Virtual Network Computing, allows you to access your Raspberry Pi
RealVNC: a company which originated VNC (there are many other implementations).
A RealVNC server is included with the Raspberry Pi, so that’s the implementation
we’re going to use.
VNC Server: an application which runs on the Raspberry Pi, and allows the VNC
client to connect, view and control your Raspberry Pi desktop.
VNC Client: an application which you can install on your desktop computer
(Windows / Linux / Mac / …) or smartphone / tablet, to connect to the Raspberry Pi
running the VNC server also called VNC viewer
Fig. 10 Using RealVNC to access the Raspberry Pi's graphical desktop
Enable VNC
You will need to interact with your Pi in order to turn on the VNC server. To do this, you have
several options:
Connect a keyboard, mouse, and monitor. Click the Terminal icon on the top left of
the desktop to open a terminal window.
Fig .11 VNC Connect
Click on the Raspberry Pi OS menu, select Preferences, and in the submenu Raspberry Pi
Configuration.
Fig. 12 Raspberry Pi Configuration
Configure your Raspberry Pi system using the Raspberry Pi Configuration tool. The tool will
have several tabs, click on the tab “Interfaces”, to see the available options there. Note that
VNC is disabled by default: Raspberry Pi Configuration tool, showing VNC as disabled
(“Enable remote access to this Pi using RealVNC”) Click on the enable radio button, and then
on ok button. VNC is now enabled in the Interfaces tab of the Raspberry Pi Configuration tool.
Watch the task bar at the top of the screen. A new icon with a V2 symbol will appear. Raspberry
Pi taskbar top right corner, before enabling VNC
Second step: obtain your Raspberry Pi RealVNC IP address and credentials
To be able to control your Raspberry Pi remotely, you need to know the IP address of the
Raspberry Pi running the RealVNC server to connect to it.
Click on the new icon (V2) in the taskbar (using the left mouse button, single click). A window
will appear, showing you all you need to know to connect:
VNC Server VNC connect by RealVNC Raspberry Pi Edition. Showing the IP address, and
the identity check signature and Catchphrase. Authentication is with your UNIX user name
and password. Download and install the RealVNC viewer.
The following steps are run on your main system, from which you desire to control the
Raspberry Pi remotely using VNC. Be sure to select the appropriate operating system
(Windows / macOS / Linux / Raspberry Pi / iOS / Android / Chrome / Solaris / HP-UX / AIX).
Install the VNC viewer according to the default procedure on your operating system. We can
also use other VNC viewers, but using the RealVNC VNC viewer is recommended, since they
have the best interoperability.
Here you can enter the Raspberry Pi IP address we have identified in step 2. Type in the address,
and click on the “connect to address or hostname” area (or simply press enter).Now the VNC
Viewer will show you an authentication screen, asking you to sign in with your credentials
(password and username).
Fig 14 Authentication
Fig 15 View Raspberry using VNC Viewer
On your host machine, download and install the RealVNC viewer. Open the application, and
click the Sign in button in the top-right. Enter your email and password, and click Sign in.
On the right side, you should see an address book (previously used connections) and something
showing your "Team" (computers available for a VNC cloud connection). Click on your Team,
and you should see your VNC-ready Raspberry Pi listed.
Double-click on your Raspberry Pi to connect to it. You should see a pop-up window
explaining that the VNC server on your Raspberry Pi has been verified. Click Continue. You
should be prompted with an Authentication window. If you did not change the login username
and password for your Pi, your default login credentials are:
Username: pi
Password: raspberry
Another slick feature is the ability to control your Raspberry Pi from your smartphone or tablet!
Download the VNC Viewer app from the iTunes store or Google Play. Open the app, sign in,
and connect to your Raspberry Pi!
In this part, we will install Apache web server in Raspberry Pi to control the LED from a
webpage that can be accessed from anywhere over the internet. Here we control an LED
connected to Raspberry Pi by using Apache web server. For this, we create an HTML/php
web page which has two buttons - one for turning on the LED and the second for turning off
the LED.
Components Required
An SSH client (Putty) is used to connect the Raspberry pi using a Laptop or computer. For
this, the raspberry pi needs to be connected to a network via LAN or Wi-Fi. If you have a
separate monitor for your raspberry pi, then it's better to connect raspberry pi with the monitor
and you don’t have to use any SSH client. Python is a very useful programming language that
has an easy to read syntax, and allows programmers to use fewer lines of code than would be
possible in languages such as assembly, C, or Java.
The Python programming language actually started as a scripting language for Linux. Python
programs are similar to shell scripts in that the files contain a series of commands that the
computer executes from top to bottom. Compare a “hello world” program written in C to the
same program written in Python:
Unlike C programs, Python programs don’t need to be compiled before running them.
However, you will need to install the Python interpreter on your computer to run them. The
Python interpreter is a program that reads Python files and executes the code.
It is possible to run Python programs without the Python interpreter installed though. Like shell
scripts, Python can automate tasks like batch renaming and moving large amounts of files. It
can be used just like a command line with IDLE, Python’s REPL (read, eval, print, loop)
function. However, there are more useful things you can do with Python. For example, you can
use Python to program things like:
Web applications
Special GUIs
Small databases
2D games
Python also has a large collection of libraries, which speeds up the development process. There
are libraries for everything you can think of – game programming, rendering graphics, GUI
interfaces, web frameworks, and scientific computing.
Many (but not all) of the things you can do in C can be done in Python. Python is generally
slower at computations than C, but its ease of use makes Python an ideal language for
prototyping programs and designing applications that aren’t computationally intensive.
4.1 INSTALLING AND UPDATING PYTHON
Python 2 and Python 3 come pre-installed on Raspbian operating systems, but to install
Python on another Linux OS or to update it, simply run one of these commands at the command
prompt:
#!/usr/bin/python
All Python program files will need to be saved with a “.py” extension. You can write the
program in any text editor such as Notepad or Notepad++, just be sure to save the file with a
“.py” extension. To run the program without making it executable, navigate to the location
where you saved your file, and enter this at the command prompt:
python hello-world.py
CONNECT THE LED TO THE RASPBERRY PI
Components:
Raspberry Pi
One LED
One 330 Ohm resistor
Jumper wires
Breadboard
Connect the components as shown in the wiring diagram below.
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(14,GPIO.OUT)
# While loop
while True:
GPIO.output(14,GPIO.HIGH)
time.sleep(1)
time.sleep(1)
At the top of the program we import the RPi.GPIO and time libraries. The RPi.GPIO library
will allow us to control the GPIO pins. The time library contains the sleep() function that we
will use to make the LED pause for one second.
Next we initialize the GPIO object with GPIO.setmode(GPIO.BCM). We are using the BCM
pin numbering system in this program. We use .GPIO.setwarnings(False) to disable the
warnings and GPIO.setup(14,GPIO.OUT) is used to set GPIO14 as an output.
Now we need to change the on/off state of GPIO14 once every second. We do this with the
GPIO.output() function. The first parameter of this function is the GPIO pin that will be
switched high or low. We have the LED connected to GPIO14 in this circuit, so the first
argument is 14.
The second parameter of the GPIO.output() function is the voltage state of the GPIO pin. We
can use either GPIO.HIGH or GPIO.LOW as an argument to turn the pin on or off.
Each GPIO.output() function in the code above is followed by a sleep() function that causes
the pin to hold its voltage state for the time (in seconds) defined in the parameter of the function.
In this program we are switching the LED on and off once every second so the argument is 1.
You can change this value to make the LED blink on and off faster or slower. Run the Python
program above by entering the following into the Raspberry Pi’s terminal:
sudo python LED.py
You should see the LED blinking on and off once every second.
You should also see a message in the terminal with “LED is ON“ when the LED is turned on,
and “LED is OFF” when the LED is turned off.
Fig. 17 output
Humans and other animals emit radiation all the time. This is nothing to be concerned about,
though, as the type of radiation we emit is infrared radiation (IR), which is pretty harmless at
the levels at which it is emitted by humans. In fact, all objects at temperatures above absolute
zero (-273.15C) emit infrared radiation. A PIR sensor detects changes in the amount of infrared
radiation it receives. When there is a significant change in the amount of infrared radiation it
detects, then a pulse is triggered. This means that a PIR sensor can detect when a human (or
any animal) moves in front of it. The pulse emitted when a PIR detects motion needs to be
amplified, and so it needs to be powered. There are three pins on the PIR: they should be
labelled Vcc, Gnd, and Out. These labels are sometimes concealed beneath the Fresnel lens
(the white cap), which you can temporarily remove to see the pin labels.
1. As shown above, the Vcc pin needs to be attached to a 5V pin on the Raspberry Pi.
2. The Gnd pin on the PIR sensor can be attached to any ground pin on the Raspberry
Pi.
3. Lastly, the Out pin needs to be connected to any of the GPIO pins.
Tuning a PIR
Most PIR sensors have two potentiometers on them. These can control the sensitivity of the
sensors, and also the period of time for which the PIR will signal when motion is detected.
Program
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
try:
print “PIR Module Test (CTRL+C to exit)”
time.sleep(2)
print “Ready”
while True:
if GPIO.input(PIR_PIN):
print “Motion Detected!”
time.sleep(1)
except KeyboardInterrupt:
print “ Quit”
GPIO.cleanup()
Step 1: Connections
The connections in this project are quite simple - the positive pin of LED is connected to GPIO
27 pin and the negative pin to a 270 ohm resistor, the other side of which is connected to GND
pin.
Fig 19 LED with Raspberry pi
WiringPi is a PIN-based GPIO access library written in C for the BCM2835, BCM2836, and
BCM2837 SoC devices used in all Raspberry Pi versions. It’s released under the GNU LGPLv3
license and is usable from C, C++, and RTB (BASIC) as well as many other languages with
suitable wrappers.
1. First we will update our Pi with the latest versions of Raspbian using the command:
cd wiringP./build
Apache is a very popular webserver, designed to create web servers that have the ability to host
one or more HTTP-based websites. Apache Web Server can be enhanced by manipulating the
code base or adding multiple extensions/add-ons. In our project, we are using an HTTP server
and its PHP extension.
Now, install the apache2 package by using this command in the terminal:
To test the web server whether it is working or not, go to your browser and type the Pi’s IP
address in the tab. To find the Pi's IP address, type ifconfig at the command line. By default,
Apache puts a test HTML file in the web folder. This default web page is served when you
browse to http://192.168.1.31 (whatever the Pi's IP address is) from another computer on the
network. Browse to the default web page either on the Pi or from another computer on the
network and you will see the following:
Fig. 20 Apache web Server
Now we will see how to change the default web page with your own HTML page
This default web page is just an HTML file on the filesystem. It is located
at var/www/html/index.html.
Navigate to this directory in a terminal window and have a look at what's inside:
cd var/www/html
ls -al
This shows that by default there is one file in /var/www/html/ called index.html and it is owned
by the root user. To edit the file, you need to change its ownership to your own username.
Change the owner of the file using:
You can now try editing this file and then refresh the browser to see the web page change.
Now if we want to use PHP code along with HTML, then we have to further install the PHP
extension in Raspberry pi. Using PHP code, we can create shell commands to control the LED
from the PHP script.
To allow the Apache server to edit PHP files, we will install the latest version of PHP and the
PHP module for Apache. Use the following command in terminal to install these:
sudo rm index.html
Save it by pressing CTRL + X and the ‘y’ and enter. Now refresh the webpage in your browser,
you will see a long page with lots of information about PHP. This shows that the PHP extension
is installed properly. If you have any problem with the pages or if the pages do not appear, try
reinstalling the apache server and its PHP extension.
Step 5: Start Coding for controlling GPIO pin using this Raspberry Pi Webserver
Now delete the previous code in index.php (<?php phpinfo(); ?>) file and insert below PHP
code to control GPIO pins inside body of HTML code.
Below is the complete code for creating two buttons to turn on and off the LED connected to
Raspberry Pi.
<html>
<head>
</head>
<body>
</form>
</center>
<?php
if(isset($_GET['off']))
else if(isset($_GET['on']))
?>
</body>
</html>
In the above code there is a PHP script which checks which button is pressed by using below
code and then turns on and off the LED accordingly.
<?php
if(isset($_GET['off']))
else if(isset($_GET['on']))
?>
Here we have used shell_exec() command in php code, this command is used to run the shell
command from the PHP script. Learn more about shell_exec here. If you run the command
inside shell_exec directly form the terminal of Raspberry pi, you can directly make GPIO pin
27 low or high. Below are two commands to test the LED directly from terminal.
/usr/local/bin/gpio -g write 27 0
/usr/local/bin/gpio -g write 27 1
After completing this, run the code in your browser by typing the IP address of raspberry pi in
the browser. You will see 2 buttons - ON, OFF to control your LED by clicking these buttons.
The Liquid Crystal library allows you to control LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you can usually tell them
by the 16-pin interface.
A register select (RS) pin that controls where in the LCD's memory you're writing
data to. You can select either the data register, which holds what goes on the screen,
or an instruction register, which is where the LCD's controller looks for instructions
on what to do next.
A Read/Write (R/W) pin that selects reading mode or writing mode
An Enable pin that enables writing to the registers
8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're
writing to a register when you write, or the values you're reading when you read.
There's also a display contrast pin (Vo), power supply pins (+5V and GND) and LED
Backlight (Bklt+ and BKlt-) pins that you can use to power the LCD, control the display
contrast, and turn on and off the LED backlight, respectively.
The process of controlling the display involves putting the data that form the image of what
you want to display into the data registers, then putting instructions in the instruction
register. The LiquidCrystal Library simplifies this for you so you don't need to know the
low-level instructions.
The Hitachi-compatible LCDs can be controlled in two modes: 4-bit or 8-bit. The 4-bit
mode requires seven I/O pins from the Arduino, while the 8-bit mode requires 11 pins. For
displaying text on the screen, you can do most everything in 4-bit mode, so example shows
how to control a 16x2 LCD in 4-bit mode.
Hardware Required
Arduino Board
LCD Screen (compatible with Hitachi HD44780 driver)
pin headers to solder to the LCD display pins
10k ohm potentiometer
220 ohm resistor
hook-up wires
breadboard
Before wiring the LCD screen to your Arduino board we suggest to solder a pin header
strip to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image
further up.
To wire your LCD screen to your board, connect the following pins:
Additionally, wire a 10k potentiometer to +5V and GND, with it's wiper (output) to LCD
screens VO pin (pin3).
Fig. 22 Arduino with LCD
Schematic
/*
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
The circuit:
* 10K resistor:
#include <LiquidCrystal.h>
void setup() {
lcd.begin(16, 2);
lcd.print("hello, world!");
}
void loop() {
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
lcd.print(millis() / 1000);
Autoscroll Example
This example sketch shows how to use the autoscroll() and noAutoscroll() methods to move
all the text on the display left or right.
autoscroll() moves all the text one space to the left each time a letter is added
This sketch prints the characters 0 to 9 with autoscroll off, then moves the cursor to the bottom
right, turns autoscroll on, and prints them again.
/*
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
The circuit:
* 10K resistor:
#include <LiquidCrystal.h>
void setup() {
lcd.begin(16, 2);
void loop() {
lcd.setCursor(0, 0);
// print from 0 to 9:
lcd.print(thisChar);
delay(500);
lcd.setCursor(16, 1);
lcd.autoscroll();
// print from 0 to 9:
for (int thisChar = 0; thisChar < 10; thisChar++) {
lcd.print(thisChar);
delay(500);
lcd.noAutoscroll();
lcd.clear();
Fig. 23 Keypad
Beneath each key is a membrane switch. Each switch in a row is connected to the other
switches in the row by a conductive trace underneath the pad. Each switch in a column is
connected the same way – one side of the switch is connected to all of the other switches in
that column by a conductive trace. Each row and column is brought out to a single pin, for a
total of 8 pins on a 4X4 keypad:
Pressing a button closes the switch between a column and a row trace, allowing current to
flow between a column pin and a row pin. The Arduino detects which button is pressed by
detecting the row and column pin that’s connected to the button.
1. First, when no buttons are pressed, all of the column pins are held HIGH, and all of the
row pins are held LOW:
2. When a button is pressed, the column pin is pulled LOW since the current from the HIGH
column flows to the LOW row pin:
3. The Arduino now knows which column the button is in, so now it just needs to find the row
the button is in. It does this by switching each one of the row pins HIGH, and at the same time
reading all of the column pins to detect which column pin returns to HIGH:
4. When the column pin goes HIGH again, the Arduino has found the row pin that is connected
to the button:
The pin layout for most membrane keypads will look like this:
To figure out which pins the columns are connected to, insert the ground wire into the pin you
know is row 1. Now press and hold any one of the buttons in that row. Now insert the positive
wire into each one of the remaining pins. The pin that makes the LED light up is the pin that’s
connected to that button’s column. Now press down another button in the same row, and insert
the positive wire into each one of the other pins. Repeat this process for each one of the other
columns until you have each one mapped out.
For a basic demonstration of how to setup the keypad, I’ll show you how to print each key
press to the serial monitor. We’ll use the Keypad library by Mark Stanley and Alexander
Brevig. This library takes care of setting up the pins and polling the different columns and
rows. To install the Keypad library, go to Sketch > Include Library > Manage Libraries and
search for “keypad”. Click on the library, then click install. Once the Keypad library is
installed, you can upload this code to the Arduino if you’re using a 4X4 keypad:
char hexaKeys[ROWS][COLS] = {
};
void setup(){
Serial.begin(9600);
void loop(){
Serial.println(customKey);
It works by sending sound waves from the transmitter, which then bounce off of an object
and then return to the receiver. You can determine how far away something is by the time
it takes for the sound waves to get back to the sensor. Let's get right to it! . Connections
VCC to 5V
GND to GND
Trig to pin 9
Echo to pin 10
You can actually connect Trig and Echo to whichever pins you want, 9 and 10 are just the ones I'm
using.
we define the pins that Trig and Echo are connected to.
Then we declare 2 floats, duration and distance, which will hold the length of the sound
wave and how far away the object is.
Next, in the setup, we declare the Trig pin as an output, the Echo pin as an input, and start
Serial communications.
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
Now, in the loop, what we do is first set the trigPin low for 2 microseconds just to make
sure that the pin in low first. Then, we set it high for 10 microseconds, which sends out an
8 cycle sonic burst from the transmitter, which then bounces of an object and hits the
receiver(Which is connected to the Echo Pin).
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
When the sound waves hit the receiver, it turns the Echo pin high for however long the
waves were traveling for. To get that, we can use a handy Arduino function called pulseIn().
It takes 2 arguments, the pin you are listening to(In our case, the Echo pin), and a
state(HIGH or LOW). What the function does is waits for the pin to go whichever sate you
put in, starts timing, and then stops timing when it switches to the other state. In our case
we would put HIGH since we want to start timing when the Echo pin goes high. We will
store the time in the duration variable. (It returns the time in microseconds)
Now that we have the time, we can use the equation speed = distance/time, but we will
make it time x speed = distance because we have the speed. What speed do we have? The
speed of sound, of course! The speed of sound is approximately 340 meters per second, but
since the pulseIn() function returns the time in microseconds, we will need to have a speed
in microseconds also, which is easy to get. A quick Google search for "speed of sound in
centimeters per microsecond" will say that it is .0343 c/μS. You could do the math, but
searching it is easier. Anyway, with that information, we can calculate the distance! Just
multiply the duration by .0343 and the divide it by 2(Because the sound waves travel to the
object AND back). We will store that in the distance variable.
distance = (duration*.0343)/2;
The rest is just printing out the results to the Serial Monitor.
Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}
7.2 Temperature Sensor
These sensors have little chips in them and while they're not that delicate, they do
need to be handled properly. Be careful of static electricity when handling them and make
sure the power supply is connected up correctly and is between 2.7 and 5.5V DC.They
come in a "TO-92" package which means the chip is housed in a plastic hemi-cylinder
with three legs. The legs can be bent easily to allow the sensor to be plugged into a
breadboard. You can also solder to the pins to connect long wires.
Unlike the FSR or photocell sensors we have looked at, the TMP36 and friends doesn't act
like a resistor. Because of that, there is really only one way to read the temperature value
from the sensor, and that is plugging the output pin directly into an Analog (ADC) input.
Remember that you can use anywhere between 2.7V and 5.5V as the power supply. For
this example I'm showing it with a 5V supply but note that you can use this with a 3.3v
supply just as easily. No matter what supply you use, the analog voltage reading will range
from about 0V (ground) to about 1.75V.
If you're using a 5V Arduino, and connecting the sensor directly into an Analog pin, you
can use these formulas to turn the 10-bit analog reading into a temperature:
This formula converts the number 0-1023 from the ADC into 0-5000mV (= 5V) If you're
using a 3.3V Arduino, you'll want to use this:
This formula converts the number 0-1023 from the ADC into 0-3300mV (= 3.3V) Then,
to convert millivolts into temperature, use this formula:
Centigrade temperature = [(analog voltage in mV) - 500] / 10
This example code for Arduino shows a quick way to create a temperature sensor, it simply
prints to the serial port what the current temperature is in both Celsius and Fahrenheit.
For better results, using the 3.3v reference voltage as ARef instead of the 5V will be more
precise and less noisy.
int sensorPin = 0;
* setup() - this function runs once when you turn your Arduino on
void setup()
{
Serial.begin(9600); //Start the serial connection with the computer
//to view the result open the serial monitor
}
void loop() // run over and over again
{
//getting the voltage reading from the temperature sensor
int reading = analogRead(sensorPin);
// converting that reading to voltage, for 3.3v arduino use 3.3
float voltage = reading * 5.0;
voltage /= 1024.0;
// print out the voltage
Serial.print(voltage); Serial.println(" volts");
// now print out the temperature
float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500
mV offset
//to degrees ((voltage - 500mV) times 100)
Serial.print(temperatureC); Serial.println(" degrees C");
// now convert to Fahrenheit
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
Serial.print(temperatureF); Serial.println(" degrees F");
delay(1000); //waiting a second
}