#Reading the Sensirion SDP810 125PA sensor
#Dev by JJ Slabbert
#Run sudo i2cdetect -y 1 to see if the sensor is connected. it will show address 25

import smbus
import time
import math
import Adafruit_CharLCD as LCD


# Raspberry Pi pin configuration:
lcd_rs        = 25  # Note this might need to be changed to 21 for older revision Pi's.
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 17
lcd_d6        = 21
lcd_d7        = 22
lcd_backlight = 4

#Specify the screen size
lcd_columns = 16
lcd_rows    = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
lcd.clear() #Clear any text on the lcd screen
lcd.message("Starting \nanemometer.py")

bus=smbus.SMBus(1) #The default i2c bus
address=0x25
bus.write_i2c_block_data(0x25, 0x3F, [0xF9]) #Stop any cont measurement of the sensor
time.sleep(0.8)

##Detect Sensor info
##bus.write_i2c_block_data(address,0x36,[0x7c])
##time.sleep(5)
##prodinfo=bus.read_i2c_block_data(address,0)
##print(prodinfo)

#Read Sensor
bus.write_i2c_block_data(address,0x36,[0x03]) #Start cont measurement
time.sleep(0.8)
a_wind_speed=0
max_wind_speed=0
min_wind_speed=12.2
x=0.00000
n=0
while True:
    n=n+1
    x=x+1
    time.sleep(0.01)
    reading=bus.read_i2c_block_data(address, 0, 9)
    reading0=reading[0]
    reading1=float(reading[1])    
    flowval=reading0+reading1/255    
    if flowval>=0 and flowval<128:
        flowrate=flowval
        wind_speed=math.sqrt(flowrate*0.72/0.625)
    elif flowval==128:
        print ("Error: Wind to strong")
        if a_wind_speed>0:
            max_wind_speed=12.2
        if a_wind_speed<0:
            min_wind_speed=-12.2
        lcd.clear()
        a_wind_speed=0
        wind_speed=0
        lcd.message("Wind to strong")

    else:
        flowrate=-(256-flowval)        
        wind_speed=-1*math.sqrt(-1*flowrate*0.72/0.625)
        
    a_wind_speed=a_wind_speed*0.97+wind_speed*0.03
    long_a_wind_speed=a_wind_speed*0.999+wind_speed*0.001
    
    if int(x/40)==float(x/40) and n>200 :
        lcd.clear()
        if a_wind_speed>0.2 or a_wind_speed<-0.2:            
            print("Wind Speed: "+str(round(a_wind_speed,1))+" m/s")
            if a_wind_speed>max_wind_speed:
                max_wind_speed=a_wind_speed
            if a_wind_speed<min_wind_speed:
                min_wind_speed=a_wind_speed
            lcd.message("W Gust: " +str(round(a_wind_speed,1))+" m/s"+"\n" +"("+str(round(min_wind_speed,1))+", "+str(round(max_wind_speed,1))+")")

            
        else:
            wind_dir="No Wind"
            print ("No wind")
            if a_wind_speed>max_wind_speed:
                max_wind_speed=a_wind_speed
            if a_wind_speed<min_wind_speed:
                min_wind_speed=a_wind_speed
            lcd.message("W Gust:" +str(0)+" m/s"+"\n" +"("+str(round(min_wind_speed,1))+", "+str(round(max_wind_speed,1))+")")
        x=0.0000000
    

        
    



