In the ebook “MicroPython Programming with the ESP-8266 and ESP-32” module 4, is there a way to get the weather data in a loop so the data refreshes continuously? Thanks.
Yes, you can do that.
For example, create the following variables at the beginning of your code: change the message_interval variable to set the interval in seconds that you’ll request data from the API (please note that for free versions of APIs, you have a limit on the number of request you can do per day).
last_message = 0 message_interval = 60
Then, add a loop like this:
while True: try: if (time.time() - last_message) > message_interval: CODE THAT GETS DATA last_message = time.time() except OSError as e: restart_and_reconnect()
I hope this helps.
Let me know if you need further help.
Thanks for the reply. Can you please explain the code so I can understand (and learn from) it?
Lets go one line at a time. ( // indicates the start of a comment)
while True: // this is a loop that goes forever
try: // tells the compiler to try this (if it causes an exception, we will handle it further down in the code)
if (time.time() - last_message) > message_interval: // gets the current time, compares to the previous time (last_message). If it is greater than message_interval
CODE THAT GETS DATA // this is your code that gets the required data
last_message = time.time() // reset the last_message time to the current time (for next go through the loop)
except OSError as e: // this is the other part of "try". So try to do this thing, and if it throws an exception, we will tell it what to do
restart_and_reconnect() // this is what we want it to do if an exception is thrown
Also, I forgot to mention that you need to add the restart_and_reconnect() function to your code too.
Here’s the function:
def restart_and_reconnect(): time.sleep(10) machine.reset()
Thank you so much Sara and Ross. Now I can see the OWM data I need and the explanation behind the code. I added 2 things so I can see the output:
x=CODE THAT GETS DATA