import tm1637
from machine import ADC, Pin
import utime
# Testing
output_pin = machine.Pin(21, machine.Pin.OUT)
output_pin.on()
# Initialize the TM1637 display
tm = tm1637.TM1637(clk=machine.Pin(0), dio=machine.Pin(1))
sensor_pin = 28
sensor = ADC(Pin(sensor_pin))
# Set the pin to provide a 3.3V output
# Clear the display initially
tm.show(" ")
# Function to display a number
min_sensor_voltage = 0
# Read max_sensor_voltage from a file if it exists
max_sensor_voltage = 65535 # Default value
try:
with open("max_sensor_value.txt", "r") as file:
max_sensor_voltage = int(file.read())
except OSError:
pass
try:
with open("min_sensor_value.txt", "r") as file:
min_sensor_voltage = int(file.read())
except OSError:
pass
fuel_tank_size = 100
readDelay = 0.5
# Define the button pins
button_set_max_pin = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)
button_set_min_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
# Variables to handle button debouncing
button_set_max_state = 1 # Initialize with the button not pressed
button_set_min_state = 1 # Initialize with the button not pressed
button_set_max_last_change = utime.ticks_ms()
button_set_min_last_change = utime.ticks_ms()
debounce_delay = 50 # Adjust this value as needed
try:
while True:
fuel_voltage_range = max_sensor_voltage - min_sensor_voltage
current_voltage_minus_min = sensor.read_u16() - min_sensor_voltage
if current_voltage_minus_min < 0:
current_voltage_minus_min = 0
if fuel_voltage_range == 0:
fuel_voltage_range = 1
# fuel_level = (max_sensor_voltage - sensor.read_u16()) * fuel_tank_size / (max_sensor_voltage - min_sensor_voltage)
fuel_level = (current_voltage_minus_min / fuel_voltage_range) * fuel_tank_size
print("fuel_level: " + "%.2f" % fuel_level + "L (adc: " + str(sensor.read_u16()) + ")")
output = str(int(fuel_level))
formatted_output = f'{" " * (4 - len(output) - 1)}{output}L'
tm.show(formatted_output)
# Read button states and apply debounce
current_time = utime.ticks_ms()
if current_time - button_set_max_last_change >= debounce_delay:
button_set_max_last_change = current_time
button_set_max_state = button_set_max_pin.value()
if current_time - button_set_min_last_change >= debounce_delay:
button_set_min_last_change = current_time
button_set_min_state = button_set_min_pin.value()
print(str(max_sensor_voltage) + " - " + str(min_sensor_voltage))
# Check if the button to set max voltage is pressed (logic low)
if button_set_max_state == 0:
max_sensor_voltage = sensor.read_u16()
# Write the sensor value to the file
with open("max_sensor_value.txt", "w") as file:
file.write(str(max_sensor_voltage))
# Check if the button to set min voltage is pressed (logic low)
if button_set_min_state == 0:
min_sensor_voltage = sensor.read_u16()
# Write the sensor value to the file
with open("min_sensor_value.txt", "w") as file:
file.write(str(min_sensor_voltage))
utime.sleep(readDelay)
except KeyboardInterrupt:
pass
# Clear the display before exiting
tm.show(" ")