EID2204 Ans
EID2204 Ans
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
def display_brand(self):
print("Device Brand:", self.brand)
def display_sensor_details(self):
# Call base class method
self.display_brand()
print("Sensor Type :", self.sensor_type)
# 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.
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
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")
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
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
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)
else:
print("Gas concentration is normal.")
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
# Initialize LCD
lcd = I2cLcd(1, I2C_ADDR, LCD_ROWS, LCD_COLS)
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))
time.sleep(2)
except KeyboardInterrupt:
print("Program stopped by user.")
finally:
spi.close()
lcd.clear()
lcd.putstr("Goodbye!")
time.sleep(2)
lcd.clear()
# 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'
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)
time.sleep(10)
except KeyboardInterrupt:
print("Program stopped by user.")