A good methodology to code Wi Py 2.



  • Hello there,

    I would like to read/find some advise in regards to how to create a "infinity loop" in Wi Py 2.0. I have done it by doing the following, but I am not so sure it is the best way.

    so...I have a python.py file, and I might have the following functions defined and a "main" function inside a while(1)

    import <> from <>

    def aFuncion1:
    #some code here...

    def aFuncion2:
    #some code here...

    def main():
    aFuncion1()
    aFuncion2()

    while(1):
    main()

    I have the feeling that I am wasting resources here, and there is a better way. so question time!!

    1. Am I right or wrong in my programming approach?
    2. I am not familiar with Threads? is this the way to go?
    3. Any other ways to be more efficient code/ memory usage?
    4. Any doco that I can be pointed to?

    Cheers
    Colombian



  • Hi Everyone,

    Ok, so it looks like at the end, it is not that bad to use a While(True) to generate an infinite loop. I know that a ON/OFF LED is not really a good example.

    thank you everyone for the comments

    Cheers
    ColombianAus



  • @ColombianAus said in A good methodology to code Wi Py 2.:

    while(1):
    main()

    Never write while(1), use while(True) instead.



  • @ColombianAus

    from machine import Pin
    
    def pin_handler(arg):
        print("got an interrupt in pin %s" % (arg.id()))
    
    p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP)
    p_in.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING, pin_handler)
    

    but for blinking led it is not good

    import pycom
    import time
    pycom.heartbeat(False)
    for cycles in range(10): # stop after 10 cycles
        pycom.rgbled(0x007f00) # green
        time.sleep(5)
        pycom.rgbled(0x7f7f00) # yellow
        time.sleep(1.5)
        pycom.rgbled(0x7f0000) # red
        time.sleep(4)
    

    look into docs
    https://docs.pycom.io/pycom_esp32/pycom_esp32/tutorial/includes/led.html



  • @livius

    Thank you for your reply. I am totally new to micro python programming style. All I want to do, at the moment is to turn a LED On and Off a fix number of times. Would you mind to elaborate a bit more about the pin handler option?

    Cheers
    ColmobianAus



  • @ColombianAus

    This depend of code - e.g. better is have pin handler instead read it in every loop.
    You can also use machine.idle to prevent 100% CPU usage
    Without more specific sample of usage it is rather hard to advice something.


 

Pycom on Twitter