Create and Write to a Text File in MicroPython for ESP32 and ESP8266

In this project, you’ll learn how to Create and Write to a Text File in MicroPython for ESP32 and ESP8266. Writing data to a file is essential for logging sensor readings, storing configuration data, or saving information for future use. This project will cover the key file operations: file open, write, and close to efficiently store sensor data.

Purpose of the Project:

The purpose of this project is to:

  • Create a text file in MicroPython for storing sensor data.
  • Write sensor readings to the text file.
  • Understand how to open, write, and close files in MicroPython to manage data.

Data Types and Variable Table for Creating and Writing to a Text File in MicroPython

Data Type Variable Name Description
string file_name The name of the text file to be created and written to.
object file Represents the file object used to open, write, and close the file.
int sensor_data Sample data that simulates a sensor reading to be stored in the file.

Syntax Table for Creating and Writing to a Text File in MicroPython

Operation Syntax Example
Open File file = open(‘file_name’, ‘mode’) file = open(‘sensor_data.txt’, ‘w’)
Write to File file.write(data) file.write(“Sensor data: 25\n”)
Close File file.close() file.close()

Required Components for Creating and Writing to a Text File

  • ESP32 or ESP8266 board
  • Sensor (optional, to collect data for logging)
  • MicroPython installed on your board
  • Jumper Wires (if using sensors)

Circuit Diagram for Writing Sensor Data to a File (Optional for Sensor Connection)

If you are using a sensor to log data, connect the sensor to the ESP32 or ESP8266 as needed. Here’s an example using a temperature sensor (like the TMP36) connected to an ADC pin.

          TMP36

          ——-

          |     |

          | VCC |—--> 3.3V

          | OUT |—--> GPIO34 (ADC Pin)

          | GND |—--> GND

          ——-

 

Circuit Connection Table (Optional for Sensor Connection)

Component Pin ESP32/ESP8266 Pin Explanation
Sensor VCC Connected to 3.3V 3.3V Powers the sensor.
Sensor OUT Connected to GPIO34 GPIO34 Reads the sensor data through an ADC pin.
Sensor GND Connected to GND GND Ground connection for the sensor.

File Operations Analysis for Creating and Writing to a Text File:

MicroPython provides file handling functions similar to standard Python. You can create or open a file in different modes (‘w’ for write, ‘a’ for append), write data to it, and then close the file when finished. The data written can be sensor readings, configuration settings, or any other data you need to store persistently on the ESP32/ESP8266.

Writing the MicroPython Code for Creating and Writing to a Text File:

Here’s an example code that demonstrates how to create a file and log sensor data into it:

import machine

import time

 

# Simulated sensor data (replace with actual sensor readings if using a sensor)

def get_sensor_data():

    return 25  # Example static temperature value

 

# File operations: create, write, and close the file

file_name = ‘sensor_data.txt’

 

def write_data_to_file(data):

    # Open the file in write mode (overwrites the file if it exists)

    with open(file_name, ‘w’) as file:

        file.write(“Sensor Data Log\n”)

        file.write(f”Temperature: {data} °C\n”)

        file.write(f”Timestamp: {time.time()}\n”)

 

# Continuously log sensor data every 5 seconds

while True:

    sensor_data = get_sensor_data()  # Simulate reading sensor data

    write_data_to_file(sensor_data)  # Write data to file

    print(f”Logged data: {sensor_data} °C”)

    time.sleep(5)  # Delay between logs

 

Running the Code and Checking the Output:

  1. Upload the code to your ESP32 or ESP8266 using Thonny or another MicroPython IDE.
  2. The code will create a text file called sensor_data.txt on the ESP32/ESP8266’s file system.
  3. Every 5 seconds, it will write the simulated sensor data (or real data if a sensor is connected) to the file, along with a timestamp.
  4. You can access the file through Thonny’s file manager or any MicroPython-compatible IDE to check the logged data.

Explanation of the Code:

  • File Creation: The file is created using open(file_name, ‘w’). If the file already exists, it will be overwritten. You can switch to ‘a’ mode to append data without overwriting.
  • Writing Data: The file.write() method writes the sensor data and timestamp to the file in a structured format.
  • File Closing: The file is automatically closed using the with statement, ensuring proper resource management.
  • Loop Function: The program continuously logs sensor data at 5-second intervals, simulating periodic data collection.

Expanding the Project:

  1. Append Mode: Modify the file mode to ‘a’ to append data instead of overwriting it, allowing you to log multiple readings over time.
  2. Data Formatting: Enhance the data logging format by adding more details, such as sensor types, units, or more complex structures like JSON.
  3. Sensor Integration: Replace the simulated data with actual readings from connected sensors like temperature, humidity, or light sensors.

Common Problems and Solutions for Creating and Writing to a Text File:

Problem Solution
File not created or written to Ensure that MicroPython has file system access and there is enough space.
Data not being written to the file Check if the correct file mode (‘w’ or ‘a’) is used and verify file permissions.
Overwriting data every time Use ‘a’ mode instead of ‘w’ to append data instead of overwriting it.

FAQ for Creating and Writing to a Text File:

Q: How can I read the data back from the file?
A: Use open(‘file_name’, ‘r’) and file.read() to read the contents of the file.

Q: How do I write multiple sensor readings to the same file?
A: Use ‘a’ mode to append data to the file instead of overwriting it. This will allow you to add multiple sensor readings over time.

Q: Can I write to the file while the ESP32/ESP8266 is connected to a sensor?
A: Yes, you can use the same process to log real sensor data into the file. Just replace the simulated data with actual sensor readings.

Conclusion:

In this project, you learned how to create and write to a text file in MicroPython for ESP32 and ESP8266. By understanding how to open, write, and close files, you can log sensor data, store configuration settings, and manage persistent data efficiently. This project provides a strong foundation for creating data logging applications in embedded systems.