Search code examples
pythonobjectnonetypeiterableraspberry-pi-pico

Nonetype object isn't iterable


I'm new to Python so I decided to replicate this one

youtube : https://www.youtube.com/watch?v=3kU3_b78JpA&ab_channel=NikunjPanchal

But there is an error in coding section

from machine import UART, Pin
bt = UART(0,9600)

L1 = Pin(2,Pin.OUT)
L2 = Pin(3,Pin.OUT)

while True:

    br = bt.readline()

    if "ON1" in br:
        L1.value(0)
    elif "OFF1" in br:
        L1.value(1)

    elif "ON2" in br:
        L2.value(0)
    elif "OFF2" in br:
        L2.value(1)

error:

Traceback (most recent call last):
   File "<stdin>", line 12, in <module>
TypeError: 'NoneType' object isn't iterable

Anyone know how to fix this?


Solution

  • You have an infinite loop where you populate the br variable. If you read the machine.UART.readline() documentation you'll see that None is returned in the event of a timeout. You need to confirm that there is a value stored in the variable before you check the content.

    from machine import UART, Pin
    
    bt = UART(0,9600)
    
    L1 = Pin(2,Pin.OUT)
    L2 = Pin(3,Pin.OUT)
    
    while True:
    
        br = bt.readline()
    
        # Check for timeout
        if br is not None:
    
            if "ON1" in br:
                L1.value(0)
            elif "OFF1" in br:
                L1.value(1)
    
            elif "ON2" in br:
                L2.value(0)
            elif "OFF2" in br:
                L2.value(1)