004 - ESP32 MicroPython: External Interrupts

Circuit Diagram for Example 3

Video Demonstration

Source Code

Example 1, Simple Polling:

 1"""
 2*** Simple Polling Method of reading an input ***
 3
 4	Author: George V. Bantique, TechToTinker
 5	Date: September 10, 2020
 6	Description: The switch or the BOOT switch is
 7		polled until such time that the switch
 8		is detected at logic LOW
 9		When the switch is press, it will blink
10		the onboard LED on GPIO2 for 7 times then
11		will send a 'Done.' message before it exit
12"""
13import machine
14import time
15
16led = machine.Pin(2, machine.Pin.OUT)
17sw = machine.Pin(0, machine.Pin.IN)
18
19def blink_led_ntimes(num, t_on, t_off, msg):
20    counter = 0
21    while (counter < num):
22        led.on()
23        time.sleep(t_on)
24        led.off()
25        time.sleep(t_off)
26        counter += 1
27    print (msg)
28
29while True:
30    if (sw.value() == 0):
31        blink_led_ntimes(7, 0.25, 0.50, 'Done.')

Example 2, Simple Interrupt:

 1"""
 2*** Simple Interrupt Method of reading an input ***
 3
 4	Author: George V. Bantique, TechToTinker
 5	Date: September 10, 2020
 6	Description: The switch or the BOOT switch is
 7		attached to interrupt for efficiency.
 8		When the interrupt is triggered, it will
 9		toggle the state of the onboard LED
10		on GPIO2.
11"""
12import machine
13
14led = machine.Pin(2, machine.Pin.OUT)
15sw = machine.Pin(0, machine.Pin.IN)
16
17def handle_interrupt(pin):
18    led.value(not led.value())
19    
20sw.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_interrupt)

Example 3, DC motor with limit switch using interrupts:

 1""" 
 2*** DC motor with limit switch using interrupts ***
 3	Author: George V. Bantique, TechToTinker
 4	Date: September 10, 2020
 5	Description: The direction of rotation of the DC motor
 6		is controlled by the limit switch in the
 7		left or right side. L298N motor driver module
 8		is use to isolate and protect the ESP32.
 9"""
10
11import machine
12
13sw1 = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
14sw2 = machine.Pin(21, machine.Pin.IN, machine.Pin.PULL_UP)
15dr1 = machine.Pin(22, machine.Pin.OUT)
16dr2 = machine.Pin(23, machine.Pin.OUT)
17
18press = False
19irq_pin = 0
20
21def handle_interrupt(pin):
22    global press
23    press = True
24    global irq_pin
25    irq_pin = int(str(pin)[4:-1])
26
27sw1.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_interrupt)
28sw2.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_interrupt)
29
30while True:
31    if press:
32        print(irq_pin)
33        press = False
34        
35        if irq_pin == 15:
36            dr1.value(0)
37            dr2.value(1)
38            print('counter')
39        elif irq_pin == 21:
40            dr1.value(1)
41            dr2.value(0)
42            print('clockwise')
43        else:
44            pass


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.