0% found this document useful (0 votes)
4 views13 pages

EID2204 Ans

The document contains a series of Python programs that demonstrate various functionalities, including handling complex numbers, string manipulation, list operations, class definitions, inheritance, file handling, and interfacing with hardware like Raspberry Pi. It includes examples for reading sensors, controlling devices, and uploading data to ThingSpeak. Each program is designed to illustrate specific programming concepts and practical applications in IoT and automation.

Uploaded by

Leroy Golconda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

EID2204 Ans

The document contains a series of Python programs that demonstrate various functionalities, including handling complex numbers, string manipulation, list operations, class definitions, inheritance, file handling, and interfacing with hardware like Raspberry Pi. It includes examples for reading sensors, controlling devices, and uploading data to ThingSpeak. Each program is designed to illustrate specific programming concepts and practical applications in IoT and automation.

Uploaded by

Leroy Golconda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Write a Python program that allows the user to input a complex number and displays its real

and imaginary parts.

Write a Python program that accepts a string and reverses it without using the built-in
reverse() method.

Write a Python program that takes a list of numbers as input and prints the sum and average
of the numbers.

Write a Python program to make a new list that will store squares of elements from the
existing list [10,8,6,4,2]

Write a program in Python that accepts ten values and returns the maximum of them.
(Use *args)
# Function to find maximum using *args
def find_maximum(*args):
max_value = args[0]
for num in args:
if num > max_value:
max_value = num
return max_value
# Input: Accept 10 integer numbers from user
num = input("Enter number: ")
a=eval(num)
# Call the function using *args
maximum = max(a)
# Output
print("The maximum value is:", maximum)
Write a Python program to display the Fibonacci sequence (first 20 terms) using the recursive
function.
# Define a recursive function to find Fibonacci number
def fibonacci(n):
if n == 0:
return 0 # First term
elif n == 1:
return 1 # Second term
else:
return fibonacci(n - 1) + fibonacci(n - 2) # Recursive step

# Print the first 20 Fibonacci numbers


print("Fibonacci sequence (first 20 terms):")
for i in range(20):
print(fibonacci(i), end=" ")
Write a Python program to define a class Student with data members: name, branch,
and grade. Include appropriate member functions to input and display student details.
# Define a class called Student
class Student:
# Function to input student details
def input_details(self):
self.name = input("Enter student name: ")
self.branch = input("Enter branch: ")
self.grade = input("Enter grade: ")

# Function to display student details


def display_details(self):
print("\nStudent Details:")
print("Name :", self.name)
print("Branch :", self.branch)
print("Grade :", self.grade)

# Create an object of Student class


s = Student()

# Call the input function to get data from user


s.input_details()

# Call the display function to show the data


s.display_details()
Write a Python program to demonstrate single level inheritance using the following
classes:
 Device: contains an attribute brand.
Sensor: inherits from Device and includes an attribute sensor_type.
# Base class
class Device:
def __init__(self, brand):
self.brand = brand

def display_brand(self):
print("Device Brand:", self.brand)

# Derived class (inherits from Device)


class Sensor(Device):
def __init__(self, brand, sensor_type):
# Call the constructor of the base class
super().__init__(brand)
self.sensor_type = sensor_type

def display_sensor_details(self):
# Call base class method
self.display_brand()
print("Sensor Type :", self.sensor_type)

# Create an object of Sensor class


s = Sensor("Honeywell", "Temperature")

# Display details
s.display_sensor_details()
Write a Python program that reads a list of numbers from a text file and checks whether a
user-specified number is present in the list. Display an appropriate message based on the
result.

Write a Python program to:


o Read a set of temperature values from a text file
o Store all values > 30°C in another file
Use try-except-finally blocks to manage file operations and errors.
try:
# Try to open and read from the input file
input_file = open("temps.txt", "r")
content = input_file.read()

# Convert the string into a list of numbers


temp_list = [int(x) for x in content.split()]

# Create a list of temperatures greater than 30


high_temps = [temp for temp in temp_list if temp > 30]

# Write the high temperatures to another file


output_file = open("high_temps.txt", "w")
for temp in high_temps:
output_file.write(str(temp) + "\n")

print("High temperatures saved to 'high_temps.txt'.")

except FileNotFoundError:
print("Error: 'temps.txt' not found.")

except ValueError:
print("Error: Make sure the file contains only numbers.")

except Exception as e:
print("Something went wrong:", e)

finally:
# Close the files if they were opened
try:
input_file.close()
except:
pass
try:
output_file.close()
except:
pass
Write a Python program for home automation using Raspberry Pi. Include:
 Device control through GPIOs
 Sensor interface (e.g., IR sensor or PIR sensor)
 WiFi-controlled LED
Data logging and cloud upload via ThingSpeak
Answer :
import RPi.GPIO as GPIO
import time
import requests

# ==== GPIO Setup ====


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Device connected to GPIO


DEVICE_PIN = 17 # Example: Relay or Bulb
SENSOR_PIN = 18 # PIR or IR sensor
LED_PIN = 27 # LED controlled via WiFi

# Setup GPIO pins


GPIO.setup(DEVICE_PIN, GPIO.OUT)
GPIO.setup(SENSOR_PIN, GPIO.IN)
GPIO.setup(LED_PIN, GPIO.OUT)

# ==== ThingSpeak Details ====


THINGSPEAK_API_KEY = 'YOUR_API_KEY_HERE'
THINGSPEAK_URL = 'https://api.thingspeak.com/update'

def upload_to_thingspeak(sensor_value):
try:
response = requests.get(THINGSPEAK_URL, params={
'api_key': THINGSPEAK_API_KEY,
'field1': sensor_value
})
print("Data uploaded to ThingSpeak:", response.text)
except:
print("Failed to upload data")

