Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4146

MicroPython • Re: Will I be able to run this code on MicroPython?

$
0
0
I managed to find an old ESP32 in my box of bits.
I assume Micropython is pretty much the same across hardware.
It is when it comes to Python source code, only really differs in what device specific import modules are available and what they do. So code which uses 'requests', 'json', etc, should work the same no matter what board is used.

Taking it as a 'retrieve a web page, parse it, print the results' task that should work on anything, will likely only differ when it comes to connecting to the router and probably much the same in that.

In fact you should be able to prototype the code on a Pi or PC host which avoids using things MicroPython doesn't support. For example this code will run on a host and a Pico W -

Code:

import requestsimport sysimport timeif sys.platform == "rp2":  print("Pico W : Connecting to router")  import network  import secrets  wlan = network.WLAN(network.STA_IF)  wlan.active(True)  wlan.connect(secrets.SSID, secrets.PASSWORD)  while wlan.status() != 3:    print("  Waiting to connect ...")    time.sleep(1)  print("Connected")else:  print("Running on host")url = "http://ident.me"data = requests.get(url)print(data.text)data.close()

Code:

pi@Pi3B:~ $ python3 wifi_show_external_ip_address.pyRunning on hostXXX.XXX.4.212

Code:

pi@Pi3B:~/ $ mptool run wifi_show_external_ip_address.pyPico W : Conecting to router  Waiting to connect ...  Waiting to connect ...ConnectedXXX.XXX.4.212

Statistics: Posted by hippy — Fri Feb 09, 2024 1:01 pm



Viewing all articles
Browse latest Browse all 4146

Trending Articles