0% found this document useful (0 votes)
7 views60 pages

Unit 4 Arduino and Raspberry (1)

This document provides an overview of Arduino and Raspberry Pi, detailing their hardware components, setup processes, and programming basics. It covers the Arduino board specifications, pin functionalities, and the Arduino IDE for coding, as well as the steps to install and configure Raspbian on a Raspberry Pi. The document emphasizes the importance of understanding the components and programming for successful electronics projects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views60 pages

Unit 4 Arduino and Raspberry (1)

This document provides an overview of Arduino and Raspberry Pi, detailing their hardware components, setup processes, and programming basics. It covers the Arduino board specifications, pin functionalities, and the Arduino IDE for coding, as well as the steps to install and configure Raspbian on a Raspberry Pi. The document emphasizes the importance of understanding the components and programming for successful electronics projects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Unit IV

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)

1. PHYSICAL DEVICE- INTRODUCTION TO AUDUINO


Arduino is an open-source platform used for building electronics projects. Arduino
consists of both a physical programmable circuit board (often referred to as a microcontroller)
and a piece of software, or IDE (Integrated Development Environment) that runs on your
computer, used to write and upload computer code to the physical board. Accepts analog and
digital signals as input and gives desired output.

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:

 Power the board by connecting it to a PC via USB cable


 Launch the Arduino IDE
 Set the board type and the port for the board
 TOOLS -> BOARD -> select your board
 TOOLS -> PORT -> select your port
TYPES:

1. Arduino Uno (R3)

2. LilyPad Arduino

3. RedBoard

4. Arduino Mega (R3)

5. Arduino Leonardo
Fig. 1 Arduino Board

Power (USB / Barrel Jack):

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.

Pins (5V, 3.3V, GND, Analog, Digital, PWM, AREF):

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.

Power LED Indicator

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.

ARDINO IDE OVERVIEW:

Program coded in Arduino IDE is called a SKETCH

1. To create a new sketchFile -> New


To open an existing sketch File -> open ->
There are some basic ready-to-use sketches available in the EXAMPLES section
File -> Examples -> select any program
2. Verify: Checks the code for compilation errors
3. Upload: Uploads the final code to the controller board
4. New: Creates a new blank sketch with basic structure
5. Open: Opens an existing sketch
6. Save: Saves the current sketch
Fig. 2 Compilation and Execution
Serial Monitor: Opens the serial console
All the data printed to the console are displayed here

Fig. 3 Structure of SKETCH

A sketch can be divided into two parts:


Setup ()
Loop()
The function setup() is the point where the code starts, just like the main() function in C and
C++
I/O Variables, pin modes are initialized in the Setup() function Loop() function, as the
name suggests, iterates the specified task in the program

DATA TYPES:
Void ,Long, Int ,Char ,Boolean, Unsigned char ,Byte, Unsigned int, Word ,Unsigned long
,Float, Double, Array ,String-char array, String-object, Short

Arduino Function libraries


Input/Output Functions:
The arduino pins can be configured to act as input or output pins using the pinMode() function
Void setup ()
{
pinMode (pin , mode);
}
Pin- pin number on the Arduino board Mode- INPUT/OUTPUT
digitalWrite() : Writes a HIGH or LOW value to a digital pin
analogRead() : Reads from the analog input pin i.e., voltage applied across the pin
Character functions such as isdigit(), isalpha(), isalnum(), isxdigit(), islower(), isupper(),
isspace() return 1(true) or 0(false)

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

Connect he board to the PC


Set the port and board type
Verify the code and upload,
notice the TX – RX led in the board starts flashing as the code is uploaded.

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

As for the specifications, the Raspberry Pi is a credit card-sized computer powered by