# ==== Main Loop ====


try:
print("Home Automation System Running...")

while True:
sensor_state = GPIO.input(SENSOR_PIN)

if sensor_state == 1:
print("Motion Detected! Turning ON device.")
GPIO.output(DEVICE_PIN, GPIO.HIGH) # Turn ON device
GPIO.output(LED_PIN, GPIO.HIGH) # Turn ON LED
else:
print("No motion. Turning OFF device.")
GPIO.output(DEVICE_PIN, GPIO.LOW) # Turn OFF device
GPIO.output(LED_PIN, GPIO.LOW) # Turn OFF LED

# Upload sensor status (1 or 0) to ThingSpeak


upload_to_thingspeak(sensor_state)

time.sleep(10) # Delay to avoid too many requests

except KeyboardInterrupt:
print("Program stopped by user.")

finally:
GPIO.cleanup()

Write a Python program to interface a Raspberry Pi with a gas sensor (like MQ-2) to monitor
air quality. The program should read the gas concentration level from the sensor and trigger
an alert if it exceeds a specified threshold.
Answer :
import spidev
import time
import RPi.GPIO as GPIO

# Setup SPI for MCP3008 ADC


spi = spidev.SpiDev()
spi.open(0, 0) # Bus 0, device 0
spi.max_speed_hz = 1350000

# Gas threshold (adjust as per calibration)


GAS_THRESHOLD = 300 # Example threshold value (0-1023 ADC scale)

# Function to read SPI data from MCP3008 channel


def read_adc(channel):
# MCP3008 protocol: 3 bytes transaction
# Start bit + single/diff bit + channel (3 bits)
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data

try:
print("Starting MQ-2 Gas Sensor Monitoring...")
while True:
gas_level = read_adc(0) # Read channel 0 where MQ-2 is connected
print("Gas Level:", gas_level)

if gas_level > GAS_THRESHOLD:


print("ALERT! Gas concentration is HIGH!")

else:
print("Gas concentration is normal.")

time.sleep(2) # Delay between readings

except KeyboardInterrupt:
print("Program stopped by user.")

finally:
spi.close()

Write a Python program that interfaces with a pH sensor connected to a Raspberry Pi, reads
the analog data, converts it to pH value, and displays it on a connected LCD screen.
Answer :
import spidev
import time
from lcd_api import LcdApi # Import LCD API (make sure you have this or your own
driver)
from i2c_lcd import I2cLcd # I2C LCD driver

# MCP3008 SPI setup


spi = spidev.SpiDev()
spi.open(0, 0) # SPI bus 0, device 0
spi.max_speed_hz = 1350000

# LCD I2C address (change if different)


I2C_ADDR = 0x27
LCD_ROWS = 2
LCD_COLS = 16

# Initialize LCD
lcd = I2cLcd(1, I2C_ADDR, LCD_ROWS, LCD_COLS)

# Function to read ADC channel


def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data

# Convert ADC value to pH (assuming linear conversion)


# You must calibrate your sensor for accurate conversion.
def adc_to_ph(adc_value):
# Example calibration:
# ADC 0 -> pH 0
# ADC 1023 -> pH 14
ph = (adc_value / 1023.0) * 14.0
return round(ph, 2)

try:
lcd.clear()
lcd.putstr("pH Sensor Ready")
time.sleep(2)

while True:
adc_value = read_adc(0) # Read channel 0 where pH sensor is connected
ph_value = adc_to_ph(adc_value)

lcd.clear()
lcd.putstr("pH Value:")
lcd.move_to(0, 1)
lcd.putstr(str(ph_value))

print("ADC:", adc_value, "pH:", ph_value)

time.sleep(2)

except KeyboardInterrupt:
print("Program stopped by user.")

finally:
spi.close()
lcd.clear()
lcd.putstr("Goodbye!")
time.sleep(2)
lcd.clear()

Design a Python-based IoT application using Raspberry Pi where:


 A temperature sensor is connected via GPIO
 Data is read and displayed locally
 Readings above 40°C are sent to ThingSpeak
Abnormal values are logged into a local file
Answer :
import Adafruit_DHT
import time
import requests

# Sensor setup
SENSOR = Adafruit_DHT.DHT11 # Use DHT22 if you have that sensor
GPIO_PIN = 4 # GPIO pin where sensor is connected

# ThingSpeak details
THINGSPEAK_API_KEY = 'YOUR_API_KEY'
THINGSPEAK_URL = 'https://api.thingspeak.com/update'

# Log file for abnormal values


LOG_FILE = 'temp_abnormal_log.txt'

def log_abnormal(temp):
with open(LOG_FILE, 'a') as file:
file.write(f"High Temp Alert: {temp} C at {time.strftime('%Y-%m-%d %H:%M:%S')}\
n")

def send_to_thingspeak(temp):
try:
response = requests.get(THINGSPEAK_URL, params={
'api_key': THINGSPEAK_API_KEY,
'field1': temp
})
if response.status_code == 200:
print("Data sent to ThingSpeak successfully.")
else:
print("Failed to send data to ThingSpeak.")
except Exception as e:
print("Error sending data:", e)

try:
print("Starting Temperature Monitoring...")
while True:
humidity, temperature = Adafruit_DHT.read_retry(SENSOR, GPIO_PIN)

if temperature is not None:


print(f"Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%")

if temperature > 40:


print("Temperature above 40°C! Logging and sending to ThingSpeak...")
log_abnormal(temperature)
send_to_thingspeak(temperature)
else:
print("Failed to get reading. Try again!")

time.sleep(10)

except KeyboardInterrupt:
print("Program stopped by user.")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy