6

hi im having error with this code but it runs in python shell could any body help me

from machine import Pin
import time
import network
import urequests
p0 = Pin(0,Pin.OUT)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('ssid', 'pass')
response = urequests.get('http://jsonplaceholder.typicode.com/albums/1')
while True:
    ans = response.json()['userId']
    p0.value(1)
    time.sleep(1)
    p0.off()
    time.sleep(1)
    print('ok')

and this is the error:

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
  File "urequests.py", line 108, in get
  File "urequests.py", line 53, in request
OSError: -202
Mogi
  • 596
  • 1
  • 6
  • 18
Sam
  • 65
  • 1
  • 5
  • the only thing I found online about OSError is stuff related to SSL, just to make sure can you change http to https in the get request? – Mogi Sep 28 '20 at 08:22
  • 2
    `-202` [seems](https://forum.pycom.io/topic/4223/what-is-oserror-code-202) to be related to a failed `getaddrinfo()` call. – Klaus D. Sep 28 '20 at 08:23

1 Answers1

6

Your issue (my guess) is that you begin to urequest.get() without connected to WiFi. Create function that do wifi connection and call it

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('essid', 'password')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())

Explain: wlan.connect() is asynchronous function and you have to wait, while it connects to wifi and only then continue with urequest.get()

Lixas
  • 6,938
  • 2
  • 25
  • 42