Пример #1
0
def customCallback(client, userdata, message):
    payload = json.loads(message.payload)
    if payload["deviceID"] == "CA2":
        lcd = LCD()
        lcd.clear()
        takePic()
        lcd.text('Time to eat', 1)
        lcd.text('medicine', 2)
        buzzerOn()
        lcd.clear()
Пример #2
0
def customCallback(client, userdata, message): #get the updated string for the sign from the topic
	print("Received a new message: ")
	print(message.payload)
	message = message.payload
	lcd = LCD()
	data = message.split(":") #split the message from user, string contains a : to seperate row 1 and row 2 for LCD
	lcd.text(data[0],1) #display text onto row 1 of lcd
	lcd.text(data[1],2) #display text onto row 2 of lcd
	print("--------------\n\n")
	f = open("led.txt","w")
	f.write(message)
	f.close()
Пример #3
0
def test_lcd():
    print('Testing LCD...')
    lcd = LCD()
    lcd.text('Works', 1)
    ans = input('Is Works printed on the LCD? y/n: ')
    lcd.clear()
    return ans == 'y'
Пример #4
0
def lcd_display(text_list):

    lcd = LCD()
    print "displaying"
    print text_list
    try:
        if 'clear' in text_list[0]:
            lcd.clear()
        else:
            lcd.text(text_list[0], 1)
            lcd.text(text_list[1], 2)
        sleep(1)
    except Exception:
        lcd.clear()
Пример #5
0
def button_sens():
    global passEnter
    global passwordCounter
    global passEnterDisplay
    passwordCounter = 0
    while (True):
        for j in range(4):
            GPIO.output(COL[j], 0)
            for i in range(4):
                if GPIO.input(ROW[i]) == 0:
                    bz.on()
                    print MATRIX[i][j]
                    sleep(0.2)
                    bz.off()
                    if MATRIX[i][j] == "A":
                        passEnter = passEnter[0:len(passEnter) - 1:]
                        passEnterDisplay = passEnterDisplay[
                            0:len(passEnterDisplay) - 1:]
                        LCD.text(passEnterDisplay, 2)
                        sleep(0.2)
                    else:
                        passEnter = passEnter + str(MATRIX[i][j])
                        passEnterDisplay = passEnterDisplay + str(MATRIX[i][j])
                        if len(passEnterDisplay) > 1:
                            passEnterDisplay_list = list(passEnterDisplay)
                            passEnterDisplay_list[len(passEnterDisplay) -
                                                  2] = "*"
                            passEnterDisplay = "".join(passEnterDisplay_list)
                        LCD.text(passEnterDisplay, 2)
                        if passEnter == passcode and len(passEnter) == 5:
                            correct_pass()
                            passEnter = ''
                            passEnterDisplay = ''
                            LCD.text('Password: '******''
                            passEnterDisplay = ''
                            LCD.text('Password: ', 1)
                        while (GPIO.input(ROW[i]) == 0):
                            pass
            GPIO.output(COL[j], 1)
Пример #6
0
class LCDScroller:
	def __init__(self):
		self.lcd = LCD(rows = 2)
		self.lcd.clear()
		self.internalclear()
		self.update_time = time.time()

	def text(self, text, line):
		print(text)
		self.lcd.text(text,line)
		line -= 1
		self.index[line] = 0
		self.texts[line] = text

	def update(self):
		if time.time() - self.update_time < 0.5:
			return
		self.update_time = time.time()
		line = 0
		for txt in self.texts:
			text_len = len(txt)
			if text_len > 16:
				self.index[line] += 1
				new_text = txt[self.index[line] : self.index[line] + 16]
				if self.index[line] + 17 > text_len:
					if len(new_text) <= 0:
						self.index[line] = 0
						new_text = txt[0 : 16 - len(new_text)]
					else:
						new_text += ' ' + txt[0 : 16 - len(new_text)]
				self.lcd.text(new_text,line + 1)
			line += 1

	def clear(self):
		self.lcd.clear()
		self.texts
		self.internalclear()

	def internalclear(self):
		self.texts = ['','']
		self.index = [0,0]
Пример #7
0
def wrong_pass(passwordCounter):
    bz.on()
    sleep(0.1)
    bz.off()
    sleep(0.1)
    bz.on()
    sleep(0.1)
    bz.off()
    print "failed"
    LCD.text('Wrong Password!', 1)
    passwordCounter += 1
    countdown = 10
    LCD.text('', 2)
    if passwordCounter == 3:
        bot.sendMessage(
            chat_id,
            "Password keyed in wrong 3 times! Lock disabled for 10 Seconds.")
        while countdown != 0:
            LCD.text('Disabled for:{}'.format(countdown), 1)
            countdown = countdown - 1
            sleep(1)
        passwordCounter = 0
    sleep(3)
    return passwordCounter
Пример #8
0
from signal import signal, SIGTERM, SIGHUP, pause
from rpi_lcd import LCD

lcd = LCD()

def safe_exit(signum, frame):
    exit(1)

try:
    signal(SIGTERM, safe_exit)
    signal(SIGHUP, safe_exit)

    lcd.text("--Welcome--", 1)
    lcd.text("Raspberry Pi!", 2)

    pause()

except KeyboardInterrupt:
    pass

finally:
    lcd.clear()
Пример #9
0
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import serial from rpi_lcd import LCD
from time import sleep

# Get serial to fetch data from arduino
ser = serial.Serial('/dev/ttyUSB0', 9600)
lcd = LCD()

def customCallback(client, userdata, message):
	print("Received a new message: ")
	print(message.payload)
	print("from topic: ")
	print(message.topic)
	print("--------------\n\n")
	
host = "arn:aws:iot:us-west-2:757945522262:thing/SmartWaterfall"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"

my_rpi = AWSIoTMQTTClient("basicPubSub")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
Пример #10
0
#device libraries
import sys
import Adafruit_DHT
import RPi.GPIO as GPIO
from gpiozero import Button
from time import sleep
import datetime as datetime
import json
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from rpi_lcd import LCD
lcd = LCD()

#Soil setup
soil = Button(24)

#amazonaws host and certs
host = "xxxxxxxxxxxxxxxxx.us-east-1.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"

#mqtt connection
my_rpi = AWSIoTMQTTClient("farm2-irrigation")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

Пример #11
0
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
from gpiozero import Buzzer, LED
from rpi_lcd import LCD
import random
import sys
import pyrebase
from datetime import datetime
import json

lcd = LCD()
lcd.text('Launching...', 1)
sleep(1)
lcd.text('Getting ready', 1)
lcd.text('......', 2)

bz = Buzzer(22)
led = LED(18)

config = {
    #Firebase API Key
}

firebase = pyrebase.initialize_app(config)
auth = firebase.auth()

#Firebase login (username, password)
user = auth.sign_in_with_email_and_password("", "")
db = firebase.database()
Пример #12
0
for a in item:
    sideslist.append([a['name'], a['description'], a['imagelocation']])
    sideprice[a['name']] = float(a['price'])

#get drinks
response = drinks.scan()
item = response['Items']
for a in item:
    drinkslist.append([a['name'], a['description'], a['imagelocation']])
    drinkprice[a['name']] = float(a['price'])

app = Flask(__name__)
app.secret_key = os.urandom(24)

orderid = 1
lcd = LCD()
mfrc522 = MFRC522.MFRC522()
continue_reading = True
lcd.text('MasterCard', 1)
lcd.text('Payment', 2)


@app.route("/")
def main():
    return render_template('index.html')


@app.route("/order", methods=['POST', 'GET'])
def selectfood():
    try:
        global continue_reading
Пример #13
0
def correct_pass():
    bz.on()
    sleep(1)
    bz.off()
    print "success"
    bot.sendMessage(chat_id, "Correct password, main door opened.")
    LCD.text('Welcome to the', 1)
    LCD.text('Community!', 2)
    sleep(5)
    options_menu()
    NightBool = False
    mode = 'Day Mode'
    publishMode(mode)
    p = proc_start()
    while (True):
        for j in range(4):
            GPIO.output(COL[j], 0)
            for i in range(4):
                if GPIO.input(ROW[i]) == 0:
                    if MATRIX[i][j] == "A":
                        if NightBool == True:
                            LCD.text('Day Mode', 1)
                            LCD.text('Activated', 2)
                            p = proc_start()
                            sleep(3)
                            options_menu()
                            NightBool = False
                            mode = 'Day Mode'
                            publishMode(mode)
                        else:
                            LCD.text('Night Mode', 1)
                            LCD.text('Activated', 2)
                            proc_stop(p)
                            if GPIO.input(21) == 1:
                                led.off()
                            sleep(3)
                            options_menu()
                            NightBool = True
                            mode = 'Night Mode'
                            publishMode(mode)
                    elif MATRIX[i][j] == "B":
                        bot.sendMessage(chat_id, 'Main Door opened')
                        LCD.text('Door', 1)
                        LCD.text('Opening', 2)
                        doorled.on()
                        sleep(10)
                        doorled.off()
                        options_menu()
                    elif MATRIX[i][j] == "C":
                        temperature, humidity = getTempHum()
                        LCD.text('Temperature:{:.1f}'.format(temperature), 1)
                        LCD.text('Humidity:{:.1f}'.format(humidity), 2)
                        sleep(7)
                        options_menu()
                    elif MATRIX[i][j] == "D":
                        bot.sendMessage(chat_id,
                                        'Garage door opened for 10 Seconds')
                        LCD.text('Garage Door', 1)
                        LCD.text('Opening', 2)
                        openGarage()
                        options_menu()
            GPIO.output(COL[j], 1)
Пример #14
0
from gpiozero import Button, Buzzer, LED
from rpi_lcd import LCD
from time import sleep
import subprocess
import MySQLdb

subprocess.call(["sudo", "modprobe", "bcm2835-v4l2"])
lcd = LCD()
btn1 = Button(13, pull_up=False)
btn2 = Button(5, pull_up=False)
buzz = Buzzer(21)
greenled = LED(24)
redled = LED(18)

try:
    db = MySQLdb.connect("localhost", "assignmentuser", "joshsmartroom",
                         "assignment")
    curs = db.cursor()
    print("Successfully connected to database!")
except:
    print("Error connecting to mySQL database")

sql = "SELECT Passcode FROM assignment.Security WHERE ID = 1"
curs.execute(sql)
result = curs.fetchall()
result = result[0][0]
password = [int(i) for i in str(result)]
print(password)
userpass = []

Пример #15
0
from nanpy import ArduinoApi, SerialManager
from rpi_lcd import LCD
from .mq2 import MQ2
from .hwalert import HWAlert
from .keypad import KeyLock
from config import config


def nanpy_connect():
    connection = SerialManager()
    arduinoObject = ArduinoApi(connection=connection)
    return arduinoObject


arduino = nanpy_connect()
arduino.pinMode(config['LM35_PIN'], arduino.INPUT)

mq = MQ2(config['MQ2_APIN'], arduino)
lcd = LCD()
buzzer = Buzzer(config['BUZZER_PIN'])

hwalert = HWAlert(lcd, buzzer)

keylock = KeyLock(hwalert, lcd)

pir = MotionSensor(config['MOTION_PIN'], sample_rate=5, queue_len=1)

mq2_alert = DigitalInputDevice(config['MQ2_DPIN'], pull_up=True)

picam = PiCamera()
Пример #16
0
	def __init__(self):
		self.lcd = LCD(rows = 2)
		self.lcd.clear()
		self.internalclear()
		self.update_time = time.time()
Пример #17
0
#device libraries
import sys
import RPi.GPIO as GPIO
from gpiozero import Button
from time import sleep
import datetime as datetime
import json
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from rpi_lcd import LCD
lcd = LCD()

#Soil setup
soil = Button(24)

#amazonaws host and certs
host = "XXXXXXXXXXXXXXXX.us-east-1.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"

#mqtt connection
my_rpi = AWSIoTMQTTClient("farm1-irrigation")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec


def activation():
Пример #18
0
b2 = 12  # Botão 2 - Para contagem
b3 = 7  # Botão 3 - Sincronizar com BD
led_on = 8  # LED indicador de leitura ligada
led_count = 25  # LED indicador de contagem

# GPIO: Driver Motores
mot_A_PWM = 26
mot_A_IN2 = 19
mot_A_IN1 = 13
mot_standby = 6
mot_B_IN1 = 5
mot_B_IN2 = 11
mot_B_PWM = 9

# Variáveis de Controle
lcd = LCD()  # LCD
play = 0  # Inicio e fim da leitura do sensor
count = 0  # Contagem das plantas
dist_max = 40  # Distância máxima para contagem
dist_min = 50  # Distância minima para contagem
dist_set = 0  # Auxiliar de nova contagem

# Definindo Dados do Usuário e Fazenda
farm_id = 2
user_id = 3

# GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(1)
GPIO.setup(TRIGGER, GPIO.OUT)
GPIO.output(TRIGGER, 0)
Пример #19
0
#Location
location = "AdminOffice"
scanning = True
valid = True
exist = False
StudentList = ""

#Create Buzzer
buzzer = 5
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer, GPIO.OUT)
GPIO.output(buzzer, GPIO.LOW)

#Create LCD
lcd = LCD()

#Create RFID
mfrc522 = MFRC522.MFRC522()


def lcdWrite(message):

    lcd.text(message, 1)


# Capture SIGINT for cleanup when the script is aborted
def end_read(signal, frame):
    global scanning
    print("Ctrl+C captured, ending read.")
    scanning = False
Пример #20
0
import sys
import Adafruit_DHT
from time import sleep
from rpi_lcd import LCD
from gpiozero import MCP3008
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from gpiozero import LED
from gpiozero import Buzzer

pin = 4
lcd = LCD()
update = True
mcp3008 = MCP3008(channel=0)

host = "a3f69y8dukmi8a-ats.iot.us-east-1.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"

my_rpi = AWSIoTMQTTClient("greenhouse1-environment")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
my_rpi.connect()

greenled = LED(20)
redled = LED(21)
from rpi_lcd import LCD
from time import sleep
lcd = LCD()
a = 1
print("schau auf dein Display")
lcd.text("Hello", 1)
lcd.text("1  2  3  4  5  6", 2)
a = input()
if (a == 'A'):
    lcd.clear()
    lcd.text("A", 1)
    lcd.text("1  2  3  4  5  6", 2)
elif (a == 'B'):
    lcd.clear()
    lcd.text("B", 1)
    lcd.text("1  2  3  4  5  6", 2)
