import RPI_ADC0832 import time import urllib import configparser import json import threading PUMP_PIN = 4 LIGHT_PIN = 22 DHT_PIN = 19 server = '' root = '/flower/api' water = False dht = dht11.DHT11(pin = DHT_PIN) # 温湿度传感器 soil = RPI_ADC0832.ADC0832() def writeConfig(section, **kwargs): config = configparser.ConfigParser() try: config[section] = kwargs with open('flower.ini', 'w') as file: config.write(file) return True except: return False def readConfig(section, kw): config = configparser.ConfigParser() try:
# PIN7 = DATA heater1 = 16 #pin36 heater2 = 19 #pin 35 humidity_pin = 15 #pin10 overheat1 = 0 underheat1 = 0 GPIO.setmode(GPIO.BCM) GPIO.setup(heater1, GPIO.OUT) GPIO.setup(heater2, GPIO.OUT) GPIO.setup(humidity_pin, GPIO.OUT) bottom_sensor = '/sys/bus/w1/devices/28-0516a359e5ff/w1_slave' top_sensor = '/sys/bus/w1/devices/28-0516a4a43fff/w1_slave' humidity_sensor = dht11.DHT11(pin=humidity_pin) firstRun = False heaterOn = False def temp_raw(sensor): f = open(sensor, 'r') lines = f.readlines() f.close() return lines def read_temp(sensor): lines = temp_raw(sensor) while lines[0].strip()[-3:] != 'YES':
#connectionString connection = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='WARMON') cursor = connection.cursor() AlarmAPIurl= "http://localhost:80/example" #"http://192.168.1.101:86/api/Alarm" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # read data using pins 18, 17 and 14 motionPin = 18 tempHumiPin = 14 smokePin = 17 instance = dht11.DHT11(pin=tempHumiPin) motionOn = 0 smokeOn =0 MaxTemp = 0 MaxHum = 0 MinTemp = 100 MinHum = 100 FromEmreMinTemp = 24 FromEmreMaxTemp = 27 FromEmreMinHum = 20 FromEmreMaxHum = 35 roomCode = 25
def __init__(self): self.bmp = BMP180() self.temphum = dht11.DHT11(pin = Temp_sensor)
from pyA20.gpio import gpio from pyA20.gpio import port import dht11 import time import datetime gpio.init() PIN = port.PA20 gpio.setcfg(port.PA20, gpio.OUTPUT) gpio.setcfg(port.PC4, gpio.OUTPUT) gpio.setcfg(port.PC7, gpio.OUTPUT) gpio.output(port.PC4, gpio.HIGH) gpio.output(port.PC7, gpio.HIGH) instance = dht11.DHT11(pin=PIN) Fan = 0 Heat = 0 while True: result = instance.read() if (result.temperature) == 0: continue tempHI = 39 tempLOW = 37 print "Temp n Humidity Results:", result.temperature, result.humidity DATA = [result.temperature, result.humidity] if (result.temperature) >= tempHI and Fan == 0: print "Detected High Temp, fan is not activated, Turning on fan and turning off light if active" gpio.setcfg(port.PC7, gpio.OUTPUT) gpio.output(port.PC7, gpio.LOW) gpio.output(port.PC4, gpio.HIGH) Fan = 1
from time import * lcd = I2C_LCD_driver.lcd( ) ##assegniamo a lcd la classe lcd presente in I2C_LCD_driver GPIO.setwarnings(False) ## serve a disabilitare gli avvisi GPIO.setmode( GPIO.BCM ) ##L'opzione GPIO.BCM specifica che si fa riferisce ai pin in base al numero del pin del Raspberry GPIO.cleanup( ) ## Ripristina tutte le porte di input, utilizzate in questo programma lcd.lcd_display_string("mini stazione", 1) while True: instanza = dht11.DHT11( pin=27 ) ##(pin = pin GPIO) in questo caso il pin del segnale del DHT-11 è collegato al GPIO27 risultato = instanza.read() ## Se è presente un segnale dal dht11 # Fahrenheit: # risultato.temperature = (risultato.temperature * 1.8) + 32 if risultato.is_valid( ): ## se il segnale è valido stampa sul lcd temp e umidità lcd.lcd_display_string( "Temperatura:%d%sC" % (risultato.temperature, chr(223)), 1) lcd.lcd_display_string("Umidita: %d %%" % risultato.humidity, 2)
def read(self, gpio): instance = dht11.DHT11(self.pin) result = instance.read() if result.is_valid(): self.temp = result.temperature self.rh = result.humidity
def __init__(self): GPIO.setmode(GPIO.BCM) self.instance = dht11.DHT11(pin = Temp_sensor)
import pandas import time import datetime import smbus import RPi.GPIO as GPIO import dht11 import numpy as np GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) instance = dht11.DHT11(pin=14) #changeable address = 0x48 A0 = 0x40 A1 = 0x41 A2 = 0x42 A3 = 0x43 bus = smbus.SMBus(1) start_data = {"Date":["0"],"Temperature":["0"],"Soil Moisture":["0"],"Humidity":["0"]} df = pandas.DataFrame(data=start_data,columns=["Date","Temperature","Soil Moisture","Humidity"]) while True: #Soil Moisture bus.write_byte(address,A2) #A2 İnput value = bus.read_byte(address) soil_moisture = 100-(value*100/255)
GPIO.output(gate_green, GPIO.LOW) GPIO.output(gate_red, GPIO.LOW) # Servo Motor Pin Config servo = 3 #GPIO4 GPIO.setup(servo,GPIO.OUT) pwm = GPIO.PWM(servo,50) # Motor Pin motor = 21 GPIO.setup(motor,GPIO.OUT) GPIO.output(motor,GPIO.HIGH) # read data using pin 14 instance = dht11.DHT11(pin=14) #RP8 #set GPIO Pins GPIO_TRIGGER = 18 #RP12 GPIO_ECHO = 24 #RP 18 #set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def angle_to_percent (angle) : if angle > 180 or angle < 0 : return False start = 4 end = 12.5
firebase = pyrebase.initialize_app(config) db = firebase.database() # Initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() #dht11 pins GPIO.setup(15, GPIO.IN) GPIO.setup(14, GPIO.IN) GPIO.setup(18, GPIO.IN) GPIO.setup(23, GPIO.IN) GPIO.setup(24, GPIO.IN) SensorInstance1 = dht11.DHT11(pin=15) SensorInstance2 = dht11.DHT11(pin=14) SensorInstance3 = dht11.DHT11(pin=18) SensorInstance4 = dht11.DHT11(pin=23) SensorInstance5 = dht11.DHT11(pin=24) #ldr pins delayt = 0.1 value1 = 0 # this variable will be used to store the ldr value ldr1 = 4 value2 = 0 # this variable will be used to store the ldr value ldr2 = 2 value3 = 0 # this variable will be used to store the ldr value ldr3 = 3 value4 = 0 # this variable will be used to store the ldr value ldr4 = 17 value5 = 0 # this variable will be used to store the ldr value
import RPi.GPIO as gpio gpio.setwarnings(False) gpio.setmode(gpio.BCM) import time import dht11 dht_instance = dht11.DHT11(pin = 24) while True: result = dht_instance.read() if result.is_valid(): temperature = result.temperature humidity = result.humidity print ("temperature is :",str(temperature)) print ("humidity is :",str(humidity)) time.sleep (5) else: print ("not a valid number") time.sleep(5)
def main(): # Main program block instance = dht11.DHT11(pin=Temp_sensor) # Openchirp remote transducer name sensorT = "temperature" sensorH = "humidity" actuatorLedR = "red_led" actuatorLedB = "blue_led" actuatorFan = "fan" smart_device.device_state[actuatorLedR] = 0 smart_device.device_state[actuatorLedB] = 0 smart_device.device_state[actuatorFan] = 1 # Two methods: 'Self Control IOT' OR 'Automatic' askforchoice = input( "How do you want to test? Self control over IOT or automatic? ") while True: result = instance.read() # Update the sensor reading temp = result.temperature hum = result.humidity count = 0 # if choose the 'self control IOT method' if (askforchoice == 'self control'): if (hum > 40): pygame.mixer.init() pygame.mixer.music.load("SchenleyPark.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue time.sleep(10) # OpenChirp output GPIO.output(red_led, int(smart_device.device_state[actuatorLedR])) GPIO.output(fan2, int(smart_device.device_state[actuatorFan])) GPIO.output(blue_led, int(smart_device.device_state[actuatorLedB])) # if choose the 'automatic method' if (askforchoice == 'automatic'): # Due to the sensor output latency, there are values measured to be 0s if (temp != 0 and hum != 0): # Save the reading to cloud server smart_device.publish("openchirp/device/" + username + "/" + sensorT, payload=temp, qos=0, retain=True) smart_device.publish("openchirp/device/" + username + "/" + sensorH, payload=hum, qos=0, retain=True) if winter: if (temp < 20): GPIO.output(blue_led, GPIO.HIGH) GPIO.output(fan2, 1) elif (temp > 23.5): GPIO.output(red_led, GPIO.HIGH) # fan2 0 is fan on GPIO.output(fan2, 0) else: GPIO.output(blue_led, GPIO.LOW) GPIO.output(red_led, GPIO.LOW) GPIO.output(fan2, 1) if summer: if (temp < 23): GPIO.output(blue_led, GPIO.HIGH) GPIO.output(fan2, 1) elif (temp > 26): GPIO.output(red_led, GPIO.HIGH) GPIO.output(fan2, 0) else: GPIO.output(blue_led, GPIO.LOW) GPIO.output(red_led, GPIO.LOW) GPIO.output(fan2, 1)
"tempC_amb": 0, "tempF_amb": 0, "humidity": 0 } #add column titles to file with open(test_file_name, 'w') as file: w = csv.DictWriter(file, chill_data.keys()) w.writeheader() ##for probe DS18 sensor ## THERM = W1ThermSensor() ##for ambient DHT11 temp & humidity sensor ## # read data using pin 12 DHT11 = dht11.DHT11(pin=12) sio = socketio.Client() @sio.event def connect(): print("Connected to Server!") @sio.event def disconnect(): print("Disconnected from Server!") @sio.event def start(started): if started == 'true': print("Starting!")
import dht11 import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) instance = dht11.DHT11(4) from RPLCD.i2c import CharLCD lcd = CharLCD('PCF8574', 0x27) while 1: result = instance.read() error = result.error_code temp = result.temperature humi = result.humidity if error == 0: lcd.cursor_pos = (0, 0) lcd.write_string("Temp: %s" % result.temperature) lcd.cursor_pos = (0, 8) lcd.write_string('C') lcd.cursor_pos = (1, 0) lcd.write_string("Humi: %s" % result.humidity) lcd.cursor_pos = (1, 8) lcd.write_string('%RH') time.sleep(1) else: lcd.cursor_pos = (0, 0) lcd.write_string(u' Please Wait! ') lcd.cursor_pos = (1, 0) lcd.write_string(u' data missing ') time.sleep(1) lcd.clear()
def toggle_LED(State): if State == 0: State = State + 1 # At this moment State == 1 C.itemconfig(Light_IMG, image=LightBulb_On) time.sleep(2) else: State = State - 1 C.itemconfig(Light_IMG, image=LightBulb_Off) time.sleep(2) print("The state of the light bulb is", State) top.after(1000, toggle_LED) instance = dht11.DHT11(pin=21) #read data using pin 21 GPIO.setwarnings(False) class enviroment: def TemperatureAndHumi(self): try: while True: #keep reading, unless keyboard is pressed result = instance.read() # using the sensor if result.is_valid(): #print datetime & sensor values timing = datetime.datetime.now() timing = timing.strftime("%d-%m-%Y_%H:%M:%S") print("Last valid input: " + timing) print("Temperature: %-3.1f C" % result.temperature) print("Humidity: %-3.1f %%" % result.humidity) Temperature = result.temperature
async def run(self): instance = dht11.DHT11(pin=7) result = instance.read() if result.is_valid(): self.char_temp.set_value(result.temperature) self.char_humidity.set_value(result.humidity)
from prometheus_client import Gauge, write_to_textfile, REGISTRY import RPi.GPIO as GPIO import dht11 import time TMP_PATH = '/textfile/dht11.prom' GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() module = dht11.DHT11(pin=24) g1 = Gauge('temperature', 'Gauge') g2 = Gauge('humidity', 'Gauge') while True: result = module.read() if result.is_valid(): g1.set(result.temperature) g2.set(result.humidity) write_to_textfile(TMP_PATH, REGISTRY) time.sleep(1)
import RPi.GPIO as GPIO import time import dht11 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) dhtPin = dht11.DHT11(pin=38) while dhtValue.temperature > 22: dhtValue = dhtPin.read() print('LED ON 18') GPIO.output(18, GPIO.HIGH) time.sleep(1.0) print('LED off 18 ') GPIO.output(18, GPIO.LOW) time.sleep(1.0) clear()
import RPi.GPIO as GPIO import dht11 import time import datetime import csv from threading import Thread import json from http.server import BaseHTTPRequestHandler, HTTPServer from urllib import parse as urlparse # initialize GPIO GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) instance0 = dht11.DHT11(pin=14) instance1 = dht11.DHT11(pin=15) data = {"temp0": -1.0, "humid0": -1.0, "temp1": -1.0, "humid1": -1.0} PORT_NUMBER = 8001 # This class will handles any incoming request from # the browser class MyHandler(BaseHTTPRequestHandler): # Handler for the GET requests def do_GET(self): global data try: elements = self.path.split('/')
# -*- coding: utf-8 -*- #위의 코드는 한글주석의 사용이 가능하도록 하는 코드임 import RPi.GPIO as gpio import paho.mqtt.client as mqtt import time import dht11 import datetime gpio.cleanup() gpio.setwarnings(False) gpio.setmode(gpio.BCM) last_temp = 25 #가장 최근의 온도를 저장(초기값은 기준치보다 아랫값을 넣어두어 무조건 True로 가도록) instance = dht11.DHT11(pin=5) #5번핀으로 dht11을 활성화 client = mqtt.Client("pub client") #MQTT 클라이언트 객체를 만듬 client.connect("127.0.0.1", 1883, 60) #로컬호스트 브로커에 접속 #무한 반복 while True: result = instance.read() #dht11로 부터 값을 읽어들임 if result.is_valid(): #유효한 값이면 시간및 온도를 출력하고 최근의 온도값을 갱신 print("Last valid input: " + str(datetime.datetime.now())) print("Temperature: %d C" % result.temperature) last_temp = result.temperature else: #유효치 않다면 유효하지 않음을 출력하고 가장 최근의 온도값을 출력 print("Result was not valid last_temperature: " + str(last_temp)) data = last_temp #data에 최근 온도를 집어넣음 print("Temperature: " + str(data)) #생성된 온도데이터를 화면에 출력 client.publish("environment/temperature",
def __init__(self, pin=14): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() self.module = dht11.DHT11(pin=pin)
# temp_monitor.py import wiringpi as pi import time import sys import dht11 import requests import ambient pi.wiringPiSetupGpio() dht11 = dht11.DHT11(pin=4) am = ambient.Ambient(****, ‘'**********’) try: while True: r = dht11.read() if r.is_valid(): r = am.send({"d1": r.temperature, "d2": r.humidity}) time.sleep(10) except KeyboardInterrupt: sys.exit(0)
import RPi.GPIO as GPIO import dht11 import time import datetime GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() instancerecording = dht11.DHT11(pin=27) while True: result = intancerecording.read() if result.is_valid(): print("temperature and humidity at: " + str(datetime.datetime.now())) print("temperature reading: %d C" % result.temperature) time.sleep(2)
DIR_ENABLE = 11 DIR_FRENTE = 13 DIR_RE = 15 ESQ_ENABLE = 33 ESQ_FRENTE = 35 ESQ_RE = 37 GPIO.setup(DIR_ENABLE, GPIO.OUT) GPIO.setup(DIR_FRENTE, GPIO.OUT) GPIO.setup(DIR_RE, GPIO.OUT) GPIO.setup(ESQ_ENABLE, GPIO.OUT) GPIO.setup(ESQ_FRENTE, GPIO.OUT) GPIO.setup(ESQ_RE, GPIO.OUT) #Configura Inputs do sensor de temperatura e humidade DHT11 sensor_dht11 = dht11.DHT11(pin = 29) #Configura Outputs do Buzzer buzzer = 12 GPIO.setup(buzzer,GPIO.OUT) GPIO.output(buzzer,0) ####################### FUNCOES QUE CONTROLAM OS MOTORES DO CARRINHO ############################### def sleep_para_andar(): time.sleep(0.01) #I need the timesleep because if not the robot will get a -1 all the time def fn_frente_soh_esq(): GPIO.output(ESQ_FRENTE,1) GPIO.output(DIR_FRENTE,0) sleep_para_andar()
# Define GPIO to LCD mapping Temp_sensor = 4 # Define LED Out temperature Pin Number Led_out_temperature = 17 # Define LED In Pin Number #Led_in=?? GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(Led_out_temperature, GPIO.OUT) #GPIO.setup(Led_in, GPIO.IN) instance = dht11.DHT11(pin=Temp_sensor) sensor = BMP085.BMP085() try: while True: #get DHT11 sensor value result = instance.read() if result.is_valid(): print("temp:" + str(result.temperature) + " C") #「lcd_string」を「print」に置き換えて、第2引数を削除した print("humid:" + str(result.humidity) + "%") #「lcd_string」を「print」に置き換えて、第2引数を削除した #print('Pressure:{0:0.2f} Pa'.format(sensor.read_pressure())) print("pressure:" + str(sensor.read_pressure()) + " Pa") disp_test01.print_disp(
import cv2 import json import requests import RPi.GPIO as GPIO import dht11 import time from watson_developer_cloud import VisualRecognitionV3 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.cleanup() SensorInstance = dht11.DHT11(pin=12) GPIO.setup(7, GPIO.OUT) p = GPIO.PWM(7, 50) p.start(7.5) T = 0 H = 0 visual_recognition = VisualRecognitionV3( '2018-03-19', iam_apikey='JTxiAlbDnxppMgOicLZuIOy-rbfbZQgipIQ5AisWmlsE') # Loading the cascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # Defining a function that will do the detections def detect(gray, frame): faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: print(faces.shape)
import RPi.GPIO as GPIO import dht11 import sys TempHumidityPin = 7 GPIO.setmode(GPIO.BOARD) instance = dht11.DHT11(TempHumidityPin) result = instance.read() if result.is_valid(): # print("Last valid input: " + str(datetime.datetime.now())) # print("Temperature: %d C" % result.temperature) # print("Humidity: %d %%" % result.humidity) # print result.temperature print 13
import RPi.GPIO as GPIO import dht11 from datetime import datetime import time # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # read data using pin 14 instance = dht11.DHT11(pin=4) result = instance.read() while (1): if result.is_valid(): print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) data = str(result.temperature) + ',' + str( result.humidity) + ',' + str(datetime.now()) with open('temperature_test.csv', 'a') as tfile: tfile.write(data) tfile.write('\n') tfile.close() else: print("Error: %d" % result.error_code) time.sleep(1) GPIO.cleanup()
import asyncio import json import os from dotenv import load_dotenv from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient # The connection details from IoT Central for the device load_dotenv() id_scope = os.getenv("ID_SCOPE") primary_key = os.getenv("PRIMARY_KEY") device_id = "pi-environment-monitor" # initial setup of DHT11, LCD1602 and ADC0832 for photoresistor GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) DHT_SENSOR = dht11.DHT11(pin=4) mylcd = lcd1602.lcd() ADC0832.setup() # Gets telemetry from the Grove sensors # Telemetry needs to be sent as JSON data async def get_telemetry() -> str: # The dht call returns the temperature and the humidity, result = DHT_SENSOR.read() temperature = result.temperature # The temperature can come as 0, meaning you are reading # too fast, if so sleep for a second to ensure the next reading # is ready while True: if result.is_valid(): timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')