Function global not readable by 'main' - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Function global not readable by 'main' (/thread-36090.html) |
Function global not readable by 'main' - fmr300 - Jan-15-2022 Wierd problem been trying to resolve for several hours - appreciate any help ! I'm runinng an ADC-sampler in a separate thread function, which logs the max-sample found during each second (approx). It signals 'main' that the max-value is ready via a flag global.... while also posting the max-value in a data global. Below is the code and the output. 'main' gets signaled properly via the flag global, but the data-value doesn't arrive - it's usually 0, but about 20% of the time some odd non-0 value. import machine import _thread ################################################ # Variables global readyFlag readyFlag = False global max_found max_found = 0 ################################################ # Functions def sampler_thread(): # Function that will be launched as a separate thread. global readyFlag global max_found adc1 = machine.ADC(26) # Start an ADC while True: max_found = 0 # Init to smallest possible value before sampling-loop cnt = 20000 # Init loop-cntr while cnt > 0: # Loop until counter=0 cnt -= 1 sample = adc1.read_u16() # Get next sample if sample > max_found: # If >max-found, set it to max-found max_found = sample print("sampler max_found:", max_found) readyFlag = True # Tell the 'main' thread that max_found is ready. ############################################## # Main _thread.start_new_thread(sampler_thread, ()) while True: if readyFlag: print("main max_found:",max_found) readyFlag = False********************** OUTPUT SAMPLE ('sampler max_found' is correct, but 'main' gets mostly 0's or odd#): sampler max_found: 2688 main max_found: 2368 sampler max_found: 2704 main max_found: 0 sampler max_found: 2672 main max_found: 0 sampler max_found: 2688 main max_found: 2128 RE: Function global not readable by 'main' - deanhystad - Jan-16-2022 What is the target os? Why aren't you using the threading module? |