Search code examples
pythonmultithreadingglobal-variablesesp32micropython

Micropython - Share variable in threads for funcions defined in diferent .py (files)


I have an ESP32 with Micropython firmware in it and I have two process in thread on it:

  1. Wi-Fi Connection with webpage interaction
  2. Neopixel led strip stuff

What I want to do is to interact through webpage (1) to change the Neopixel led stuff (2). Both process are in Threads. The problem is, how I change a variable from process (1) to (2)? I tryed using global variables and it did work if both thread process and its functions are in the same file (.py), but if I do the same but placing the function in diferent .py, it does not work!!

This below works:

import _thread
from time import sleep

var_global = 0

def thread_Teste1():
  global var_global
  while True:
    sleep(1.5)
    var_global += 1
    print("Teste1: ", var_global)

def thread_Teste2():
  global var_global
  while True:
    sleep(1)
    var_global += 1
    print("Teste2: ", var_global)

# Thread
try:
  _thread.start_new_thread(thread_Teste1, ())
  _thread.start_new_thread(thread_Teste2, ())
except Exception:
  import traceback
  print(traceback.format_exc())

while True:
    sleep(1000)

But if I do the same putting the "while True" code into a function in separated file .py, it does not work, I mean, it does not see the global variable (I tried many ways coding but didn't work)

Any suggestion of how I can change a value of a variable in different threads with the code in different file .py? I found about Queue but it does not work on Micropython...

Thanks!


Solution

  • I resolved it by declaring the global variable in a separated file .py and then I import this file where I want to use. Also, where I import it, I "re"declare the variable inside with the same name (I guess to make it visible).