belrey10

Day 9: Return with the Elixir – Storing and Retrieving Data

Nov 5th, 2024 (edited)
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. import machine
  2. import time
  3.  
  4. # Initialize the photoresistor and the button
  5. photoresistor = machine.ADC(machine.Pin(26))
  6. button = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_DOWN)
  7.  
  8. # File to store data
  9. filename = "light_data.txt"
  10.  
  11. def read_sensor_data():
  12.     light_level = photoresistor.read_u16()
  13.     return light_level
  14.  
  15. def store_data(data):
  16.     with open(filename, 'a') as f:
  17.         f.write(f"{data}\n")
  18.  
  19. def retrieve_data():
  20.     try:
  21.         with open(filename, 'r') as f:
  22.             data = f.readlines()
  23.             return data
  24.     except OSError:
  25.         return []
  26.  
  27. while True:
  28.     if button.value() == 1:
  29.         light_level = read_sensor_data()
  30.         store_data(light_level)
  31.         print(f"Data Stored Successfully")
  32.         time.sleep(2)
  33.        
  34.         print(f"Retrieving stored data")
  35.         file_content = retrieve_data()
  36.         time.sleep(1)
  37.         print(f"Retrieved data is: {file_content}")
Add Comment
Please, Sign In to add comment