Functions in Micro-python

1k views Asked by At

i have a question about micro-python that how to make and call functions in micro-python or any other idea related to functions my code throwing an error that NameError: name 'my_func' isn't defined

import time
from machine import Pin
led = Pin(2, Pin.OUT)
btn = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
    if not btn.value():
        my_func()
        while not btn():
            pass
        
def my_func():
    led(not led())
    time.sleep_ms(300)
2

There are 2 answers

0
Lixas On

Generaly, what I do following: Imports then Functions and after that- rest of the flow

Slightly modified your code to pass LED object for function

import time
from machine import Pin

def my_func(myLed):
    myLed.value(not myLed.value()) # invert boolean value
    time.sleep_ms(300)


led = Pin(2, Pin.OUT)
btn = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
    if not btn.value():
        my_func(led)
        while not btn():
            pass
    
1
user8261244 On

you need to import a function before it can be called.