#!/usr/bin/env python
#-*- coding: utf-8 -*-

# python3 /home/scripts_python_niveaux/niveaux_00.py


# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# ADS1115
# This code is designed to work with the ADS1115_I2CADC I2C Mini Module available from ControlEverything.com.
# https://www.controleverything.com/content/Analog-Digital-Converters?sku=ADS1115_I2CADC#tabs-0-product_tabset-2

import smbus2
import time

# Get I2C bus
bus = smbus2.SMBus(1)

# ADS1115 address, 0x48(72)
# Select configuration register, 0x01(01)
#		0xc483(33923)	AINP = AIN0 and AINN = AIN1, +/- 2.048V
#   1100 0100    1000 0011
#				Continuous conversion mode, 128SPS
data = [0xd4,0x83]
bus.write_i2c_block_data(0x48, 0x01, data)

time.sleep(0.5)

while True :

	# ADS1115 address, 0x48(72)
	# Read data back from 0x00(00), 2 bytes
	# raw_adc MSB, raw_adc LSB
	data = [0x54,0x83]
	bus.write_i2c_block_data(0x48, 0x01, data)
	time.sleep(0.25)
	
	data = bus.read_i2c_block_data(0x48, 0x00, 2)

	# Convert the data
	raw_adc = data[0] * 256 + data[1]

	if raw_adc > 32767:
		raw_adc -= 65535
		
	V_cuve_eau = (2.048/32768) * raw_adc
	H_cuve_eau = ( V_cuve_eau - 0.400 ) * (300/1.6) + 0.00


	data = [0x44,0x83]
	bus.write_i2c_block_data(0x48, 0x01, data)
	time.sleep(0.25)
	
	data = bus.read_i2c_block_data(0x48, 0x00, 2)

	# Convert the data
	raw_adc = data[0] * 256 + data[1]

	if raw_adc > 32767:
		raw_adc -= 65535
		

	V_phyto_eau = (2.048/32768) * raw_adc
	H_phyto_eau = ( V_phyto_eau - 0.382 ) * (100/1.6) + 4.80

	# Output data to screen
	print("  cuve :  V_cuve_eau = %.3f" % V_cuve_eau ,  "Volts ;  H_cuve_eau = %.1f" % H_cuve_eau, "cm")
	print(" phyto : V_phyto_eau = %.3f" % V_phyto_eau , "Volts ; H_phyto_eau =  %.1f" % H_phyto_eau, "cm")
	
	print(" ")
	