Пример #22
0
from flask import Flask, render_template, request
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
from gpiozero import Buzzer
import json
from rpi_lcd import LCD

foodorderid=[]
drinkorderid=[]
currentorderid=""
pastservedorderid=[]
bz = Buzzer(26)
lcd = LCD()
lcd.text('Serving:', 1)
lcd.text('', 2)


# Custom MQTT message callback
def customCallback(client, userdata, message):
    global foodorderid
    global drinkorderid
    global currentorderid
    global pastservedorderid
    j = json.loads(message.payload)
    if j['orderid'] in drinkorderid:
            bz.on()
            sleep(0.5)
            bz.off()
            sleep(0.5)
            drinkorderid.remove(j['orderid'])
            if currentorderid!="":
Пример #23
0
def pillSchedule():
    try:

        # Setting up the pin for the dht sensor, the buzzer and motion sensor
        pin = 4
        bz = Buzzer(5)
        pir = MotionSensor(26, sample_rate=20, queue_len=1)

        # To setup the certificate etc for mqtt
        host = "acway7h5aefsa-ats.iot.us-east-1.amazonaws.com"
        rootCAPath = "getEnvironmentCert/rootca.pem"
        certificatePath = "getEnvironmentCert/certificate.pem.crt"
        privateKeyPath = "getEnvironmentCert/private.pem.key"

        # Set the filename and bucket name
        BUCKET = 'sp-p1726819-s3-bucket'
        location = {'LocationConstraint': 'us-east-1'}
        file_path = "/home/pi/labs/assignment/photo"
        file_name = "user.jpg"

        my_rpi = AWSIoTMQTTClient("PubSub-p1726819" + rand_str_gen())
        my_rpi.configureEndpoint(host, 8883)
        my_rpi.configureCredentials(rootCAPath, privateKeyPath,
                                    certificatePath)
        my_rpi.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
        my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
        my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

        # Connect and subscribe to AWS IoT
        my_rpi.connect()

        update = True
        while update:
            try:
                global medicine_time
                data = get_data_from_dynamodb(1, 'pillSchedule', -1)
                medicine_time = data
                global medicine_time_plus
                medicine_time_plus = datetime.datetime.strptime(
                    medicine_time, "%H:%M:%S")
                medicine_time_plus += datetime.timedelta(0, 60)
                medicine_time_plus = medicine_time_plus.strftime("%H:%M:%S")

                # Get the current time now and check if it is the time specified
                now = datetime.datetime.now()
                time_string = now.strftime("%H:%M:%S")
                if (medicine_time_plus > time_string > medicine_time):

                    # Alert the user by turning on the buzzer
                    bz.on()
                    print("Time to eat medicine")

                    # Print on the LCD to tell the user to take med
                    lcd = LCD()
                    lcd.text('Time to eat', 1)
                    lcd.text('medicine :)', 2)

                    # Checking how long did the user take to take the medicine after buzzer on
                    old_now = datetime.datetime.now().strftime("%H:%M:%S")
                    start_dt = datetime.datetime.strptime(old_now, '%H:%M:%S')
                    pir.wait_for_motion(
                        10)  # Motion sensor will only wait for 10 seconds
                    new_now = datetime.datetime.now()
                    new_time = new_now.strftime("%H:%M:%S")
                    end_dt = datetime.datetime.strptime(new_time, '%H:%M:%S')
                    duration = (end_dt - start_dt)
                    diff = int(duration.seconds)

                    # If the user took more than 10 seconds it means that the user did not take the medicine on time

                    if diff < 8:

                        # Take a photo and store to S3
                        takePhoto(file_path, file_name)
                        uploadToS3(file_path, file_name, BUCKET, location)

                        ageLow = 0
                        ageHigh = 0

                        # Print the deteced face attribute
                        print('Detected faces for')
                        for faceDetail in detect_faces(BUCKET, file_name):
                            ageLow = faceDetail['AgeRange']['Low']
                            ageHigh = faceDetail['AgeRange']['High']
                            print('Age between {} and {} years old'.format(
                                ageLow, ageHigh))
                            print('Here are the other attributes:')
                            print(
                                json.dumps(faceDetail,
                                           indent=4,
                                           sort_keys=True))

                        # To ensure that the medicine is taken by elderly and not others (Kids or pets)
                        if (ageLow < 20 < ageHigh):

                            # The medicine is taken in less than 10 seconds, turn off buzzer
                            lcd.text('Medicine taken', 1)
                            lcd.text('successfully :)', 2)
                            print("User ate medicine after {:.2f} seconds".
                                  format(diff))
                            bz.off()

                            # Get the current date and time and insert the data into the database
                            True_string = 'True'
                            message = {}
                            message["deviceID"] = "CA2"
                            message["datetimeID"] = new_now.isoformat()
                            message["takenOnTime"] = True_string
                            my_rpi.publish("sensor/takeMed",
                                           json.dumps(message), 1)

                            # Clear LCD
                            print("Uploaded data to database")
                            print("Waiting for next schedule")
                            lcd.clear()
                            sleep(60)

                        # The medicine is not taken by elderly
                        else:
                            bz.off()
                            print("Medicine not taken by patient")

                            # Send a msg to the user telling that the patient did not take medicine on time
                            send_user_Msg("Medicine not taken by patient")

                            # Get the current date and time and insert into the database
                            False_string = 'False'
                            message = {}
                            message["deviceID"] = "CA2"
                            message["datetimeID"] = new_now.isoformat()
                            message["takenOnTime"] = False_string
                            my_rpi.publish("sensor/takeMed",
                                           json.dumps(message), 1)

                            # Clear LCD
                            print("Uploaded data to database")
                            print("Waiting for next schedule")
                            lcd.clear()
                            sleep(60)

                    else:
                        # The user did not take medicine within 10 seconds
                        bz.off()
                        print("Patient did not take medicine on time")

                        # Send a msg to the user telling that the patient did not take medicine on time
                        send_user_Msg("User did not eat medicine on time")

                        # Get the current date and time and insert into the database
                        False_string = 'False'
                        message = {}
                        message["deviceID"] = "CA2"
                        message["datetimeID"] = new_now.isoformat()
                        message["takenOnTime"] = False_string
                        my_rpi.publish("sensor/takeMed", json.dumps(message),
                                       1)

                        # Clear LCD
                        print("Uploaded data to database")
                        print("Waiting for next schedule")
                        lcd.clear()
                        sleep(60)

            except KeyboardInterrupt:
                update = False
            except:
                print("Error while inserting data...")
                print(sys.exc_info()[0])
                print(sys.exc_info()[1])
    except:
        print(sys.exc_info()[0])
        print(sys.exc_info()[1])
