Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Practical: 1: Aim: Getting Started With Nodemcu, Arduino With Esp8266 and Esp32 in The Arduino Ide

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

ANUPAM TIWARI 180860109017(IOT)

PRACTICAL: 1
Aim: Getting started with NodeMCU, Arduino with ESP8266 and ESP32 in the
Arduino IDE.
What is NodeMCU?

NodeMCU is an open source platform based on ESP8266 which can connect objects and let data
transfer using the Wi-Fi protocol. In addition, by providing some of the most important features of
microcontrollers such as GPIO, PWM, ADC, and etc., it can solve many of the project’s needs
alone.

NodeMCU Architecture

What is Arduino?

Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It


consists of a circuit board, which can be programed (referred to as a microcontroller) and a ready-made
software called Arduino IDE (Integrated Development Environment), which is used to write and upload
the computer code to the physical board.

Arduino Architecture
ANUPAM TIWARI 180860109017(IOT)

 Features
 Arduino programming is a simplified version of C++, which makes the learning process easy.
 The Arduino IDE is used to control the functions of boards. It further sends the set of specifications
to the microcontroller.
 Arduino does not need an extra board or piece to load new code.
 Arduino can read analog and digital input signals.
 The hardware and software platform is easy to use and implement
 Arduino IDE- Installation

 How to program NodeMCU using Arduino IDE


 Steps 1: Choose Preferences in the File menu and enter the copied code in Additional Board
Manager URLs part. Then press OK.
ANUPAM TIWARI 180860109017(IOT)

 Steps 2: Search the word ESP8266 in Boards>boards manager from Tools menu. Then install
ESP8266 boards. After complete installation, you will see the INSTALLED label on ESP8266
boards.
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL: 2
AIM: - GPIO Interfacing and Programming.

 GPIO stands for General Purpose Input Output.


 The Raspberry Pi has two rows of GPIO pins, which are connections between the Raspberry Pi, and
the real world.
 Output pins are like switches that the Raspberry Pi can turn on or off (like turning on/off a LED
light). But it can also send a signal to another device.
 Input pins are like switches that you can turn on or off from the outside world (like a on/off light
switch). But it can also be a data from a sensor, or a signal from another device.
 That means that you can interact with the real world, and control devices and electronics using the
Raspberry PI and its GPIO pins!

Arduino GPIO Pins


Arduino Uno board has various digital IO pins which can

be used for input/output devices. Following image shows

the digital IO pins of Arduino Uno,


 Arduino analog pins can also be used as digital
input/output pins. Let’s see digital input, output of Arduino
(ATmega).

 Digital Output
 Arduino (ATmega) digital pins can be configured as
output to drive output devices. We have to configure these
pins to use as output.
 To configure these pins, pinMode () function is used Arduino GPIO
  Which set direction of pin as input or output.
 pinMode(pin no, Mode)
 This function is used to configure GPIO pin as input or output.
o pin no number of pin whose mode we want to set.
o Mode INPUT, OUTPUT or INPUT_PULLUP
 E.g. pinMode (3, OUTPUT)  //set pin 3 as output
 These Arduino (ATmega) pins can source or sink current up to 40 mA which is sufficient to drive
led, LCD display but not sufficient for motors, relays, etc.
 Note: While connecting devices to Arduino output pins use resistor. If any connected device to
Arduino withdraw current more than 40 mA from the Arduino then it will damage the Arduino pin or
IC.
 These pin produce output in terms of HIGH (5 V or 3.3 V) or LOW (0 V). We can set output on
these pins using digitalWrite () function.

 DigitalWrite (pin no, Output value)


ANUPAM TIWARI 180860109017(IOT)

 This function is used to set output as HIGH (5 V) or LOW (0 V)


o pin no number of a pin whose mode we want to set.
o Output value HIGH or LOW
o E.g. digitalWrite (3, HIGH)

 Sketch for LED Blinking using Arduino


