Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- # ================================================================
- # simpletest.py
- # ----------------------------------------------------------------
- # Code modified from Adafruit sample code simpletest.py from the
- # DHT library
- # ----------------------------------------------------------------
- # Modifications by G.D. Walters for Full Circle Magazine #132
- # ================================================================
- import Adafruit_DHT
- # import the paho library
- # also import the time library for the sleep function
- import paho.mqtt.client as mqtt
- from time import sleep
- # Set some global definitions
- MQTT_SERVER = '192.168.1.224'
- MQTT_PATH1 = 'greghouse/dht22/humidity'
- MQTT_PATH2 = 'greghouse/dht22/temperature'
- sensor = Adafruit_DHT.DHT22
- pin = 4 # GPIO Input pin for data from the sensor Physical pin 7
- sleep(3) # Wait 3 seconds before starting up for things to stabilize…
- def on_connect(client,userdata,flags, rc):
- print('Connected with result code ' + str(rc))
- client.subscribe(MQTT_PATH1)
- client.subscribe(MQTT_PATH2)
- # The callback for when a PUBLISH message is received from the broker.
- def on_message(client, userdata, msg):
- print(msg.topic+' '+str(msg.payload))
- # more callbacks, etc.
- client = mqtt.Client()
- client.on_connect = on_connect
- client.on_message = on_message
- client.connect(MQTT_SERVER, 1883, 60)
- while 1:
- humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
- # Temp in centigrade
- temperaturec = temperature
- # Temp in fahrenheit
- temperaturef = temperature * 9/5.0 + 32
- if humidity is not None and temperature is not None:
- # If using Celsius, change the '*F' to '*C'
- # and use temperaturec
- print('Temp={0:0.1f}*F Humidity={1:0.1f}%'.format(
- temperaturef,
- humidity))
- hmsg = '{0:0.1f}'.format(humidity)
- # Change the next line to temperaturec if you want to
- # publish in centigrade
- tmsg = '{0:0.1f}'.format(temperaturef)
- client.publish(MQTT_PATH1,hmsg,qos=1,retain=True)
- client.publish(MQTT_PATH2,tmsg,qos=1,retain=True)
- else:
- print('Failed to get reading. Try again!')
- sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement