CHEERSNetworkClimate & health

Home / Resources / Weather station

CHEERS technical resources · WindChaser

Source code for wind_bearer_software.mr_V6

WindChaser technical documentation: Source code for wind_bearer_software.mr_V6. Original instructions, component references and source limitations.

Original documentation: Min Tai Yap and Julian Walker · © 2025. Migrated to CHEERS on 3 December 2026. This is working documentation; unresolved source gaps remain visible.

Software source reference
"""
Contains the main script to set up and run the weather station. To set up the weather station, 
the parameters and paths need to be specified in parameter/parameters.txt and parameter/user_path.txt.
Please refer to <TODO> for further information.

:Authors:
    Min Tai Yap <Min.Yap2@monash.edu>
"""

# Essential libraries
import time
import board
import busio
import RPi.GPIO as GPIO
import smbus2
import os
import datetime
import asyncio
from adafruit_blinka.microcontroller.bcm283x.pin import Pin

# Permissions and auxiliary functions
from wind_bearer_software.utils.permission import set_gpio_permissions

# Functions
from wind_bearer_software.utils.csv_writer import csv_write, format_value
from wind_bearer_software.utils.io_utils import read_parameter_dict
from wind_bearer_software.utils.program_checker import program_checker

# Sensors
from wind_bearer_software.sensor_func.wind_speed import measure_wind_speed
from wind_bearer_software.sensor_func.rain_gauge import rain_detect
from wind_bearer_software.sensor_func.as5600 import as5600_read
from wind_bearer_software.sensor_func.sunlight_detect import sunlight_read
from wind_bearer_software.sensor_func.sht45 import sht45_read, init_sht45
from wind_bearer_software.sensor_func.sht45_heater import sht45_heat_nb
from wind_bearer_software.sensor_func.bmp388 import bmp388_init, bmp388_read
from wind_bearer_software.sensor_func.ads1115_voltage_V2 import bat_volts


