'''
example name：Water level sensor
version：v1.0
date：2020.3
Author：01Studio
Description: Measure the Water level (liquid level) height and display it in oled.
Forum: forum.01studio.org
'''

#import ADC module
from gpiozero import MCP3004

#import luma,oled lib
from luma.core.render import canvas
from luma.oled.device import ssd1306

from time import sleep

#initialize oled，I2C1; the oled address is 0x3c
device = ssd1306(port=1, address=0x3C)

#Initialize the ADC module and connect the sensor to CH1
adc = MCP3004(channel=1)

while True:

    V = adc.value*3.3      #Collection range: 0-1, converted into voltage value 0-3.3V

    #Water level: 0-1cm
    if 0 <= V <= 0.48:
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'Water_level test:', fill="white")
            draw.text((0, 40), str("%.2f"%V) + 'V'+' 0-1cm', fill="white")
        print("%.2f"%V + 'V'+' 0-1cm')

    #Water level: 1-2cm
    if 0.48 < V <= 0.73:
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'Water_level test:', fill="white")
            draw.text((0, 40), str("%.2f"%V) + 'V'+' 1-2cm', fill="white")
        print("%.2f"%V + 'V'+' 1-2cm')

    #Water level: 2-3cm
    if 0.73 < V <=0.97:
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'Water_level test:', fill="white")
            draw.text((0, 40), str("%.2f"%V) + 'V'+' 2-3cm', fill="white")
        print("%.2f"%V + 'V'+' 2-3cm')

    #Water level: 3-4cm
    if 0.97 < V <=1.05:
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'Water_level test:', fill="white")
            draw.text((0, 40), str("%.2f"%V) + 'V'+' 3-4cm', fill="white")
        print("%.2f"%V + 'V'+' 3-4cm')

    #Water level: >4cm
    if 1.05 < V :
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'Water_level test:', fill="white")
            draw.text((0, 40), str("%.2f"%V) + 'V'+' >4cm', fill="white")
        print("%.2f"%V + 'V'+' >4cm')

    sleep(1) #Collection interval 1 second

