from machine import ADC, Pin
import time
# Constants
V_IN = 3.3 # Supply voltage (in Volts) from ESP32
R_known = 10000 # Known resistor value in ohms (e.g., 10kΩ)
# Setup GPIO 27 as output (providing 3.3V)
gpio_27 = Pin(27, Pin.OUT)
gpio_27.value(1) # Set GPIO 27 high (3.3V)
# Setup GPIO 34 as ADC input
adc = ADC(Pin(36))
adc.atten(ADC.ATTN_11DB) # Set attenuation to measure up to 3.3V
# Function to measure the unknown resistor
def measure_resistance():
# Read the ADC value (12-bit resolution, so value is from 0 to 4095)
adc_value = adc.read()
# Convert the ADC value to a voltage
V_out = adc_value * V_IN / 4095 # ADC value to voltage
# Calculate the resistance using the voltage divider formula
if V_out == 0:
return float('inf') # To avoid division by zero
# If both resistors are equal, use the known resistor value for R_known
R_unknown = R_known * (V_IN / V_out - 1)
return R_unknown
# Collect readings
readings = []
for i in range(10):
R_unknown = measure_resistance()
readings.append(R_unknown)
print("Measured Resistance {}: {:.2f} ohms".format(i + 1, R_unknown))
time.sleep(1)
# Calculate and print the average resistance
average_resistance = sum(readings) / 10
print("Average Measured Resistance: {:.2f} ohms".format(average_resistance))