void setup()
{
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop()
{
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}

LED BLINKING OUTPUT :


ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 3
AIM: - Digital ON/OFF sensor (PIR and IR) interfacing programming.

What is PIR and IR Sensors?


An Infrared (IR) sensor is an electronic device that measures and detects infrared radiation in its
surrounding environment. While measuring the temperature of each color of light (separated by
a prism), he noticed that the temperature just beyond the red light was highest. IR is invisible
to the human eye, as its wavelength is longer than that of visible light.

A Passive Infrared Sensor (PIR sensor) is an electronic sensor that measures infrared (IR) light
radiating from objects in its field of view. They are most often used in PIR-based motion detectors. PIR
sensors are commonly used in security alarms and automatic lighting applications.

CODE :

OUTPUT :
ANUPAM TIWARI 180860109017(IOT)

CONNECTION DIAGRAM:

IR sensor PIR sensor

OUTPUT :
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 4
AIM: - Analog Sensor programming and uploading sensor data on cloud and Write
a program to upload data of temperature and Humidity using Arduino/Node MCU.

What is DHT11 Sensor?


The DHT11 is a basic, ultra-low-cost digital temperature and humidity sensor. It uses a capacitive
humidity sensor and a thermistor to measure the surrounding air, and spits out a digital signal on the
data pin (no analog input pins needed).

 Getting API Key

1. Go to https://thingspeak.com/ and create an account if you do not have one. Login to your account.
2. Create a new channel by clicking on the button. Enter basic details of the channel. Than Scroll
down and save the channel.
3. Channel Id is the identity of your channel. Note down this. Than go to API keys copy and paste this
key to a separate notepad file will need it later.

CODE :

// Hardware: NodeMCU,DHT11
#include <DHT.h>  // Including library for dht
#include <ESP8266WiFi.h>

String apiKey = "Your API of thingsspeak";   


const char *ssid =  "Your wifi Network name";     
const char *pass =  "Network password";
const char* server = "api.thingspeak.com";

#define DHTPIN 0          


DHT dht(DHTPIN, DHT11);
WiFiClient client;

void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server,80))   //   "184.106.153.149" or api.thingspeak.com
{
ANUPAM TIWARI 180860109017(IOT)

String postStr = apiKey;


postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
delay(10000);
}

OUTPUT OF DHT11 SENSOR CONNECTION DIAGRAM

CLOUD OUTPUT :
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 5
AIM: - Controlling devices remotely using Bluetooth link, Wi-Fi link

Introduction:
Blynk is a Platform with IOS and Android apps to control Arduino, Raspberry Pi and the likes over the
Internet. It’s a digital dashboard where you can build a graphic interface for your project by simply
dragging and dropping widgets.

How It Works

A. Connect in seconds to approved computers, machines, devices, or even unattended servers or other
equipment.
B. Access system, data, files, and applications.
C. Control the equipment, system, machine, computer, phone, or IoT device, as though you were the
primary user handling it in person.

CODE to Control LED CONNECTION DIAGRAM


ANUPAM TIWARI 180860109017(IOT)

OUTPUT :

OFF in Blynk

ON in Blynk
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 6
AIM: - Write a program to monitor Heartbeat in Arduino UNO.

What is Heartbeat Sensor?


Heartbeat Sensor is an electronic device that is used to measure the heart rate i.e. speed of the heartbeat.
Monitoring body temperature, heart rate and blood pressure are the basic things that we do in order to
keep us healthy.
In order to measure the body temperature, we use thermometers and a sphygmomanometer to monitor
the Arterial Pressure or Blood Pressure.

Working of the Circuit

Upload the code to Arduino UNO and Power on the system. The Arduino asks us to place our finger in
the sensor and press the switch.
Place any finger (except the Thumb) in the sensor clip and push the switch (button). Based on the data
from the sensor, Arduino calculates the heart rate and displays the heartbeat in bpm.
While the sensor is collecting the data, sit down and relax and do not shake the wire as it might result in
a faulty values.
After the result is displayed on the LCD, if you want to perform another test, just push the rest button
on the Arduino and start the procedure once again.