the Broadcom BCM2835 system-on-a-chip (SoC). This SoC includes a 32-bit ARM1176JZFS
processor, clocked at 700MHz, and a Videocore IV GPU. It also has 256MB of RAM in a POP
package above the SoC. The Raspberry Pi is powered by a 5V micro USB AC charger or at
least 4 AA batteries (with a bit of hacking). While the ARM CPU delivers real-world
performance similar to that of a 300MHz Pentium 2, the Broadcom GPU is a very capable
graphics core capable of hardware decoding several high definition video formats. The
Raspberry Pi model available for purchase at the time of writing — the Model B —
features HDMI and composite video outputs, two USB 2.0 ports, a 10/100 Ethernet port, SD
card slot, GPIO (General Purpose I/O Expansion Board) connector, and analog audio output
(3.5mm headphone jack). The less expensive Model A strips out the Ethernet port and one of
the USB ports but otherwise has the same hardware. Raspberry Pi Basics: installing Raspbian
and getting it up and running.
1 Downloading Raspbian and Image writer.

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.

2 Writing the image

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.

Fig. 6 Raspberry Configuration

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.

Fig. 7 Boot Options


In the "choose boot option window", select the second option, that is, "Desktop Log in as
user 'pi' at the graphical desktop" and hit the enter button. Once done you will be taken back
to the "Setup Options" page, if not select the "OK" button at the bottom of this window and
you will be taken back to the previous window. We do this because we want to boot into the
desktop environment which we are familiar with. If we don't do this step then the Raspberry Pi
boots into a terminal each time with no GUI options. Once, both the steps are done, select the
"finish" button at the bottom of the page and it should reboot automatically. If it doesn't, then
use the following command in the terminal to reboot.
sudo reboot

Updating the firmware

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.

Fig. 8 Raspberry Desktop


Once you are on the desktop, open a terminal and enter the following command to update the
firmware of the Pi.

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.

Fig. 9 GPIO Pins

GPIO:

Act as both digital output and digital input.

Output: turn a GPIO pin high or low.

Input: detect a GPIO pin high or low


Installing GPIO library:

Open terminal

Enter the command “sudoapt-get install python-dev” to install python development

Enter the command “sudoapt-get install python-rpi.gpio” to install GPIO library.

Basic python coding:


Open terminal enter the command

sudo nano filename.py

This will open the nano editor where you can write your code

Ctrl+O : Writes the code to the file

Ctrl+X : Exits the editor

Blinking LED Code:

import RPi.GPIO as GPIO #GPIO library import time

GPIO.setmode(GPIO.BOARD) # Set the type of board for pin numbering

GPIO.setup(11, GPIO.OUT) # Set GPIO pin 11as output pin

for i in range (0,5): GPIO.output(11,True) # Turn on GPIO pin 11

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

3. REMOTE DESKTOP ON THE RASPBERRY Pi WITH VNC

 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

Enable VNC Cloud Connection on the Pi

Enable RealVNC using the Raspberry Pi Configuration tool

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:

Fig. 13 Real VNC

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!

4. CONTROLLING GPIO USING WEB INTERFACE

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

1. Raspberry pi board (With Raspbian operating system)


2. LED
3. 4. 250-ohm resistor
4. Jumper Wires

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

 Desktop applications and utilities

 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:

sudo apt-get install python3


Installs or updates Python 3.

sudo apt-get install python


Installs or updates Python 3

4.2 WRITING A PYTHON PROGRAM


To demonstrate creating and executing a Python program, we’ll make a simple “hello world”
program. To begin, open the Nano text editor and create a new file named hello-world.py by
entering this at the command prompt:

sudo nano hello-world.py


Enter this code into Nano, then press Ctrl-X and Y to exit and save the file:

#!/usr/bin/python

print "Hello, World!";

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.

Fig. 16 Raspberry pi with LED