Пример #24
0
sql = "SELECT FaceScanConfidence FROM assignment.Security"
curs.execute(sql)
result = curs.fetchall()
setconfidence = int(result[0][0])

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
cam.set(3, 640)  # set video widht
cam.set(4, 480)  # set video height

# Define min window size to be recognized as a face
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)

lcd = LCD()
lcd.text('Scanning...', 1)
starttime = time.time()
while True:
    confidentint = 0
    ret, img = cam.read()
    img = cv2.flip(img, -1)  # Flip vertically

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(int(minW), int(minH)),
    )
Пример #25
0
from signal import signal, SIGTERM, SIGHUP, pause
from rpi_lcd import LCD
from time import sleep
from gpiozero import DistanceSensor
from threading import Thread

message = ""
reading = True
lcd = LCD()
sensor = DistanceSensor(echo=20, trigger=21)


def safe_exit(signum, frame):
    exit(1)


def display_distance():
    global message

    while reading:
        sleep(0.25)
        lcd.text(message, 1)


def read_distance():
    global message

    while reading:
        message = "Distance: " + '{:1.2f}'.format(sensor.value) + " m"

        print(message)
import serial
import array as arr
import time
import csv
import RPi.GPIO as GPIO
from rpi_lcd import LCD


lcd = LCD()

