Skip to content

Commit f11c71a

Browse files
committed
save data to esp flash
1 parent 05e1e1a commit f11c71a

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import uasyncio as asyncio
2+
import sys
3+
import os
4+
5+
# Function to generate a unique file name with a three-digit integer
6+
def generate_filename():
7+
base_name = "output"
8+
files = os.listdir()
9+
10+
max_num = 0
11+
for file in files:
12+
if file.startswith(base_name) and file.endswith('.txt'):
13+
try:
14+
num = int(file[len(base_name):-4])
15+
max_num = max(max_num, num) # Find the highest number
16+
except ValueError:
17+
continue
18+
19+
new_file_name = f"{base_name}_{max_num + 1:03d}.txt"
20+
21+
return new_file_name
22+
23+
# Open file for writing (for Process 2)
24+
try:
25+
fname = generate_filename()
26+
file = open(fname, 'w')
27+
print(f"New file `{fname}` created")
28+
except OSError as e:
29+
print("[!] Failed to open file:", e)
30+
sys.exit()
31+
32+
# Process 1: Print to serial monitor
33+
async def process_to_serial():
34+
while True:
35+
print("This is being printed to the serial monitor")
36+
await asyncio.sleep(1)
37+
38+
# Process 2: Write to file
39+
async def process_to_file():
40+
while True:
41+
file.write("This is being written to the file\n")
42+
file.flush() # Ensure data is written immediately
43+
await asyncio.sleep(1)
44+
45+
# Main coroutine
46+
async def main():
47+
print("Starting tasks...")
48+
task1 = asyncio.create_task(process_to_serial())
49+
task2 = asyncio.create_task(process_to_file())
50+
51+
# Run both tasks concurrently
52+
try:
53+
await asyncio.gather(task1, task2)
54+
except asyncio.CancelledError:
55+
print("Tasks cancelled.")
56+
57+
try:
58+
# Event loop used to schedule and run tasks
59+
loop = asyncio.get_event_loop()
60+
loop.run_until_complete(main())
61+
62+
except KeyboardInterrupt:
63+
# This part runs when Ctrl+C is pressed
64+
print("Program stopped. Exiting...")
65+
66+
# Optional cleanup code
67+
file.close()
68+
loop.stop() # Not available in all uasyncio versions

0 commit comments

Comments
 (0)