The 330 Ohm resistor is a current limiting resistor. Current limiting resistors should always be
used when connecting LEDs to the GPIO pins. If an LED is connected to a GPIO pin without
a resistor, the LED will draw too much current, which can damage the Raspberry Pi or burn
out the LED. Here is a nice calculator that will give you the value of a current
limiting resistor to use for different LEDs. After connecting the hardware components, the next
step is to create a Python program to switch on and off the LED. This program will make the
LED turn on and off once every second and output the status of the LED to the terminal. The
first step is to create a Python file. To do this, open the Raspberry Pi terminal and type nano
LED.py. Then press Enter. This will create a file named LED.py and open it in the Nano text
editor. Copy and paste the Python code below into Nano and save and close the file.

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

GPIO.setup(14,GPIO.OUT)

# While loop

while True:

# set GPIO14 pin to HIGH

GPIO.output(14,GPIO.HIGH)

# show message to Terminal

print "LED is ON"

# pause for one second

time.sleep(1)

# set GPIO14 pin to HIGH


GPIO.output(14,GPIO.LOW)

# show message to Terminal

print "LED is OFF"

# pause for one second

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

4.3 Using a PIR sensor

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.

Fig. 18 Raspberry with PIR

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

import RPi.GPIO as GPIO


import time

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()

4.4 Controlling LED using Raspberry Pi Webserver

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

Step 2: Installing WiringPi Library

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:

sudo apt-get update

2. Now we will install git by using this command:

sudo apt-get install git-core

3. Now obtain WiringPi using git by this command:


git clone git://git.drogon.net/wiringPi

4. Then install WiringPi library using:

cd wiringP./build

Step 3: Installing a Web Server

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.

To Install Apache web server, we will use the following commands:

First, update the available packages:

sudo apt-get update

Now, install the apache2 package by using this command in the terminal:

sudo apt-get install apache2 -y

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 will show you:


total 12

drwxr-xr-x 2 root root 4096 Jan 8 01:29 .

drwxr-xr-x 12 root root 4096 Jan 8 01:28 ..

-rw-r--r-- 1 root root 177 Jan 8 01:29 index.html

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:

Sudo chown pi: index.html.

You can now try editing this file and then refresh the browser to see the web page change.

Install PHP in Raspberry Pi

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 apt-get install php libapache2-mod-php -y

Now remove the default index.html file:

sudo rm index.html

And create your own index.php file:

sudo nano index.php


Now enter the below code in index.php to test the PHP installation.

<?php phpinfo(); ?>

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>

<meta name="viewport" content="width=device-width" />

<title>Raspberry Pi WiFi Controlled LED</title>

</head>

<body>

<center><h1>Control LED using Raspberry Pi Webserver</h1>

<form method="get" action="index.php">

<input type="submit" style = "font-size: 14 pt" value="OFF" name="off">


<input type="submit" style = "font-size: 14 pt" value="ON" name="on">

</form>

</center>

<?php

shell_exec("/usr/local/bin/gpio -g mode 27 out");

if(isset($_GET['off']))

echo "LED is off";

shell_exec("/usr/local/bin/gpio -g write 27 0");

else if(isset($_GET['on']))

echo "LED is on";

shell_exec("/usr/local/bin/gpio -g write 27 1");

?>

</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

shell_exec("/usr/local/bin/gpio -g mode 27 out");

if(isset($_GET['off']))

echo "LED is off";

shell_exec("/usr/local/bin/gpio -g write 27 0");

else if(isset($_GET['on']))

echo "LED is on";

shell_exec("/usr/local/bin/gpio -g write 27 1");

?>
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.

5. LIQUID CRYSTAL DISPLAYS (LCD) WITH ARDUINO

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.

Fig. 21 Output of the sketch in 16x2 LCD


The LCDs have a parallel interface, meaning that the microcontroller has to manipulate
several interface pins at once to control the display. The interface consists of the following
pins:

 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:

 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 GND
 LCD VSS pin to GND
 LCD VCC pin to 5V
 LCD LED+ to 5V through a 220 ohm resistor
 LCD LED- to GND

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

The circuit (made using Fritzing).

Schematic

The schematic (made using Fritzing).


Hello world example

