0% found this document useful (0 votes)
14 views6 pages

C 0 de

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

C 0 de

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

1.

// Define LED pins


const int led1 = 11;
const int led2 = 12;
const int led3 = 13;
void setup() {
// Initialize LED pins as output
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
// Turn on LED 1 for 1 second
digitalWrite(led1, HIGH);
delay(1000); // 1000 milliseconds = 1 second
digitalWrite(led1, LOW);
// Turn on LED 2 for 2 seconds
digitalWrite(led2, HIGH);
delay(2000); // 2000 milliseconds = 2 seconds
digitalWrite(led2, LOW);
// Turn on LED 3 for 3 seconds
digitalWrite(led3, HIGH);
delay(3000); // 3000 milliseconds = 3 seconds
digitalWrite(led3, LOW);
}

2.
#include <PulseSensorPlayground.h>

// Create an instance of the PulseSensorPlayground class


PulseSensorPlayground pulseSensor;

const int pulsePin = A0; // Analog pin where the pulse sensor is connected

void setup() {
Serial.begin(9600);

// Initialize the PulseSensorPlayground library


pulseSensor.analogInput(pulsePin);
pulseSensor.setThreshold(550); // Set the threshold for detecting beats
pulseSensor.begin();
}

void loop() {
// Read the value from the sensor
int signal = pulseSensor.getBeatsPerMinute();

// Print the heart rate if it is valid


if (signal > 0) {
Serial.print("Heart Rate: ");
Serial.print(signal);
Serial.println(" bpm");
} else {
Serial.println("No pulse detected.");
}

// Delay for 1 second


delay(1000);
}
3.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
lcd.begin();
lcd.backlight();
// Print initial message
lcd.setCursor(0, 0);
lcd.print("System Monitor");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(2000);
}

void loop() {
// Update system stats
float networkUtilization = getNetworkUtilization();
float cpuLoad = getCPULoad();
float diskSpace = getDiskSpace();
// Display system stats on LCD
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0);
lcd.print("Network: ");
lcd.print(networkUtilization);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("CPU: ");
lcd.print(cpuLoad);
lcd.print("% Disk: ");
lcd.print(diskSpace);
lcd.print("GB");
delay(5000); // Delay for 5 seconds before updating again
}

// Function to get network utilization


float getNetworkUtilization() {
// Implement your code to get network utilization
return 50.5; // Placeholder value for demonstration
}

// Function to get CPU load


float getCPULoad() {
// Implement your code to get CPU load
return 30.2; // Placeholder value for demonstration
}
// Function to get disk space
float getDiskSpace() {
// Implement your code to get disk space
return 25.7; // Placeholder value for demonstration
}

4.
// Define pin numbers
const int gasPin = A0;
const int ledPin = 8;
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(ledPin, OUTPUT); // Set LED pin as output
}
void loop() {
// Read gas sensor value
int gasValue = analogRead(gasPin);
// Map gas sensor value to LED brightness
int brightness = map(gasValue, 0, 1023, 0, 255);
// Display gas sensor value on serial monitor
Serial.print("Gas Level: ");
Serial.println(gasValue);
// Turn on LED based on gas sensor value
analogWrite(ledPin, brightness);
delay(1000); // Delay for 1 second
}

5.
import RPi.GPIO as GPIO
import time

# Set GPIO pin numbers


pir_pin = 12 # PIR sensor output pin
led_pin = 11 # LED pin

# Setup GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pir_pin, GPIO.IN)
GPIO.setup(led_pin, GPIO.OUT)

# PIR sensor pin as input


# LED pin as output
try:
print("PIR Sensor Test (CTRL+C to exit)")
time.sleep(2) # Warmup time for PIR sensor
print("Ready")
while True:
if GPIO.input(pir_pin): # If motion is detected
print("Motion Detected!")
GPIO.output(led_pin, GPIO.HIGH) # Turn on LED

else :

print("Motion not detected")


GPIO.output(led_pin, GPIO.LOW)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nExiting...")
finally:
GPIO.cleanup()

6.
import time
import board
import adafruit_dht
import thingspeak
from rpi_lcd import LCD