[docs] async def main(): """ Sets up and runs the program to collect data from the weather station. The data from the anemometer and the rain gauge have to be read continuously. All other measurements are read after the interval specified in parameter/parameters.txt has passed. Please note that the sunlight sensor readings have not been validated, yet. Subsequently, the data is written to the latest csv file specified in the parameter/userpath.txt file. Each hour, a new csv file is created. """ # ---------------------------------- SETUP ---------------------------------------------- # Initialize GPIO permissions set_gpio_permissions() # Setup GPIO pins GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Get file paths and parameters file_paths_dict = read_parameter_dict('user_path.json') param_dict = read_parameter_dict('parameters.json') # GPIO pins and parameters hall_pin_rain = int(param_dict['hall_pin_rain']) hall_pin_wind = int(param_dict['hall_pin_wind']) interval = param_dict['interval'] wind_pri_cali = param_dict['wind_cf'] wind_sec_cali = param_dict['wind_cf_10'] bmp_slp = param_dict["sea_level_pressure"] south_deg = float(param_dict["south_deg"]) rain_scoop = param_dict['rain_scoop'] # measured volume of the scoop in ml funnel_area = param_dict['funnel_area'] # in mm^2 rain_cali = float(param_dict["rain_cali"]) ws_name = param_dict["ws_name"] # Path & directory saved_dirs = file_paths_dict['ds'] # Setup GPIO for hall sensors GPIO.setup(hall_pin_rain, GPIO.IN) GPIO.setup(hall_pin_wind, GPIO.IN) # Initialize I2C bus bus = smbus2.SMBus(1) i2c = busio.I2C(scl=Pin(3), sda=Pin(2)) # Calibration # cali_degrees = 180 - wind_deg if south_deg > 180: cali_degrees = south_deg - 180 elif south_deg < 180: cali_degrees = 180 - south_deg else: # when south_deg = 0 cali_degrees = south_deg # Initialize sensors sht = await init_sht45(i2c) bmp = await bmp388_init(i2c, bmp_slp) # Initialize runtime variables within the function scope before_time = time.time() cal_count = rain_count = rain_mm = rain_ml = flag_csv = flag_csv_df = flag_sht = 0 old_date, old_hour = -1, -1 # ---------------------------- MAIN LOOP ------------------------------------------------- try: print("Starting... Ensure rain collector and wind vane are correctly aligned.") while True: now = time.time() elapsed = int(now - before_time) # Measure wind speed and rain cal_count = measure_wind_speed(cal_count, hall_pin_wind) rain_count, raw_rain_mm, raw_rain_ml = rain_detect(rain_count, hall_pin_rain, rain_scoop, funnel_area) # Apply calibration factor rain_mm = rain_cali * raw_rain_mm rain_ml = rain_cali * raw_rain_ml if elapsed >= interval: # ------------------------------------------- Sensor readings ----------------------------------------------- raw_degrees = await as5600_read(bus) actual_degrees = raw_degrees - cali_degrees # Calibrating to actual wind direction if actual_degrees <= 360 and actual_degrees >= 0: angle_degrees = actual_degrees elif actual_degrees > 360: angle_degrees = actual_degrees - 360 elif actual_degrees < 0: angle_degrees = actual_degrees + 360 print(f'AS5600 Precise Angle: {angle_degrees:.2f} degrees') SI1151_visible, SI1151_uv, SI1151_ir = await sunlight_read() # general approximation for lux to W/M^2 is 0.0079: 1 lux ≈ 0.0079 W/m ^ 2 solar_rad = 0.0079*(SI1151_visible + SI1151_uv + SI1151_ir) print(f"Approximated Solar Radiation: {solar_rad} W/m^2") bmp_temp, bmp_pressure, bmp_altitude = await bmp388_read(bmp) battery_voltage = await bat_volts(i2c) if flag_sht <= 10: sht_temp, sht_rh = await sht45_read(sht) else: sht_temp, sht_rh = -2, -2 # return a non valid value to differentiate await sht45_heat_nb(i2c, interval) flag_sht = 0 if sht_rh > 98: flag_sht += 1 # patch to wind speed, 1 rpm = 2 cal_count because there's two magnets, SUBJECT to changes due to magnet orientation cal_count = cal_count / 2 # Calculate wind speed, apply its primary calibration factor then secondary based on 10m surface wind speed wind_speed = ((cal_count / elapsed) / wind_pri_cali) * wind_sec_cali rpm = cal_count / (elapsed / interval) # Display readings current_time = time.strftime("%Y-%m-%d %H:%M:%S") print(f"\nCurrent Time: {current_time}") print(f"Wind Speed: {wind_speed} m/s, RPM: {rpm}") print(f"Rain: {rain_mm} mm, {rain_ml} ml") # Save to CSV for folder_path in saved_dirs: if os.path.exists(folder_path): try: if flag_csv == 1: flag_csv_df = 1 else: print("First set of data is removed for consistency due to inaccuracy") current_date = datetime.datetime.now().strftime('%d%m%Y') current_hour = datetime.datetime.now().strftime('%H') if current_date != old_date or current_hour != old_hour: flag_csv = 0 # Reinitialize sensors sht = await init_sht45(i2c) try: # Format the values to two decimals first sht_temp = format_value(sht_temp) sht_rh = format_value(sht_rh) bmp_temp = format_value(bmp_temp) bmp_pressure = format_value(bmp_pressure) bmp_altitude = format_value(bmp_altitude) angle_degrees = format_value(angle_degrees) wind_speed = format_value(wind_speed) SI1151_visible = format_value(SI1151_visible) SI1151_uv = format_value(SI1151_uv) SI1151_ir = format_value(SI1151_ir) solar_rad = format_value(solar_rad) flag_csv, filepath = csv_write(ws_name, flag_csv, flag_csv_df, folder_path, current_date, current_hour, current_time, battery_voltage, rpm, rain_mm, rain_ml, sht_temp, sht_rh, bmp_temp, bmp_pressure, bmp_altitude, angle_degrees, wind_speed, SI1151_visible, SI1151_uv, SI1151_ir) print(f'Variables saved to {filepath}\n') # break # Exit the loop after successfully saving to the first available file path except: pass except Exception as e: print(f'Error processing data for {folder_path}: {e}') continue # Reset for next iteration flag_csv = 1 before_time = time.time() cal_count = rain_count = rain_mm = rain_ml = 0 old_date, old_hour = datetime.datetime.now().strftime('%d%m%Y'), datetime.datetime.now().strftime('%H') except KeyboardInterrupt: print("\nScript terminated by user.") except Exception as e: print(f"Error: {e}") finally: print("Program stopped.")
if __name__ == "__main__": # Get file paths and parameters file_paths_dict = read_parameter_dict('user_path.json') if not program_checker(file_paths_dict['main_file']): print("Another instance is running. Exiting.") exit(1) asyncio.run(main())