Skip to content

Instantly share code, notes, and snippets.

@simonmoreau
Created February 24, 2019 14:15
Show Gist options
  • Save simonmoreau/a1a7572610e03e044c41d482e5a45977 to your computer and use it in GitHub Desktop.
Save simonmoreau/a1a7572610e03e044c41d482e5a45977 to your computer and use it in GitHub Desktop.
A Python script to send values from an Adafruit DHT22 to an Azure Cosmos DB database
import Adafruit_DHT
import azure.cosmos.cosmos_client as cosmos_client
import time
def reading():
config = {
'ENDPOINT': 'https://bim42db.documents.azure.com:443/',
'PRIMARYKEY': my Azure Cosmos DB Key',
'DATABASE': 'bim42db',
'CONTAINER': 'bmsPiCollection'
}
# Initialize the Cosmos client
client = cosmos_client.CosmosClient(url_connection=config['ENDPOINT'], auth={
'masterKey': config['PRIMARYKEY']})
database_link = 'dbs/' + config['DATABASE']
collection_link = database_link + '/colls/{0}'.format(config['CONTAINER'])
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT22
# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
pin = 'P8_11'
# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
pin = 4
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
timestamp = time.ctime(time.time())
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
print(timestamp)
# Create and add some items to the container
item1 = client.CreateItem(collection_link, {
'timestamp': timestamp,
'temperature': temperature,
'humidity': humidity,
'sensorId': 'sensor1'
}
)
else:
print('Failed to get reading. Try again!')
reading()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment