tl;dr: Strip this to the bones, get the threading working, then build it back up.
Thank you for posting the source.
I added some code review at the bottom.
cite your reference
tried to implement ... as I've seen on many tutorials / projects
It would be helpful if there were # comments in the source
code mentioning the URL of a tutorial this is based on.
As written, it does not appear to me that the OP code
should be expected to work, as it does not appear to be
playing nice with the OS.
Ordinarily I would expect to see a
class BackgroundLogging(Thread):
which we can start, run, and perhaps join if it ever exits.
Mentioning documentation URLs in the source code can be helpful, too.
I can't say that I find this encouraging:
https://docs.micropython.org/en/latest/library/_thread.html
This module implements multithreading support.
This module is highly experimental and its API is not yet fully settled and not yet described in this documentation.
Maybe it's supposed to not work?
I didn't notice any automated tests in there, unlike some
of the other modules such as time.
independent tasks
Your code has three looping tasks:
- wait for HTTP request and send HTML result
- append a new temperature reading to a file
- print "test" to show we're still alive
Given that "nothing works" currently,
I recommend you scale back your ambitions until you
have something very simple which is working.
Then you can slowly build it up to something fancier,
pausing to debug if some tiny addition managed to break things.
So start a red, a green, and a blue thread.
Each will simply print color + timestamp,
briefly sleep, and then loop to repeat.
No special ADC hardware is needed, so you can test it
on your laptop, see it work, then test on the Pi, and see it work.
I assume the ADC(4) and sensor.read_u16() calls
are "fast" and do not block threads.
Replacing them with a constant of 0 and then restoring
the original call will let you verify that during testing.
networking
Aren't you supposed to import usocket as socket ?
file format
After your code has been successfully working for a day,
each temperature poll will have to write out
8640 lines of temperature data, which seems like
8639 lines too many.
I recommend you abandon JSON format and prefer to import csv.
Then you can append a single line and flush() it out.
A fancier approach would use the builtin sqlite database.
That way you could store a year's worth of readings,
and use an indexed table to quickly get just today's temperatures.
Here is some unrelated code review.
You might rename open_socket() to open_web_socket().
pathlib
def file_exists(filepath):
try:
os.stat(filepath) # Check if the file exists
return True
except OSError:
return False
We can tighten this up by preferring the newer
pathlib
which has been available since 2022.
from pathlib import Path
def file_exists(filepath: str) -> bool:
return Path(filepath).exists()
get_sensors_values().