0

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 Answers2

1

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
    
Lixas
  • 6,938
  • 2
  • 25
  • 42
0

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

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 07 '22 at 08:06