I would move the print statement to
print_adc() as I think that may cause an allocation. Are you using the official port or the Loboris one?
There are a few things which can be improved in your code. Instantiating the ADC in the interrupt handler is, at best, inefficient. Also I don't think you can use any pin for the ADC. I don't have your hardware but the following worked for me on an ESP32 board:
Code: Select all
from machine import ADC, Pin
import micropython
micropython.alloc_emergency_exception_buf(100)
adc = ADC(Pin(34)) # A valid ADC pin
adc.width(ADC.WIDTH_9BIT)
adc.atten(ADC.ATTN_11DB)
def print_adc(pin):
print("PIN %s value: %r" % (pin, pin()))
print("ADC value: %r" % adc.read())
def irq_handler(pin):
micropython.schedule(print_adc, pin)
pin = Pin(23, mode=Pin.IN, pull=Pin.PULL_UP)
pin.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=irq_handler)
Lastly, unless your platform has hardware debouncing, for anything other than a quick hack you need to debounce the digital I/O pins. There are many solutions to this, but if you understand (or are prepared to learn) asynchronous programming one way may be found in
this repo. Otherwise solutions using timers may be found in this forum.