#!/usr/bin/env python #This code counts how many times the reed switch of the anemometer closes the circuit #in every rotation it happens two times. We then can translate the number of counts #in distance knowing the radius of the anemometer and using the equation of 2*pi*radius #We then calculate speed of the wind, dividing the distance by time, fixing a given #predermined period of time (wind_interval). Just make sure you leave the same number in #wind_interval and in the client.loop (timestamp + number). import cayenne.client from gpiozero import Button import time import logging import math MQTT_USERNAME = "xxxx" MQTT_PASSWORD = "xxxx" MQTT_CLIENT_ID = "xxxx" wind_count = 0 # counts how many half-rotations radius_cm = 9.0 # radius in cm of the anemometer wind_interval = 5 # how often (secs) to report speed ADJUSTMENT = 1.18 # adjustment of the anemometer given by the manufacturer # The callback for when a message is received from Cayenne. def on_message(message): print("message received: " + str(message)) # If there is an error processing the message return an error string, otherwise return nothing. client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID,port=8883) # every half-rotation, add 1 count def spin(): global wind_count wind_count = wind_count + 1 # print("spin" + str(wind_count)) # calculate the wind speed def calculate_speed(time_sec): global wind_count circumference_cm = (2 * math.pi) * radius_cm rotations = wind_count / 2.0 dist_km = (circumference_cm * rotations) / 100000.0 # divided by cm in a km km_per_sec = dist_km / time_sec km_per_hour = km_per_sec * 3600 # multiplied by secs in an hour return km_per_hour * ADJUSTMENT def reset_wind(): global wind_count wind_count = 0 # recommended function to reset the wind_count to zero when assembling the weather station wind_speed_sensor = Button(5) wind_speed_sensor.when_pressed = spin i=0 timestamp = 0 # loop to measure wind speed and report at 5 secs interval. Number after while True: client.loop() if (time.time() > timestamp + 5): x = calculate_speed(wind_interval) client.virtualWrite(1,x) print(x) wind_count = 0 timestamp = time.time()