0% found this document useful (0 votes)
111 views26 pages

Lab Manual

Uploaded by

sidhu.valavala
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)
111 views26 pages

Lab Manual

Uploaded by

sidhu.valavala
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/ 26

EXPERIMENT 1

1. Getting started with Raspberry Pi, Install Raspian on your SD


card
Aim
To install Raspberry Pi OS on an SD card for use with a Raspberry Pi.
Apparatus
 Raspberry Pi (any model)
 SD card (at least 8GB recommended)
 SD card reader (if your computer does not have one built-in)
 Computer (Windows, macOS, or Linux)
 Internet connection
 Raspberry Pi Imager or other imaging software (like Balena Etcher)
Description
1. Download Raspberry Pi OS:
o Visit the official Raspberry Pi website.
o Download the Raspberry Pi Imager or the image file for Raspberry
Pi OS.
2. Prepare the SD Card:
o Insert the SD card into your computer’s card reader.
o If using Raspberry Pi Imager, select the OS and choose the SD
card. Click "Write" to flash the OS onto the card.
o If using an image file, open Balena Etcher or similar software,
select the Raspberry Pi OS image, choose the SD card, and click
"Flash."
3. Safely Eject the SD Card:
o Once the writing process is complete, safely eject the SD card from
your computer.
4. Set Up the Raspberry Pi:
o Insert the SD card into the Raspberry Pi.
o Connect the Raspberry Pi to a monitor, keyboard, and power
supply.
o Power on the Raspberry Pi. It will boot into Raspberry Pi OS for
the first time and guide you through the initial setup (language, Wi-
Fi, updates, etc.).
Result
Upon successful installation and setup, the Raspberry Pi will boot into
Raspberry Pi OS, allowing you to start exploring and using it for various
projects.
EXPERIMENT 2
2. Python-based IDE (integrated development environments) for
the Raspberry Pi and how to trace and debug Python code on the
device
Aim
To set up a Python-based IDE on Raspberry Pi and learn how to trace and
debug Python code effectively.
Apparatus
 Hardware:
o Raspberry Pi (any model)
o Monitor, keyboard, and mouse
o MicroSD card (with Raspberry Pi OS installed)
 Software:
o Python (usually pre-installed)
o Integrated Development Environment (IDE) such as Thonny,
Geany, or Visual Studio Code
Description
1. Setting Up the IDE:
o Thonny:
 Usually pre-installed on Raspberry Pi OS. If not, install it
using:
bash
sudo apt update
sudo apt install thonny
o Geany:
 Install it using:
bash
sudo apt update
sudo apt install geany
o Visual Studio Code:
 Install by downloading from the official website or using:
bash
sudo apt update
sudo apt install code
2. Writing and Running Python Code:
o Open your chosen IDE and create a new Python file (e.g.,
example.py).
o Write a simple Python script to demonstrate tracing and debugging:
Python

def add(a, b):


return a + b

def main():
x=5
y = 10
result = add(x, y)
print("The result is:", result)

if __name__ == "__main__":
main()
3. Debugging the Code:
o In Thonny:
 Click the "Debug" button to step through the code,
inspecting variable values.
o Using pdb:
 Modify the code to include the pdb module:
Python
import pdb
def add(a, b):
return a + b
def main():
x=5
y = 10
pdb.set_trace() # Set a breakpoint
result = add(x, y)
print("The result is:", result)
if __name__ == "__main__":
main()

 Run the script, and it will pause at pdb.set_trace(), allowing


you to inspect and step through the code.
4. Using Visual Studio Code:
o Set breakpoints by clicking in the margin next to the line numbers.
o Run the debugger using the "Run" icon, and you can step through
your code and inspect variables.
Code
import pdb

def add(a, b):


return a + b

def main():
x=5
y = 10
pdb.set_trace() # Start debugger here
result = add(x, y)
print("The result is:", result)

if __name__ == "__main__":
main()
Result
Upon running the script in the IDE, you will:
 See the output of the result printed as "The result is: 15" after debugging.
 If using pdb, you can inspect variable values at the breakpoint and step