CODE:
#include <LiquidCrystal.h>
LiquidCrystal lcd(6, 5, 3, 2, 1, 0);
int data=A0;
int start=7;
int count=0;
unsigned long temp=0;
byte customChar1[8] = {0b00000,0b00000,0b00011,0b00111,0b01111,0b01111,0b01111,0b01111};
byte customChar2[8] = {0b00000,0b11000,0b11100,0b11110,0b11111,0b11111,0b11111,0b11111};
byte customChar3[8] = {0b00000,0b00011,0b00111,0b01111,0b11111,0b11111,0b11111,0b11111};
byte customChar4[8] = {0b00000,0b10000,0b11000,0b11100,0b11110,0b11110,0b11110,0b11110};
byte customChar5[8] = {0b00111,0b00011,0b00001,0b00000,0b00000,0b00000,0b00000,0b00000};
byte customChar6[8] = {0b11111,0b11111,0b11111,0b11111,0b01111,0b00111,0b00011,0b00001};
byte customChar7[8] = {0b11111,0b11111,0b11111,0b11111,0b11110,0b11100,0b11000,0b10000};
byte customChar8[8] = {0b11100,0b11000,0b10000,0b00000,0b00000,0b00000,0b00000,0b00000};
void setup()
{
lcd.begin(16, 2);
lcd.createChar(1, customChar1);
lcd.createChar(2, customChar2);
lcd.createChar(3, customChar3);
lcd.createChar(4, customChar4);
lcd.createChar(5, customChar5);
lcd.createChar(6, customChar6);
lcd.createChar(7, customChar7);
ANUPAM TIWARI 180860109017(IOT)

lcd.createChar(8, customChar8);
pinMode(data,INPUT);
pinMode(start,INPUT_PULLUP);
}
void loop()
{
lcd.setCursor(0, 0);
lcd.print("Place The Finger");
lcd.setCursor(0, 1);
lcd.print("And Press Start");
while(digitalRead(start)>0);
lcd.clear();
temp=millis();
while(millis()<(temp+10000))
{
if(analogRead(data)<100)
{
count=count+1;
lcd.setCursor(6, 0);
lcd.write(byte(1));
lcd.setCursor(7, 0);
lcd.write(byte(2));
lcd.setCursor(8, 0);
lcd.write(byte(3));
lcd.setCursor(9, 0);
lcd.write(byte(4));
lcd.setCursor(6, 1);
lcd.write(byte(5));
lcd.setCursor(7, 1);
lcd.write(byte(6));
lcd.setCursor(8, 1);
lcd.write(byte(7));
lcd.setCursor(9, 1);
lcd.write(byte(8));
while(analogRead(data)<100);
lcd.clear();
}
}
lcd.clear();
lcd.setCursor(0, 0);
count=count*6;
lcd.setCursor(2, 0);
lcd.write(byte(1));
lcd.setCursor(3, 0);
lcd.write(byte(2));
lcd.setCursor(4, 0);
lcd.write(byte(3));
lcd.setCursor(5, 0);
lcd.write(byte(4));
ANUPAM TIWARI 180860109017(IOT)

lcd.setCursor(2, 1);
lcd.write(byte(5));
lcd.setCursor(3, 1);
lcd.write(byte(6));
lcd.setCursor(4, 1);
lcd.write(byte(7));
lcd.setCursor(5, 1);
lcd.write(byte(8));
lcd.setCursor(7, 1);
lcd.print(count);
lcd.print(" BPM");
temp=0;
while(1);
}

CONNECTION DIAGRAM OUTPUT OF HEARTBEAT


ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 7
AIM: - Experiments on Agriculture loT (Soil moisture, PH monitor)

In agriculture IoT applications include farm vehicle tracking, livestock monitoring, storage monitoring
and other farm operations. The diagram on the right provides a visual of this application.
In this IoT model, sensors can be deployed in the farm – to the ground, in water, in vehicles etc. to
collect data. The collected data is stored in the cloud system or server and accessed by the farmer via
the internet or their mobile phones.

What is Soil moisture Sensor?


Soil moisture sensors measure the volumetric water content in soil. Since the direct gravimetric
measurement of free soil moisture requires removing, drying, and weighing of a sample, soil moisture
sensors measure the volumetric water content indirectly by using some other property of the soil, such
as electrical resistance, dielectric constant, or interaction with neutrons, as a proxy for the moisture
content.

What is PH monitor Sensor?


A pH sensor is one of the most essential tools that's typically used for water measurements.
This type of sensor is able to measure the amount of alkalinity and acidity in water and other
solutions.

CODE: OUTPUT OF Soil moisture Sensor


ANUPAM TIWARI 180860109017(IOT)

