🌤️Misty weather forecaster

Have you ever thought that your Misty could become an excellent weather reporter and forecaster?

The Adafruit BME280 board will give you barometric pressure, temperature and humidity!

The humidity level is a nice report to have in your home. The barometric pressure data are temperature-dependent. This means that if your temperature goes up Misty will read a lower pressure reading.

Materials:

Adafruit BME280 instructions

You can find the instructions for this board in this link

If you're using the breadboard you will need to solder the breadboard 1 pins into the circuitboard. You can slide the board over the pins and heat the pins, then apply solder. After your board is ready here is the pin layout, this is on an Arduino board but of course, it's the same on Misty backpack. You can use the 3.3volt supply.

Arduino Code:

//Libraries
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
unsigned long delayTime;

// Void Setup to check the initial condition
void setup() {
  Serial.begin(9600);
  while(!Serial); // time to get serial running
  Serial.println(F("BME280 test"));
  unsigned status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
    while (1) delay(10);
  }
  Serial.println("-- Default Test --");
  delayTime = 1000;
  Serial.println();
}

//Infinite function that reads and sends the data to Misty
void loop() {
  Serial.print("Temperature: ");
  Serial.print(bme.readTemperature());
  Serial.println(" *F");
  Serial.print("Pressure: ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");
  Serial.print("Humidity: ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");
  Serial.println();
  delay(delayTime);
}

You can follow these instructions to complete the setup of the BME280 board before starting it. In this Arduino code, we declare the libraries that we'll use, void setup and void loop. The void setup prepares the code and runs only once, in this case, we check the presence of the BME280 sensor. In the void loop, we read and send the data from the Arduino sensor to Misty via serial port.

Misty Code:

from mistyPy.Robot import Robot
from mistyPy.Events import Events
import time
import threading

# Connect to Misty
misty = Robot("YOUR MISTY IP")
print("Successfully connected to Misty.")
misty.change_led(0, 255, 0)

#Variables
initial_pressure = None
initial_temperature = None
temperature = None
pressure = None
humidity = None
announce_interval = 360 # 6 minutes in seconds

#Functions
#Normalizing data
misty.speak("Let's see what's going on with your weather")
def parse_data(data):
    message = data["message"]["message"]
    try:
      if "Temperature" in message:
        temp_index = message.index("Temperature: ") + len("Temperature: ")
        temp_end_index = message.index(" *F", temp_index)
        temperature_celsius = float(message[temp_index:temp_end_index].strip())
        temperature_fahrenheit = temperature_celsius * 9.0/5.0 + 32.0
        return ("temperature", round(temperature_fahrenheit, 2))
      elif "Pressure" in message:
        pressure_index = message.index("Pressure: ") + len("Pressure: ")
        pressure_end_index = message.index(" hPa",pressure_index)
        pressure = message[pressure_index:pressure_end_index].strip()
        return ("pressure", pressure)
      elif "Humidity" in message:
        humidity_index = message.index("Humidity: ") + len("Humidity: ")
        humidity_end_index = message.index(" %", humidity_index)
        humidity = message[humidity_index:humidity_end_index].strip()
        return ("humidity", humidity)
    except ValueError:
      return None
 
#Change Misty's screen
def display_data(temperature, pressure, humidity):
    display_text = f"\nTemperature: {temperature} *F\nPressure:{pressure} hPa\nHumidity: {humidity} %"
    misty.display_image("e_SystemBlackScreen.jpg")
    misty.display_text(display_text, "Large")
    print(f"Updated display with: {display_text}")

#Announcement of the weather condition
def announce_weather_condition(pressure):
    if pressure > 974:# change this value according to your experiments
        misty.speak("There is no storm system in the vicinity for sometime and most likely sunny skies.")
    elif pressure < 960:
        misty.speak("We are currently within a precipitation system.")

#Starting readings
def announce_readings():
    global temperature, pressure, humidity
    while True: #infinite loop
        #while reading data
        if temperature and pressure and humidity:
            misty.speak(f"The current temperature is {temperature} degrees Fahrenheit, the pressure is {pressure} hPa, and the humidity is {humidity} percent.")
            announce_weather_condition(pressure)
        time.sleep(announce_interval)

#Pressure variation
def check_pressure_change(new_pressure):
    global initial_pressure
    if initial_pressure is None:
       initial_pressure = new_pressure
       pressure_difference = new_pressure - initial_pressure
       return pressure_difference
    if abs(pressure_difference) >= 5:
       direction = "up" if pressure_difference > 0 else "down"
       misty.speak(f"I am detecting a distinct change in pressure by 5 points {direction}.")

#Read the data
def serial_msg_test(data):
    global temperature, pressure, humidity, initial_temperature, initial_pressure
    print(f"Received data: {data}")
    parsed = parse_data(data)
    if parsed:
        if parsed[0] == "temperature":
            temperature = parsed[1]
            if initial_temperature is None:
                initial_temperature = temperature
                misty.speak(f"The current temperature is {initial_temperature} degrees Fahrenheit.")
        elif parsed[0] == "pressure":
            pressure = float(parsed[1])
            if initial_pressure is None:
                initial_pressure = pressure
                misty.speak(f"The current pressure is {initial_pressure} hPa.")
                announce_weather_condition(pressure)
            check_pressure_change(pressure)
        elif parsed[0] == "humidity":
            humidity = parsed[1]
    
    if temperature and pressure and humidity:
        display_data(temperature, pressure, humidity)

# Start the announcement thread
announcement_thread = threading.Thread(target=announce_readings)
announcement_thread.daemon = True
announcement_thread.start()

# Register serial event
misty.register_event(event_name="serial_message_event", event_type=Events.SerialMessage, callback_function=serial_msg_test, keep_alive=True)
print("Serial event registered. Waiting for data...")

# Keep the program running 
# CHOOSE OF THE FOLLOWING SOLUTION

#you can use this variation suggested by 
try:
    while True:
        pass # No delay to ensure real-time updates
except KeyboardInterrupt:
    print("Program terminated by user.")
except Exception as e:
    print(f"Error in keep_alive: {e}")

#or the usual misty command
misty.keep_alive()

This is a very well-built code. On top, we have the libraries that Misty will use. Then we connect with our robot via IP address as usual and declare the variables that we'll use in the code.

Then we have the functions that we'll use to read and normalize the data, check the variation in pressure and change Misty's display and behaviour according to the data.

In the last lines, we find the function that registers the event and two possible solutions to keep Misty alive. Remember to use only one of the two solutions.

Notes from the creator:

The barometric values I entered for when Misty says "a storm is en route or not ..." will change depending on where you live and the altitude you are at.

The best way to figure out your own is to run the program frequently, on sunny clear days, rainy days and most importantly note the levels during a major storm (snow, thunderstorms etc).

Eventually, you will figure out which values are appropriate to your own location.

Thanks

A special thanks to Scott who shared with us his Misty weather forecaster project! You can find his contacts here if you are willing to collaborate with him on new Misty projects! crmfghtr@yahoo.com

Last updated