Top.Mail.Ru

MicroPython Examples

Some code examples to get started with Iguana and master MicroPython

MicroPython Code Examples

Flashing LED

On ESP8266 (NodeMCU Devkit 1.0) and ESP32 (Devkit V1) blinking on-board LED.

import machine, time

led = machine.Pin(2, Pin.OUT)

while True:
  led.value(1)
  time.sleep(0.5)
  led.value(0)
  time.sleep(0.5)

Flashing LED at random interval

On ESP8266 (NodeMCU Devkit 1.0) and ESP32 (Devkit V1) the built-in LED blinks at random intervals.

from machine import Pin
from time import sleep
from urandom import getrandbits

led = Pin(2, Pin.OUT)

while True:
  t = getrandbits(2) / 10
  print(t)    
  led.value(not led.value())
  sleep(t)

Pulse Width Modulation (PWM)

On ESP8266 (NodeMCU Devkit 1.0) and ESP32 (Devkit V1) smoothly changes the brightness of the built-in LED.

from machine import Pin, PWM
from time import sleep

pwm = PWM(Pin(2))
pwm.freq(1000)

while True:
  for i in range (0, 1023, 50):
    pwm.duty(i)
    sleep(0.1)

  for i in range (1023, 0, -50):
    pwm.duty(i)
    sleep(0.1)

Hall Sensor

Reads and prints the value of the built-in sensor on the ESP32 to measure the magnitude of the magnetic field.

from esp32 import hall_sensor
from time import sleep

while True:
  h = hall_sensor()
  print(h)
  sleep(0.2)

WiFi Network Scanner

print("Scanning for WiFi networks, please wait...")
print("")

import network
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

mod = ['Open', 'WEP', 'WPA-PSK' 'WPA2-PSK4', 'WPA/WPA2-PSK']
for (ssid, bssid, channel, RSSI, authmode, hidden) in sta_if.scan():
  print("* {:s}".format(ssid))
  print("   - Auth: {} {}".format(mod[authmode], '(hidden)' if hidden else ''))
  print("   - Channel: {}".format(channel))
  print("   - RSSI: {}".format(RSSI))
  print("   - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
  print()