CODE: OUTPUT OF PH monitor Sensor


ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 8
AIM :- IoT based home automation.

The Internet of Things (or commonly referred to as IoT) based Home Automation system, as the name
suggests aims to control all the devices of your smart home through internet protocols or cloud based
computing.
The IoT based Home Automation system offer a lot of flexibility over the wired systems s it comes with
various advantages like ease-of-use, ease-of-installation, avoid complexity of running through wires or
loose electrical connections, easy fault detection and triggering and above and all it even offers easy
mobility.

CODE :

OUTPUT of Blynk:
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 9
AIM: Familiarization with Raspberry Pi and its architecture. Perform necessary
software installation.
Architecture
The architecture of a RPI is based on a Broadcom
SOC BCM2835 which belongs to ARM Cortex
family with ARMv6 architecture. It is a 32 bit
RISC with a clock speed of 700 MHz and has eight
pipelines. This architecture is different from
Arduino processor which is X86 based and work
on CISC which is a better option it provides the
pipelining facilities. BCM2835 also provides the
branch prediction improving the flow in the
instruction pipeline. The advantages that are
obtained because of having a RISC architecture
are low transistor count, low power consumption
and therefore less heat gener ation. This
architecture also features three pipelines, viz,
ALU, MAC and load /store

Introduction:
Ultra-low-cost credit-card-sized single-board Linux computer Raspberry Pi developed by Raspberry
foundation (UK), is a small, powerful and lightweight ARM11 (Broadcom 2835) based development
board or a computer which is able to perform operations similar to a PC. The powerful graphics
capabilities and HDMI video output make it ideal for multimedia applications such as media centers
and narrowcasting solutions. With access to the internet, through Ethernet or Wi-Fi (with a USB
dongle), and a high definition output, the Raspberry Pi is an incredibly versatile piece of computing kit.
The Raspberry Pi is based on a Broadcom BCM2835 chip that is based on ARMv6. It does not feature a
built-in hard disk or solid-state drive, instead relying on an SD card for booting and long-term storage.
This single board computer is inexpensive yet comes packed with Ethernet, USB, a high powered
graphics engine, digital I/O ports and enough CPU power to accomplish your projects.
The Foundation provides Debian and Arch Linux ARM distributions for download. Tools are available
for Python as the main programming language.
The Raspberry Pi Model B features:
 The Broadcom BCM2835 ARM11 (used in most smart-phones) 700Mhz , System on Chip‟
Processor (Similar performance to a 300MHz Pentium 2 Processor).
 Integrated Video core 4 Graphics Processing Unit (GPU) capable of playing Full 1080p High
Definition Blu-Ray Quality Video (Roughly equivalent graphical processing power of an Xbox 1)
 512Mb SDRAM
 The free, versatile, and highly developer friendly Debian GNU/Linux Operating System
 2 x USB Ports
 HDMI Video Output
 RCA Video Output
 3.5mm Audio Output Jack
 10/100Mb Ethernet Port for Internet Access
 5V Micro USB Power Input Jack
 SD, MMC, SDIO Flash Memory Card Slot
ANUPAM TIWARI 180860109017(IOT)

 26-pin 2.54mm Header Expansion Slot (Which allow for peripherals and expansion boards)

Scratch view of raspberry pi Hardware Specification & Description:

Name Description
The Processor This chip is a 32 bit, 700 MHz System on Chip, which is built on the ARM11
architecture (ARMv6 instruction set). SoC-Broadcom BCM2835
The Secure Digital SD / MMC / SDIO card slot (3.3V card power support only)
Card slot
The USB port Model B has 2 Nos. USB 2.0 ports. Model A have only one current limited USB
port.
Ethernet port Model B has standard RJ45 connector and Model A does not.
HDMI connector The HDMI port provides digital video and audio output hence TV can be connected.
14 different video resolutions are supported.
Status LEDs ACT Green Light when the SD card is accessed
PWR Red Hooked upto 3.3V power
FDX Green ON if network adapter is full duplex.

LNX Green Network activity light.