through the execution, helping you understand the flow of the program.
EXPERIMENT 3
3. Using Raspberry pi
a. Calculate the distance using distance sensor.
Aim
To calculate the distance between an object and the distance sensor
using a Raspberry Pi and an ultrasonic distance sensor.
Apparatus
1. Raspberry Pi (with GPIO pins)
2. HC-SR04 Ultrasonic Distance Sensor
3. Jumper Wires (Female to Male and Male to Male as needed)
4. Breadboard (optional for wiring convenience)
Description
The HC-SR04 ultrasonic sensor emits sound waves at a frequency of
40kHz. When it encounters an obstacle, it reflects the waves back to
the sensor. The sensor calculates the time between sending the pulse
and receiving the echo to determine the distance to the object. The
formula used is:
Distance=Time×Speed of Sound / 2
Speed of Sound in air is approximately 343 m/s.
 Trigger Pin on the HC-SR04 sends a pulse, and the Echo Pin
receives the reflection.

Code
import RPi.GPIO as GPIO
import time

# GPIO setup
GPIO.setmode(GPIO.BCM)
TRIG_PIN = 23
ECHO_PIN = 24
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)

def measure_distance():
# Send a 10us pulse to trigger the sensor
GPIO.output(TRIG_PIN, True)
time.sleep(0.00001)
GPIO.output(TRIG_PIN, False)

# Record the start time


while GPIO.input(ECHO_PIN) == 0:
start_time = time.time()

# Record the end time


while GPIO.input(ECHO_PIN) == 1:
end_time = time.time()

# Calculate the duration of the pulse


duration = end_time - start_time
# Calculate distance in cm
distance = (duration * 34300) / 2 # 34300 cm/s is the speed of
sound in air
return distance

try:
while True:
dist = measure_distance()
print(f"Distance: {dist:.2f} cm")
time.sleep(1)
except KeyboardInterrupt:
print("Measurement stopped by User")
finally:
GPIO.cleanup()
Result
 Run the code on the Raspberry Pi.
 The terminal will display the distance between the sensor and an
object in front of it, updating every second.
b. Basic LED functionality
Aim
To control an LED (turn it on, off, and blink) using a Raspberry Pi and Python
programming.
Apparatus
1. Raspberry Pi (with GPIO pins)
2. LED (any color)
3. 330Ω Resistor (to limit current and protect the LED)
4. Jumper Wires (Female to Male as needed)
5. Breadboard (optional, for easier connections)
Description
The Raspberry Pi’s GPIO pins can be used to control basic electronic
components like LEDs. By programming these pins, we can send signals to turn
an LED on and off. The resistor limits the current flowing through the LED,
preventing damage.
In this setup:
 The GPIO pin acts as an output pin to control the LED.
 The LED has two terminals: the longer leg (anode) connects to the
positive (GPIO pin), and the shorter leg (cathode) connects to the ground
(GND) through a resistor.
Code
import RPi.GPIO as GPIO
import time

# GPIO setup
GPIO.setmode(GPIO.BCM) # BCM mode allows using GPIO numbers
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
try:
print("Turning LED on")
GPIO.output(LED_PIN, GPIO.HIGH) # Turn LED on
time.sleep(2)

print("Turning LED off")


GPIO.output(LED_PIN, GPIO.LOW) # Turn LED off
time.sleep(2)

print("Blinking LED")
for _ in range(5):
GPIO.output(LED_PIN, GPIO.HIGH) # LED on
time.sleep(1)
GPIO.output(LED_PIN, GPIO.LOW) # LED off
time.sleep(1)

except KeyboardInterrupt:
print("Process interrupted by user")
finally:
GPIO.cleanup() # Reset GPIO settings
Result
 When you run the code, the LED will:
1. Turn on for 2 seconds.
2. Turn off for 2 seconds.
3. Blink five times, with each cycle (on and off) lasting 1 second.
EXPERIMENT 4
4.Raspberry Pi interact with online services through the use of
public APIs and SDKs
Aim

To connect a Raspberry Pi to an online service and retrieve data through a


public API using Python programming.

Apparatus
1. Raspberry Pi (with internet access via Wi-Fi or Ethernet)

2. Python (installed on the Raspberry Pi)

3. API Key (from the chosen public API service, e.g., OpenWeatherMap for
weather data)

4. Internet Connection
Description
By using APIs, the Raspberry Pi can interact with online services to fetch data
or perform actions. In this case, we'll use the OpenWeatherMap API to get
current weather data for a specified city. After retrieving the data, the program
will parse and display the temperature and weather description.

Code
This Python code uses the OpenWeatherMap API to fetch and display weather
data. Replace YOUR_API_KEY with a valid API key from OpenWeatherMap.

import requests

# Replace with your own OpenWeatherMap API key


API_KEY = "YOUR_API_KEY"

CITY = "London" # Replace with desired city

BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def get_weather(city):

