Introduction:
Not all projects need a cloud connection. Sometimes, you just want to log sensor data locally for later analysis. In this lesson, you’ll learn how to collect environmental sensor readings using the UNIHIKER K10 and save them to a text or CSV file using MicroPython. This feature is ideal for fieldwork, offline logging, or classroom science experiments.
What You’ll Learn:
How to open and write to files using MicroPython
How to log temperature, humidity, and light data over time
How to timestamp your logs using the system clock
How to view or export log files later via USB or Thonny
🔧 Step 1: Setup Sensors
from pinpong.board import Board
from pinpong.libs.unihiker import TempHumSensor, LightSensor
import time
Board().begin()
temp_humi = TempHumSensor()
light = LightSensor()
📝 Step 2: Open a File and Write Data
# Open or create log file
log_file = open("sensor_log.csv", "a") # Use "w" to overwrite instead
# Optional: write header row
log_file.write("timestamp,temperature,humidity,light\n")
🔁 Step 3: Log Sensor Data with Timestamps
while True:
timestamp = time.time()
temp, humi = temp_humi.read()
light_val = light.read()
line = f"{timestamp},{temp:.2f},{humi:.2f},{light_val}\n"
log_file.write(line)
log_file.flush() # Ensure data is saved in real time
print("Logged:", line.strip())
time.sleep(5)
You can stop the script anytime using Thonny or by rebooting. Your file sensor_log.csv will appear in the root directory of the device.
💡 Tips for Better Logging
Use
time.localtime()to convert the timestamp into readable date/time.Rotate files by date (e.g.,
log_2025_07_24.csv).Visualize the data in Excel, Google Sheets, or Python’s pandas.
Conclusion:
This lesson gives your UNIHIKER K10 the ability to store data locally—perfect for offline environments or battery-powered field sensors. You can combine this with Lesson 3 (Sensor Dashboard) or Lesson 5 (IoT) to offer both live and offline data features. In future lessons, you could schedule logging via button press, add log file selection menus, or even upload logs later when Wi-Fi becomes available.