100 Yellow On if the network connection is 100Mbps
Analog Audio out This is a standard 3.5mm mini analog audio jack,intented to drive high impedence
load(like amplified speakers).
Composite video This is a standard RCA-type jack that provides NTSC or PAL video signals.
out
Memory 512 MB in Model B and 256 MB in Model A
(SDRAM)
Supportable Arch Linux ARM, Debian GNU/Linux, Gentoo, Fedora, FreeBSD, NetBSD, Plan 9,
Operating ystems Raspbian OS, RISC OS, Slackware Linux

BLOCK DIAGRAM:
ANUPAM TIWARI 180860109017(IOT)

DETAILED DESCRIPTION OF COMPONENTS:

1) System Timer: The System Timer peripheral provides four 32-bit timer channels and a single 64-bit
free running counter. Each channel has an output compare register, which is compared against the 32
least significant bits of the free running counter values.

2) The Processor: At the heart of the Raspberry Pi is the same processor you would have found in the
iPhone 3G and the Kindle 2, so you can think of the capabilities of the Raspberry Pi as comparable to
those powerful little devices. This chip is a 32 bit, 700 MHz System on a Chip, which is built on the
ARM11 architecture. ARM chips come in a variety of architectures with different cores configured to
provide different capabilities at different price points

3) Interrupt controller: The interrupt controller can be programmed to interrupt the processor when
any of the status bits are set. The GPIO peripheral has three dedicated interrupt lines. Each GPIO bank
can generate an independent interrupt. The third line generates a single interrupt whenever any bit is set.

4) General Purpose Input/output (GPIO): 3.3 volt logic via 26 pin header (NOT 5 volt or short
tolerant) Pins can be configured to be input/output. General Purpose Input/output (GPIO) is a generic
pin on a chip whose behavior can be controlled by the user at run time. True GPIO (General Purpose
Input Output) pins that you can use to turn LEDs on and off etc.

5) PCM / I2S Audio: The PCM audio interface is an APB peripheral providing input and output of
telephony or high quality serial audio streams. It supports many classic PCM formats including I2S.
The PCM audio interface has 4 interface signals; PCM_CLK - bit clock. PCM_FS - frame sync signal.
PCM_DIN - serial data input. PCM_DOUT - serial data output. PCM is a serial format with a single bit
data_in and out.

6) DMA Controller: The BCM2835 DMA Controller provides a total of 16 DMA channels. Each
channel operates independently from the others and is internally arbitrated onto one of the 3 system
busses.

7) UART: The BCM2835 device has two UARTS. On mini UART and PL011 UART. The PL011
UART is a Universal Asynchronous Receiver/Transmitter. This is the ARM UART (PL011)
ANUPAM TIWARI 180860109017(IOT)

implementation. The UART performs serial-to-parallel conversion on data characters received from an
external peripheral device or modem, and parallel-to-serial conversion on data characters received from
the Advanced Peripheral Bus.

8) Pulse Width Modulator: PWM controller incorporates the following features: • Two independent
output bit-streams, clocked at a fixed frequency. • Bit-streams configured individually to output either
PWM or a serialized version of a 32-bit word. • PWM outputs have variable input and output
resolutions. • Serialize mode configured to load data to and/or read data from a FIFO storage block, that
can store up to eight 32-bit words. • Both modes clocked by clk_pwm which is nominally 100MHz, but
can be varied by clock manager.

9) CPU
 ARM 1176JZF-S (armv6k) 700MHz
 RISC Architecture and low power draw
 Not compatible with traditional PC software

10) MEMORY
 RAM:- 512MB (Model B rev.2), 256 MB (Model A, Model B rev.1)
 SD Card:- At least 4GB SD card is needed, and it should be a Class 4 card. Class 4 cards are capable
of transferring at least 4MB/sec. Some of the earlier Raspberry Pi boards had problems with Class 6 or
higher cards, which are capable of faster speeds but are less stable. One can also use micro SD card
using adapter. As there is no hard drive on the Pi; everything is stored on an SD Card. A protective case
is needed as the solder joints on the SD socket may fail if the SD card is accidentally bent.

11) Two USB 2.0 ports in RPi: Dual USB sockets on RPi model B, single on model A.It can be
expandable via regular or powered hubs. On the Model B there are two USB 2.0 ports, but only one on
the Model A. Some of the early Raspberry Pi boards were limited in the amount of current that they
could provide. Some USB devices can draw up 500mA.

