import machine
import math
import utime
import random
import time
# Get temperature function which returns temperature from sensor in celsius as float
# Function uses random number in order to have different values
def get_temperature():
analog_value = adc.read_u16()
voltage = (analog_value / 65535) * V_REF
resistance = R1 / ((V_REF / voltage) - 1)
kelvin = 1 / (1 / 298.15 + 1 / BETA * math.log(resistance / 10000))
celsius = kelvin - 273.15
return round(celsius * get_random_number(), 2)
# Get random number between 0.9 to 1.1 with a chance of 5% that the number is between 0.1 and 1.6
def get_random_number():
if(random.randint(0,100)< 50):
return random.uniform(0.1, 1.6)
else:
return random.uniform(0.9, 1.1)
# Set Beta ´value for temperature sensor
BETA = 3950
# Set Resistor value for temperature sensor
R1 = 10000
# Set reference voltage for temperature sensor
V_REF = 3.3
# Initialise ADC with temperature sensor connected
adc = machine.ADC(machine.Pin(28))
def generate_timestamp():
# Custom function to generate a timestamp string
# Example: "YYYY-MM-DD HH:MM:SS"
# Note: MicroPython may not support all formatting options like strftime()
current_time = utime.localtime() # Get current local time components
year, month, day, hour, minute, second, *_ = current_time
return f"{year:04d}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
def main():
temps = []
events = []
while True:
#implement assignment
current_temp = get_temperature()
current_time = generate_timestamp() # Get current timestamp
temps.append(current_temp)
if len(temps) > 100:
temps = temps[-100:]
#print(temps)
#utime.sleep(1)
max_temp = max(temps)
min_temp = min(temps)
# Check for temperature events (under 10°C or over 30°C)
if current_temp < 10 or current_temp > 30:
# Create an event tuple (temperature, timestamp)
event = (current_temp, current_time)
# Append the event to the events list
events.append(event)
print(f"{event}")
utime.sleep(1)
print(max_temp, min_temp)
if __name__ == "__main__":
main()