MJRoBot (Marcelo Rovai)
Published © GPL3+

RPi - IoT Weather Station

Capturing sensor data and logging them locally and on an IoT service, via MQTT protocol.

IntermediateFull instructions provided3 hours8,779
RPi - IoT Weather Station

Things used in this project

Story

Read more

Schematics

Github

Code

Code snippet #7

Plain text
import Adafruit_DHT
DHT22Sensor = Adafruit_DHT.DHT22
DHTpin = 16
humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin)
if (humDHT is not None) and (tempDHT is not None):
    hum = round (humDHT,1)
    temp = round (tempDHT, 1)

Code snippet #14

Plain text
import Adafruit_BMP.BMP085 as BMP085
bmp180Sensor = BMP085.BMP085()
tempBMP = round(bmp180Sensor.read_temperature(), 1)
presBMP = round(bmp180Sensor.read_pressure()/100, 1) # absolute pressure in hPa
altBMP =  round(bmp180Sensor.read_altitude(),1)

Code snippet #16

Plain text
def bmp180GetData(altitude):

    temp = bmp180Sensor.read_temperature()
    pres = bmp180Sensor.read_pressure()
    alt =  bmp180Sensor.read_altitude()
    presSeaLevel = pres / pow(1.0 - altitude/44330.0, 5.255) 

    temp = round (temp, 1)
    pres = round (pres/100, 2) # absolute pressure in hPa (or mbar)
    alt = round (alt)
    presSeaLevel = round (presSeaLevel/100, 2) # absolute pressure in hPa (or mbar)

    return temp, pres, alt, presSeaLevel

Code snippet #21

Plain text
def readSensorUV():                   
    numOfReadings = 3
    dataSensorUV = 0
    for i in range(numOfReadings): 
        dataSensorUV += ReadChannel(0)
        time.sleep(0.2)
    dataSensorUV /= numOfReadings
    dataSensorUV = (dataSensorUV * (3.3 / 1023.0))*1000;
    return round(dataSensorUV)

Code snippet #22

Plain text
def indexCalculate(dataSensorUV):
    if dataSensorUV < 227: indexUV = 0
    elif (227 <= dataSensorUV) & (dataSensorUV < 318): indexUV = 1
    elif (318 <= dataSensorUV) & (dataSensorUV < 408): indexUV = 2
    elif (408 <= dataSensorUV) & (dataSensorUV < 503): indexUV = 3
    elif (503 <= dataSensorUV) & (dataSensorUV < 606): indexUV = 4    
    elif (606 <= dataSensorUV) & (dataSensorUV < 696): indexUV = 5
    elif (696 <= dataSensorUV) & (dataSensorUV < 795): indexUV = 6
    elif (795 <= dataSensorUV) & (dataSensorUV < 881): indexUV = 7 
    elif (881 <= dataSensorUV) & (dataSensorUV < 976): indexUV = 8
    elif (976 <= dataSensorUV) & (dataSensorUV < 1079): indexUV = 9 
    elif (1079 <= dataSensorUV) & (dataSensorUV < 1170): indexUV = 10
    else: indexUV = 11  
    return indexUV

Code snippet #23

Plain text
# time library 
import datetime

# Get data (from sensors)
def getSensorData():
    global timeString
    global humLab
    global tempExt
    global tempLab
    global presSL
    global altLab
    global presAbs
    global UV_mV
    global UV_index

    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")

    tempExt = round(ds18b20Sensor.get_temperature(), 1)

    tempLab, presAbs, altLab, presSL = bmp180GetData(altReal) 

    humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin)
    if humDHT is not None and tempDHT is not None:
        humLab = round (humDHT)
        
    UV_mV = readSensorUV()
    UV_index = indexCalculate(UV_mV) 

Code snippet #24

Plain text
with open("/home/pi/rpi_weather_station.csv", "a") as log:
    while True:
        getSensorData()
        log.write("{},{},{},{},{},{},{},{},{}\n".format(timeString, humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index))
        time.sleep(30)

Code snippet #27

Plain text
channelID = "YOUR CHANNEL ID"
apiKey = "YOUR WRITE KEY"

topic = "channels/" + channelID + "/publish/" + apiKey
mqttHost = "mqtt.thingspeak.com"
tTransport = "tcp"
tPort = 1883
tTLS = None<br>

Code snippet #29

Plain text
print ("[INFO] Data prepared to be uploaded")<br>try:
    publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)
    print ("[INFO] Data sent for 8 fields: ", humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)
except:
    print ("[INFO] Failure in sending data")

Code snippet #30

Plain text
import time
while(True): 
    getSensorData()
    tPayload = "field1=" + str(humLab)+ "&field2=" + str(tempExt)+ "&field3=" + str(tempLab)+ "&field4=" + str(presSL)+ "&field5=" + str(altLab) + "&field6=" + str(presAbs)+ "&field7=" + str(UV_mV) + "&field8=" + str(UV_index)
    try:
        publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)
        save_log()
    except (KeyboardInterrupt):
        break
    except:
        print ("[INFO] Failure in sending data") 
    time.sleep(60)

Github

https://github.com/adafruit/Adafruit_Python_DHT

Github

https://github.com/adafruit/Adafruit_Python_BMP

Github

https://github.com/Mjrovai/RPi-Weather-Station

Credits

MJRoBot (Marcelo Rovai)

MJRoBot (Marcelo Rovai)

66 projects • 956 followers
Professor, Engineer, MBA, Master in Data Science. Writes about Electronics with a focus on Physical Computing, IoT, ML, TinyML and Robotics.
Thanks to Mauricio Pinto.

Comments