Using Interrupts to react quickly

The Pi Pico can handle interrupts.
An interrupt is an arrangement in which the normal flow of a program is paused, when an input pin changes state.
When this happens a designated function is made to run.

This is set up by a command in the program, using a "method" of the chosen pin ( .irq() ) that attaches a function to a pin - See below


See sample program: Testint.py . View: Testint.txt

Setting up software
The function is written normally in the program, and can access pins and variables in the normal way.
Note that data items seen by the main program must be set as global
It records the state of the pin (ssense), and keeps a count of black-white transitions (Markers)

This is the interrupt handler function

def stpirq(PinId):    #PinId is the oin it happened on
    global Markers          # count of stop sensors
    global ssense           # sensor "value" for main prog
    if (stp.value() == 1):     # Black
        led2.off()             # side LED
        ssense = 0
    else:                      # white
        led2.on()              # side LED
        ssense = 100
        Markers+=1             # increase count


Setting up the interrupt to call the handler

# set up interrupts on pin "stp" 
#    to cause function "stpirq()" 
#     to run whenever it changes from 0-1 or 1-0.

stp = Pin(28, Pin.IN) # set up stop sensor input as digital not analogue

              # set up interrupt handler for pin stp as stpirq()
stp.irq(handler=stpirq,trigger=Pin.IRQ_FALLING|Pin.IRQ_RISING) 
    
Setting up hardware
Required sensor voltages.
- for digital inputs the input voltage should be above 1.7 volts, (dark)
or below 1.4 volts (white).
- The readings for the standard stop sensor circuit are about 2.8v and 2.0 volts.
  Changing the detector load resistor can bring the white voltage to about 0.3v
How to modify the sensor.
- the load resistor (R11) of the detector should be changed from 2.0k to 4.7k
- this allows the white (low) reading to go down to 0.2 volts when the detector draws it maximum curent.

Make a free website with Yola

Old
New