Lab Manual
Lab Manual
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()
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)
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("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
Apparatus
1. Raspberry Pi (with internet access via Wi-Fi or Ethernet)
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
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def get_weather(city):
url = f"{BASE_URL}?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
# Check if the response is successful
if response.status_code == 200:
data = response.json()
main = data['main']
weather = data['weather'][0]
temperature = main['temp']
description = weather['description']
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.")
The terminal will display the weather data for the specified city,
including:
Example Output
Weather in London:
Temperature: 15°C
Apparatus
1. Arduino Board (e.g., Arduino Uno)
Description
Code
This Arduino code sends a pulse to the HC-SR04’s trigger pin, waits for the
echo, and calculates the distance.
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);
// Calculate distance in cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Result
Upload the code to the Arduino.
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)
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:
Code
This Arduino code turns the LED on, off, and makes it blink.
void setup() {
}
void loop() {
// Turn LED on
digitalWrite(LED_PIN, HIGH);
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:
Apparatus
1. Arduino Board (e.g., Arduino Uno)
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() {
void loop() {
Serial.print(temperatureC);
Serial.println(" °C");
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
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.
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud
pinMode(TRIG_PIN, OUTPUT); // Set trigger pin as output
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);
// Calculate distance in cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
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)
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.
Code
This code turns the LED on, off, and makes it blink.
void setup() {
pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output
}
void loop() {
// Turn LED on
digitalWrite(LED_PIN, HIGH);
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: