from machine import SoftI2C, Pin, ADC
from machine_i2c_lcd import I2cLcd
from time import sleep
#LCD setup
i2c = SoftI2C(scl=Pin(1), sda=Pin(0), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
#Buttons
next_button = Pin(14, Pin.IN, Pin.PULL_DOWN)
select_button = Pin(15, Pin.IN, Pin.PULL_DOWN)
analog_pin = ADC(28)
#Variables
Rc = 10000 # 10kΩ
t = 50000 # microseconds
Known_resistor = 1000
Shunt_resistor = 1
menu_options = ["1.Ammeter", "2.Ohmmeter", "3.Voltmeter", "4.Capacitance"]
current_option = 0
def menu():
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("* MAIN MENU: ")
lcd.move_to(0, 1)
lcd.putstr(menu_options[current_option])
def Ohmmeter():
lcd.clear()
while True:
reading = analog_pin.read_u16()
voltage = (reading / 65535.0) * 3.3
print("RAW ADC:", reading, " Voltage:", voltage)
# Calculate resistance
if (3.3 - voltage) != 0:
unknown_resistance = (voltage * Known_resistor) / (3.3 - voltage)
else:
unknown_resistance = 0
lcd.move_to(0, 0)
if voltage > 3.2:
lcd.putstr("R: Open Circuit ")
elif reading < 500:
lcd.putstr("R: 0.00 Ohm ")
else:
if unknown_resistance < 1000:
lcd.putstr("R: {:.2f} ohms ".format(unknown_resistance))
else:
lcd.putstr("R: {:.2f} kOhms ".format(unknown_resistance / 1000))
# Exit to menu
if select_button.value() == 1:
sleep(0.3)
break
sleep(0.5)
def Voltmeter():
lcd.clear()
while True:
reading = analog_pin.read_u16()
voltage = (reading / 65535.0) * 3.3
print("RAW ADC:", reading, " Voltage:", voltage)
lcd.move_to(0, 0)
if reading < 100:
lcd.putstr("V: 0.00 v ")
else:
lcd.putstr("V: {:.2f} v ".format(voltage))
if select_button.value() == 1:
sleep(0.3)
break
sleep(0.5)
def Ammeter():
lcd.clear()
while True:
reading = analog_pin.read_u16()
voltage = (reading / 65535.0) * 3.3
print("RAW ADC:", reading, " Voltage:", voltage)
current_amps = voltage / Shunt_resistor
lcd.move_to(0, 0)
if current_amps < 1.0:
lcd.putstr("I: {:.2f} mA ".format(current_amps * 1000))
else:
lcd.putstr("I: {:.2f} A ".format(current_amps))
if select_button.value() == 1:
sleep(0.3)
break
sleep(0.5)
def capacitancemeter():
C = t / (Rc * 1000000)
lcd.clear()
print("\n" * 1)
print("This is a simulated C and cannot be changed through the potentiometer")
while True:
lcd.move_to(0, 0)
lcd.putstr("Simulated C:")
lcd.move_to(0, 1)
lcd.putstr("{:.6f}F".format(C))
if select_button.value() == 1:
sleep(0.3)
break
sleep(0.5)
# --- Main Loop ---
menu() # Initial draw
#learn this
while True:
# Check Next Button
if next_button.value() == 1:
current_option = (current_option + 1) % len(menu_options)
menu()
# Wait until button is released
while next_button.value() == 1:
sleep(0.01)
# Check Select Button
if select_button.value() == 1:
# Wait until button is released
while select_button.value() == 1:
sleep(0.01)
if current_option == 0:
Ammeter()
elif current_option == 1:
Ohmmeter()
elif current_option == 2:
Voltmeter()
elif current_option == 3:
capacitancemeter()
# After exiting any function, redraw the menu
menu()
sleep(0.1) # Small power-saving delayNEXT
SELECT