The Pi PICO allows you to run two programs simultaneously. Each is actually called a "Thread" and both are stored in the same Python file.
When started, the Pico runs Thread 1, and you have to put in a command in thread 1 to run a function as the second thread:
The advantage of this is that the second thread can be scanning inputs very fast, so that inputs are not missed during pauses, or long calculations in the first thread.
A sample program using two threads is Drag5 (view txt)
the first thread reads the pushbutton and line sensors, , and runs the motors. It starts thread2 running as required.
the second thread constantly scans the stop sensor at high speed and counts how many have been seen.
Starting the second thread
def Thread2():
global Markers,ClearCount,MarkerMs
print("Th2 starting")
while True:
ssense = reads(stopsense.read_u16()) # read stop sensor
while (ssense < 60):
ssense = reads(stopsense.read_u16()) # read stop sensor
time.sleep(.001)
if (ClearCount == True ): # if flag set
ClearCount = False # clear flag
Markers = 0 # reset count
# marker started...... increment count
Markers += 1
tstart = time.ticks_ms() # record start time
while (ssense >40):
ssense = reads(stopsense.read_u16()) # read stop sensor
time.sleep(.001)
if (ClearCount == True ):
ClearCount = False
Markers = 0
MarkerMs=time.ticks_diff(time.ticks_ms(),tstart) # record length
## marker ended
time.sleep(.001)
This is the code to start the second thread.
It must be included in the main thread.
_thread.start_new_thread(Thread2, ())
Communication between the threads
Both threads can see the same global data.
However, if both try to write to the same variable at the same time, there is no way of knowing which one will win.
Another variable can be used
- to signal "do something" by setting it to True,
- and signal "I have done it" by setting it to False.
If each thread checks this value before setting (or resetting) another sharedvariable, then no collisions will happen.
These variable are sometimes called "Flags"