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():


    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?


  • 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


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


    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
    for cycles in range(10): # stop after 10 cycles
        pycom.rgbled(0x007f00) # green
        pycom.rgbled(0x7f7f00) # yellow
        pycom.rgbled(0x7f0000) # red

    look into docs

  • @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?


  • @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.

Log in to reply

Pycom on Twitter