# Create the request URL

url = f"{BASE_URL}?q={city}&appid={API_KEY}&units=metric"

# Send request to API

response = requests.get(url)
# Check if the response is successful

if response.status_code == 200:
data = response.json()

# Parse JSON response

main = data['main']
weather = data['weather'][0]
temperature = main['temp']

description = weather['description']

# Display weather data

print(f"Weather in {city}:")

print(f"Temperature: {temperature}°C")
print(f"Description: {description.capitalize()}")

else:

print("Error fetching weather data. Please check your API key and city
name.")

# Fetch and display weather data for the specified city


get_weather(CITY)
Result
 Run the script on the Raspberry Pi.

 The terminal will display the weather data for the specified city,
including:

o Temperature in degrees Celsius

o Weather description (e.g., "Clear sky", "Rain")

Example Output
Weather in London:

Temperature: 15°C

Description: Clear sky


EXPERIMENT 5
5. Using Arduino
a. Calculate the distance using distance sensor.
Aim
To measure the distance between an object and an ultrasonic distance sensor
using an Arduino.

Apparatus
1. Arduino Board (e.g., Arduino Uno)

2. HC-SR04 Ultrasonic Distance Sensor


3. Jumper Wires (Male to Female and Male to Male as needed)

4. Breadboard (optional, for easier wiring)

Description

The HC-SR04 ultrasonic sensor measures distance by emitting ultrasonic


waves, which reflect off an object and return to the sensor. The sensor
calculates the distance based on the time taken for the echo to return. This time
is then converted to a distance using the speed of sound.
The formula used for calculating distance is:
Distance=Time×Speed of Sound/2

where the Speed of Sound is approximately 343 m/s in air.

Code
This Arduino code sends a pulse to the HC-SR04’s trigger pin, waits for the
echo, and calculates the distance.

#define TRIG_PIN 9 // Trigger pin on the HC-SR04

#define ECHO_PIN 10 // Echo pin on the HC-SR04

void setup() {
Serial.begin(9600); // Start serial communication for debugging
pinMode(TRIG_PIN, OUTPUT);

pinMode(ECHO_PIN, INPUT);

void loop() {
// Send a 10us pulse to trigger the sensor

digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);

digitalWrite(TRIG_PIN, HIGH);

delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Measure the time for the echo to return

long duration = pulseIn(ECHO_PIN, HIGH);

// Calculate distance in cm

float distance = (duration * 0.0343) / 2;

// Print the distance to the serial monitor

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

delay(1000); // Wait for a second before the next measurement


}

Result
 Upload the code to the Arduino.

 Open the Serial Monitor to view the distance readings.

The output will display the distance (in centimeters) between the sensor and any
object in front of it, updating every second.

Example Output
Distance: 15.35 cm

Distance: 16.24 cm

Distance: 14.50 cm
b. Basic LED functionality
Aim

To control an LED (turn it on, off, and blink) using an Arduino and simple
programming.

Apparatus
1. Arduino Board (e.g., Arduino Uno)
2. LED (any color)

3. 220Ω Resistor (to limit current and protect the LED)

4. Jumper Wires
5. Breadboard (optional, for easier wiring)

Description
The Arduino can be programmed to control basic electronic components like
LEDs. By setting up an LED as an output component on one of the Arduino’s
digital pins, you can control its state. The resistor limits current flow, protecting
the LED and Arduino pin.

In this setup:

 The positive (anode) side of the LED connects to an Arduino digital


output pin.

 The negative (cathode) side connects to GND through a resistor.

Code
This Arduino code turns the LED on, off, and makes it blink.

#define LED_PIN 13 // Define the pin connected to the LED

void setup() {

pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output

}
void loop() {

// Turn LED on

digitalWrite(LED_PIN, HIGH);

delay(1000); // Wait for 1 second

// Turn LED off

digitalWrite(LED_PIN, LOW);
delay(1000); // Wait for 1 second

Result
 Upload the code to the Arduino.

 The LED connected to pin 13 will blink on and off with a delay of 1
second between each state change.

Example Output
The LED will:

1. Turn on for 1 second.

2. Turn off for 1 second.

3. Repeat this cycle indefinitely.


c. Calculate temperature using temperature sensor
Aim
To measure temperature using an Arduino and an LM35 temperature sensor.

Apparatus
1. Arduino Board (e.g., Arduino Uno)

2. LM35 Temperature Sensor

3. Jumper Wires
4. Breadboard (optional, for easier wiring)

Description
The LM35 is a temperature sensor that outputs a voltage linearly proportional to
the temperature in degrees Celsius. For every degree Celsius rise, the output
voltage increases by 10 mV. For example, at 25°C, the LM35 outputs 250 mV.

The analog output of the LM35 connects to an analog input pin on the Arduino,
which reads the voltage and converts it to a temperature value.

Code
This Arduino code reads the voltage from the LM35 sensor and calculates the
temperature in degrees Celsius.

#define SENSOR_PIN A0 // Define the analog input pin for the LM35

void setup() {

Serial.begin(9600); // Start serial communication for output

void loop() {

// Read the analog voltage from the sensor


int sensorValue = analogRead(SENSOR_PIN);
// Convert the analog reading to voltage (assuming 5V reference voltage)

float voltage = sensorValue * (5.0 / 1023.0);

// Convert the voltage to temperature in Celsius

float temperatureC = voltage * 100.0; // 10mV per degree Celsius

// Print the temperature in Celsius


Serial.print("Temperature: ");

Serial.print(temperatureC);

Serial.println(" °C");

delay(1000); // Wait for a second before taking another reading

Result
 Upload the code to the Arduino.

 Open the Serial Monitor to view the temperature readings, which will be
displayed in degrees Celsius and updated every second.

Example Output
Temperature: 24.50 °C

Temperature: 24.62 °C
Temperature: 24.48 °C
EXPERIMENT 6
6. Using Node MCU
a. Calculate the distance using distance sensor.
Aim
To calculate the distance between an object and the ultrasonic distance sensor
using a NodeMCU ESP8266.

Apparatus

1. NodeMCU ESP8266

2. HC-SR04 Ultrasonic Distance Sensor


3. Jumper Wires
4. Breadboard (optional for easy wiring)

Description

The HC-SR04 sensor emits ultrasonic waves and receives the echo when they
reflect off an object. The time between sending and receiving the signal is used
to calculate the distance to the object, with the following formula:
Distance=Time×Speed of Sound / 2

Here, the Speed of Sound is approximately 343 m/s (or 0.0343 cm/µs). The
distance calculation divides by 2 because the pulse travels to the object and
back.

Code

This code uses the ESP8266WiFi library and built-in functions to calculate the
distance and print it via serial communication.

#define TRIG_PIN D1 // Define the trigger pin

#define ECHO_PIN D2 // Define the echo pin

void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud
pinMode(TRIG_PIN, OUTPUT); // Set trigger pin as output

pinMode(ECHO_PIN, INPUT); // Set echo pin as input

void loop() {
// Send a 10µs pulse to trigger the sensor

digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);

digitalWrite(TRIG_PIN, HIGH);

delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Measure the time for the echo to return

long duration = pulseIn(ECHO_PIN, HIGH);

// Calculate distance in cm

float distance = (duration * 0.0343) / 2;

// Print the distance

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

delay(1000); // Wait for a second before the next measurement


}

Result
 Upload the code to the NodeMCU.

 Open the Serial Monitor (set to 115200 baud rate) to view the distance
readings.

Example Output
Distance: 15.32 cm

Distance: 16.48 cm

Distance: 14.92 cm
b. Basic LED functionality
Aim
To control an LED (turn it on, off, and blink) using a NodeMCU ESP8266.

Apparatus
1. NodeMCU ESP8266
2. LED (any color)

3. 220Ω Resistor (to limit current and protect the LED)

4. Jumper Wires
5. Breadboard (optional, for easier wiring)

Description

Using a digital output pin on the NodeMCU, we can control the LED's state by
sending a high or low signal to the pin. The resistor limits the current flowing
through the LED, protecting it and the NodeMCU pin.
In this setup:

 The positive (anode) leg of the LED is connected to a digital pin on the
NodeMCU.

 The negative (cathode) leg is connected to GND through a resistor.

Code
This code turns the LED on, off, and makes it blink.

#define LED_PIN D1 // Define the pin connected to the LED

void setup() {
pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output

}
void loop() {
// Turn LED on

digitalWrite(LED_PIN, HIGH);

delay(1000); // Wait for 1 second

// Turn LED off


digitalWrite(LED_PIN, LOW);

delay(1000); // Wait for 1 second


}

Result
 Upload the code to the NodeMCU.

 The LED will blink on and off with a delay of 1 second between each
state change.

Example Output
The LED will:

1. Turn on for 1 second.

2. Turn off for 1 second.

3. Repeat this cycle indefinitely.

You might also like