/*

LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The LiquidCrystal

library works with all 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.

This sketch prints "Hello World!" to the LCD

and shows the time.

The circuit:

* 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 resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)

// include the library code:

#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin

// with the arduino pin number it is connected to

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

// Print a message to the LCD.

lcd.print("hello, world!");
}

void loop() {

// set the cursor to column 0, line 1

// (note: line 1 is the second row, since counting begins with 0):

lcd.setCursor(0, 1);

// print the number of seconds since reset:

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

noAutoscroll() turns scrolling off

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.

/*

LiquidCrystal Library - Autoscroll

Demonstrates the use a 16x2 LCD display. The LiquidCrystal

library works with all 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.

This sketch demonstrates the use of the autoscroll()

and noAutoscroll() functions to make new text scroll or not.

The circuit:

* 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

* 10K resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)

// include the library code:

#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin

// with the arduino pin number it is connected to


const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

void loop() {

// set the cursor to (0,0):

lcd.setCursor(0, 0);

// print from 0 to 9:

for (int thisChar = 0; thisChar < 10; thisChar++) {

lcd.print(thisChar);

delay(500);

// set the cursor to (16,1):

lcd.setCursor(16, 1);

// set the display to automatically scroll:

lcd.autoscroll();

// print from 0 to 9:
for (int thisChar = 0; thisChar < 10; thisChar++) {

lcd.print(thisChar);

delay(500);

// turn off automatic scrolling

lcd.noAutoscroll();

// clear screen for the next loop:

lcd.clear();

6. ARDUINO WITH KEYPAD


The buttons on a keypad are arranged in rows and columns. A 3X4 keypad has 4 rows and 3
columns, and a 4X4 keypad has 4 rows and 4 columns:

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:

Fig. 24 keypad Structure

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.

This happens in four steps:

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:

Fig 25 Pin Layout


Follow the diagrams below to connect the keypad to an Arduino Uno, depending on whether
you have a 3X4 or 4X4 keypad: First, find out which keypad pins are connected to the button
rows. Insert the ground (black) wire into the first pin on the left. Press any button in row 1 and
hold it down. Now insert the positive (red) wire into each one of the other pins. If the LED
lights up at one of the pins, press and hold another button in row 1, then insert the positive wire
into each one of the other pins again. If the LED lights up on a different pin, it means the
ground wire is inserted into the row 1 pin. If none of the buttons in row 1 make the LED light
up, the ground wire is not connected to row 1. Now move the ground wire over to the next pin,
press a button in a different row, and repeat the process above until you’ve found the pin for
each row.

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.

PROGRAMMING THE KEYPAD

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:

THE CODE FOR A 3X4 KEYPAD


If you’re using a 3X4 keypad, you can use this code:
#include <Keypad.h>

const byte ROWS = 4;

const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {

{'1', '2', '3', 'A'},

{'4', '5', '6', 'B'},

{'7', '8', '9', 'C'},

{'*', '0', '#', 'D'}

};

byte rowPins[ROWS] = {9, 8, 7, 6};

byte colPins[COLS] = {5, 4, 3, 2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,


COLS);

void setup(){

Serial.begin(9600);

void loop(){

char customKey = customKeypad.getKey();


if (customKey){

Serial.println(customKey);

7. ARDUINO WITH SENSORS

7.1 Ultrasonic sensor

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

The connections are very simple:

 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.

Fig 26. Ultra Sonic Sensor


Code:

we define the pins that Trig and Echo are connected to.

const int trigPin = 9;


const int echoPin = 10;

Then we declare 2 floats, duration and distance, which will hold the length of the sound
wave and how far away the object is.

float duration, distance;

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)

duration = pulseIn(echoPin, HIGH);

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.

Reading the Analog Temperature Data

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:

Voltage at pin in milliVolts = (reading from ADC) * (5000/1024)

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:

Voltage at pin in milliVolts = (reading from ADC) * (3300/1024)

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

Fig 27 Temperature Sensor

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
}

You might also like