[SOLVED] Nonetype object isn’t iterable

Issue

This Content is from Stack Overflow. Question asked by HotDoge

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)


This Question was asked in StackOverflow by HotDoge and Answered by Dan Nagle It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?