# Define your ThingSpeak channel parameters


channel_id = 2595470
write_key = '86CNU3LZRKBSRJW9'
# Initialize the ThingSpeak channel
channel = thingspeak.Channel(id=channel_id, api_key=write_key)

# Initialize the LCD


lcd = LCD()

# Initialize the sensor (DHT11 connected to GPIO 4)


sensor = adafruit_dht.DHT11(board.D4, use_pulseio=False)

while True:
try:
# Read the sensor data
temperature_c = sensor.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = sensor.humidity

# Print the values to the serial port


print("Temp={0:0.1f}C, Temp={1:0.1f}F, Humidity={2:0.1f}
%".format(temperature_c, temperature_f, humidity))

# Display the values on the LCD


lcd.text("Temp={0}C".format(temperature_c), 1)
lcd.text("Humi={0}%".format(humidity), 2)

# Send the data to ThingSpeak


response = channel.update({'field1': temperature_c, 'field2': humidity})
print("Data sent to ThingSpeak. Response:", response)

except RuntimeError as error:


# Errors happen fairly often with DHT sensors, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
sensor.exit()
raise error

# Wait before taking the next reading


time.sleep(15)

7.
import RPi.GPIO as GPIO
import smtplib
from email.mime.text import MIMEText
import time

# Email settings
EMAIL_ADDRESS = '[email protected]' # Your email address
EMAIL_PASSWORD = ' ' # Your email password
TO_EMAIL = '' # Recipient's email address

# Set up GPIO
WPIN = 4
BUZZERPIN=17
GPIO.setmode(GPIO.BCM)
GPIO.setup(WPIN, GPIO.IN)
GPIO.setup(BUZZERPIN, GPIO.OUT)

# Function to send email notification


def send_email():
msg = MIMEText('Water sensor detected water!')
msg['Subject'] = 'Alert:Water sensor is wet!'
msg['From'] = EMAIL_ADDRESS
msg['To'] = TO_EMAIL

try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.send_message(msg)
print("Email sent successfully")
except Exception as e:
print(f"Failed to send email: {e}")

# Main loop
try:
print("Water Sensor with email (CTRL+C to exit)")
time.sleep(2)
print("Ready")

while True:
if GPIO.input(WPIN): # If water is detected
print("Water sensor is wet!")
GPIO.output(BUZZERPIN,True)
send_email()
time.sleep(5) # Delay to avoid multiple detections
GPIO.output(BUZZERPIN,False)

except KeyboardInterrupt:
print("Program terminated")
finally:
GPIO.cleanup() # Clean up GPIO on exit

8.
import time
import RPi.GPIO as GPIO
import thingspeak

BUZZER_PIN = 33
LDR_PIN = 3
LED = 11

channel_id = "" # Add your ThingSpeak channel ID here


write_key = "" # Add your ThingSpeak write API key here

def setup_gpio():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(LDR_PIN, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)

def ldr():
channel = thingspeak.Channel(id=channel_id, api_key=write_key)
while True:
ldr_value = GPIO.input(LDR_PIN)
if ldr_value == 1:
print("High: Switch on buzzer")
GPIO.output(BUZZER_PIN, True)
print("LED ON")
GPIO.output(LED, True)
else:
print("Low: Don't switch on buzzer")
GPIO.output(BUZZER_PIN, False)
print("LED OFF")
GPIO.output(LED, False)

time.sleep(0.3)

LDRData = ldr_value
BuzzerData = 1 if ldr_value == 1 else 0

# Send data to ThingSpeak


try:
response = channel.update({'field1': LDRData, 'field2': BuzzerData})
print(f"LDRData: {LDRData}, BuzzerData: {BuzzerData}")
print("ThingSpeak Response:", response)
except Exception as e:
print("Connection failed:", e)

if __name__ == "__main__":
setup_gpio() # Initialize GPIO once
try:
ldr() # Start the LDR monitoring loop
except KeyboardInterrupt:
print("Program interrupted")
finally:
GPIO.cleanup() # Clean up GPIO settings

You might also like