#Button Setup
GPIO.setmode(GPIO.BCM)   # Specify We Want to reference Physical pins

# Raspberry Pi pin configuration:
pump_relay = 21
light_relay = 20

LED_blue = 13
LED_red = 19

GPIO.setup(pump_relay, GPIO.OUT)
GPIO.setup(light_relay, GPIO.OUT)

GPIO.setup(LED_blue, GPIO.OUT)
GPIO.setup(LED_red, GPIO.OUT)

#reset value
x = 0

#temp values, will change with testing
luxVLow = 800
from rpi_lcd import LCD
from time import sleep

lcd = LCD(address=0x27, bus=1, width=16, rows=2)

lcd.text('Hello World!', 1)
lcd.text('Raspberry Pi', 2)

sleep(2)
lcd.clear()

lcd.text("This is test string for i2c lcd screen, which has 16x2 demension.",
         1)
sleep(5)
Пример #28
0
# DHT11 Sensor  :   GPIO PIN 20
# Motion Sensor :   GPIO PIN 26
# Lights LED    :   GPIO PIN 21
# Door LED      :   GPIO PIN 16
# Buzzer        :   GPIO PIN 5
# Servo Motor   :   GPIO PIN 12
# Keypad        :   GPIO PIN 19, 17, 27, 22, 18, 23, 24, 25

sens1 = 20
adc = MCP3008(channel=0)
light = round(1024 - (adc.value * 1024))
pir = MotionSensor(26, sample_rate=5, queue_len=1)
led = LED(21)
doorled = LED(16)
LCD = LCD()
bz = Buzzer(5)
passcode = '12345'

# Initalize Servo
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
servo1 = GPIO.PWM(12, 50)
servo1.start(0)
servo1.ChangeDutyCycle(2)

# Numpad Matrix
MATRIX = [[1, 2, 3, 'A'], [4, 5, 6, 'B'], [7, 8, 9, 'C'], ['*', 0, '#', 'D']]

# Match pins to rows and columns
Пример #29
0
my_rpi = AWSIoTMQTTClient("ADMIN_NUMBER_CLIENT")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
my_rpi.connect()

update = True
# card reading variables
uid = None
prev_uid = None
continue_reading = True
# lcd variable
lcd = LCD()
# bot variable
bot = telepot.Bot(my_bot_token)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(40, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(37, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
pwm = GPIO.PWM(11, 50)
pwm.start(0)


def SetAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(11, True)
Пример #30
0
def options_menu():
    LCD.text('A:NightM B:Door', 1)
    LCD.text('C:TemHum D:GDoor', 2)