12) Ethernet port: The model B has a standard RJ45 Ethernet port. The Model A does not, but can be
connected to a wired network by a USB Ethernet adapter (the port on the Model B is actually an
onboard USB to Ethernet adapter). WiFi connectivity via a USB dongle is another option.

13) HDMI connector: The HDMI port provides digital video and audio output. 14 different video
resolutions are supported, and the HDMI signal can be converted to DVI (used by many monitors),
composite (analog video signal usually carried over a yellow RCA connector), or SCART (a European
standard for connecting audio-visual equipment) with external adapters.

14) Video:
 HDMI or (digital) DVI via cheap adaptor/cable
 Composite NTSC/PAL via RCA
 Wide range of resolutions
 NO VGA without an add-on, nontrivial converter (Adafruit)

15) Audio:
 Via HDMI or from stereo jack
 Output only
 Support Maturity appears to be lagging

16) Networking
 10/100mbps via RJ45 on model B
ANUPAM TIWARI 180860109017(IOT)

 Wireless via USB add-on supported

17) Power: There is no power switch on the Pi. Micro-USB connector is used to supply power (this
isn‟t an additional USB port; it‟s only for power). Micro-USB was selected because cheap USB power
supplies are easy to find.
 Primary power via microUSB plug: a 1Amp cell charger works well, but to use a USB hard drive, 2
Amp power is needed.
 Model A about a quarter amp less PC USB port does not work
ANUPAM TIWARI 180860109017(IOT)

PRACTICAL : 10
AIM: To interface LED with Raspberry Pi and write Python programming to turn
ON/ OFF LED using Raspberry Pi.

The features of the Raspberry Pi’s GPIO Pins before proceeding with the further step of how to Blink
an LED using Raspberry Pin and its GPIO Pins. 

Components Required
 Raspberry Pi 3 Model B (any Raspberry Pi would do fine)
 5mm LED x 1
 1KΩ Resistor (1/4 Watt) x 1
 Mini Breadboard x 1
 Connecting wires
 Miscellaneous (Computer, Ethernet cable, Power Supply for Raspberry Pi etc.)

Circuit Diagram of Blinking LED with Raspberry Pi


In order to Blink an LED using Raspberry Pi, we need to first connect the LED to the Raspberry Pi.
There are two ways you can connect your LED to the Raspberry Pi. I’ll show both ways of connecting
the LED.
Circuit 1
In the first circuit, the anode of the LED is
connected to GPIO25 (Physical Pin 22) through a
1KΩ current limiting resistor. The cathode of the
LED is connected to the GND Pin.

In this circuit, the anode of the LED is connected


to the 3.3V supply pin of the Raspberry Pi
through the 1KΩ resistor. The cathode of the
LED is connected to GPIO25 (Physical Pin 22).

In this circuit, the GPIO pin acts as the sink


(GND).

NOTE: I’ll be concentrating on the first circuit,


where the GPIO pin GPIO25 acts as the source.
The code explained in the further sections will be
specific to this circuit. The code can also be used
for second circuit with slight or no modifications.
ANUPAM TIWARI 180860109017(IOT)

CODE:

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin ,set initial value to low
(off)
while True: # Run forever
GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second

Code for Blinking an LED with Raspberry Pi


#!/usr/bin/env python
import RPi.GPIO as GPIO # RPi.GPIO can be referred as GPIO from now
import time
ledPin = 22 # pin22
def setup():
GPIO.setmode(GPIO.BOARD) # GPIO Numbering of Pins
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin as output
GPIO.output(ledPin, GPIO.LOW) # Set ledPin to LOW to turn Off the LED
def loop():
while True:
print 'LED on'
GPIO.output(ledPin, GPIO.HIGH) # LED On
time.sleep(1.0) # wait 1 sec
print 'LED off'
GPIO.output(ledPin, GPIO.LOW) # LED Off
time.sleep(1.0) # wait 1 sec
def endprogram():
GPIO.output(ledPin, GPIO.LOW) # LED Off
GPIO.cleanup() # Release resources
if __name__ == '__main__': # Program starts from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the destroy() will be executed.
endprogram()
ANUPAM TIWARI 180860109017(IOT)

CONNECTION DIAGRAM

OUTPUT OF LED

You might also like