NodeMCU Config: Difference between revisions

From Network Security Wiki
Content added Content deleted
 
(32 intermediate revisions by the same user not shown)
Line 5: Line 5:
= Micropython =
= Micropython =


*Documentation:
== Basics ==
http://docs.micropython.org/en/latest/esp8266/quickref.html

== Installation ==
*Flashing Micropython
Download firmware file from [http://micropython.org/download#esp8266 micropython.org]


*Installing:
sudo pip install esptool
sudo pip install esptool
esptool.py --port /dev/ttyUSB0 erase_flash
esptool.py --port /dev/ttyUSB0 erase_flash
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 ~/Desktop/esp8266-20171101-v1.9.3.bin
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 ~/Desktop/esp8266-20171101-v1.9.3.bin


*Check the firmware integrity:
*Connecting via Terminal:
sudo apt install picocom
picocom /dev/ttyUSB0 -b115200


<syntaxhighlight lang="python">
*Connecting via REPL(web):
import webrepl_setup
import esp
esp.check_fw()
</syntaxhighlight>


== Console Access ==
If you disabled automatic start-up on boot, you may run configured daemon on demand using:
import webrepl
webrepl.start()


* Via Terminal:
*Checking filesystem:
sudo apt install picocom
import os
picocom /dev/ttyUSB0 -b115200
os.listdir()


Exiting from picocom:
*Create directories:
Cntrl + A
os.mkdir('dir')
Cntrl + X


* Via REPL(web):
*Remove Files:
os.remove('data.txt')


<syntaxhighlight lang="python">
*Writing Data to files:
import webrepl_setup
f = open('data.txt', 'w')
</syntaxhighlight>
f.write('some data')
f.close()


* If you disabled automatic start-up on boot, you may run configured daemon on demand using:
*Reading data:
f = open('data.txt')
f.read()
f.close()


<syntaxhighlight lang="python">
* Checking Machine Frequency & Overclocking:
import machine
import webrepl
webrepl.start()
machine.freq() # get the current frequency of the CPU
</syntaxhighlight>
machine.freq(160000000) # set the CPU frequency to 160 MHz

*Check AP Name:
import network;
ap = network.WLAN(network.AP_IF);
print(ap.config('essid'));

*Change AP name and password:
import network;
ap = network.WLAN(network.AP_IF);
ap.active(True);
ap.config(essid='MyESP8266', authmode=network.AUTH_WPA_WPA2_PSK, password='mypassword');
print(ap.config('essid'));

*Boot Process:
As a final step of boot procedure, ''main.py'' is executed from filesystem
This file is a hook to start up a user application each time on boot (instead of going to REPL).
For small test applications, you may name them directly as ''main.py''
but instead it’s recommended to keep your application(s) in separate files, and have just the following in main.py:

import my_app
my_app.main()


* Upload data using Serial Port
* Upload data using Serial Port
sudo pip install adafruit-ampy
sudo pip install adafruit-ampy
ampy --port /dev/ttyUSB0 put ~/Desktop/main.py
ampy --port /dev/ttyUSB0 put ~/Desktop/main.py
ampy --port /dev/ttyUSB0 ls


== Error Codes ==
* Check the firmware integrity:
import esp
esp.check_fw()


Error Code Details:
== Deep-sleep mode ==
https://github.com/micropython/micropython-lib/blob/master/errno/errno.py


== File System ==
*The deep-sleep mode will shut down the ESP8266 and all its peripherals, including the WiFi (but not including the real-time-clock, which is used to wake the chip).
*This drastically reduces current consumption and is a good way to make devices that can run for a while on a battery.


*Checking filesystem:
*To be able to use the deep-sleep feature you must connect GPIO16 to the reset pin.
*Then the following code can be used to sleep and wake the device:


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import machine
import os
os.listdir()
</syntaxhighlight>


*Create directories:
# configure RTC.ALARM0 to be able to wake the device
<syntaxhighlight lang="python">
rtc = machine.RTC()
os.mkdir('dir')
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
</syntaxhighlight>


*Remove Files:
# set RTC.ALARM0 to fire after 10 seconds (waking the device)
<syntaxhighlight lang="python">
rtc.alarm(rtc.ALARM0, 10000)
os.remove('data.txt')
</syntaxhighlight>


*Reading data:
# put the device to sleep
<syntaxhighlight lang="python">
machine.deepsleep()
f = open('data.txt')
f.read()
f.close()
</syntaxhighlight>
</syntaxhighlight>


*Writing Data to files:
*Note that when the chip wakes from a deep-sleep it is completely reset, including all of the memory.
*The boot scripts will run as usual and you can put code in them to check the reset cause to perhaps do something different if the device just woke from a deep-sleep.
*For example, to print the reset cause you can use:

<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
f = open('data.txt', 'w')
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
f.write('some data')
print('woke from a deep sleep')
f.close()
else:
print('power on or hard reset')
</syntaxhighlight>
</syntaxhighlight>


*Execute a script called foo.py
== Code Snipets ==
import foo


== Information ==
===Playing with GPIO===


*Checking Machine Frequency & Overclocking:
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import machine
import machine
machine.freq() # get the current frequency of the CPU
import time
machine.freq(160000000) # set the CPU frequency to 160 MHz
import urandom
</syntaxhighlight>


*Diagnostics
pin = machine.Pin(2, machine.Pin.OUT)
import port_diag


== Networking ==
def toggle(p):
p.value(not p.value())


=== AP Mode ===
while True:

time.sleep_ms(urandom.getrandbits(8))
*Check AP Name:
toggle(pin)
<syntaxhighlight lang="python">
import network
ap = network.WLAN(network.AP_IF)
print(ap.config('essid'))
</syntaxhighlight>
</syntaxhighlight>


*Change AP name and password:
<syntaxhighlight lang="python">
import network
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid='MyESP8266', authmode=network.AUTH_WPA_WPA2_PSK, password='mypassword') # Password should be min 8 char
print(ap.config('essid'))
</syntaxhighlight>


*Turning off AP:
===Fading an LED===
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
ap = network.WLAN(network.AP_IF)
import time, math
ap.active(False)
import machine
</syntaxhighlight>


=== Station Mode ===
led = machine.PWM(machine.Pin(2), freq=1000)


Connecting to WIFI AP:
def pulse(l, t):
sta_if = network.WLAN(network.STA_IF)
for i in range(20):
sta_if.active(True)
l.duty(int(math.sin(i / 10 * math.pi) * 500 + 500))
sta_if.connect('<your ESSID>', '<your password>')
time.sleep_ms(t)


To check if the connection is established:
while True:
sta_if.isconnected()
pulse(led, 20)
</syntaxhighlight>


Once established you can check the IP address:
sta_if.ifconfig()


You can then disable the access-point interface if you no longer need it:
=== Control a hobby servo ===
ap_if.active(False)


Disconnecting from Station:
Hobby servo motors can be controlled using PWM.
sta_if = network.WLAN(network.STA_IF)
They require a frequency of 50Hz and a duty between about 40 and 115, with 77 being the center value.
sta_if.active(False)

Here is a function you can run (or put in your boot.py file) to automatically connect to your WiFi network:


*Manual Movements
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
def do_connect():
servo = machine.PWM(machine.Pin(12), freq=50)
import network
servo.duty(40)
sta_if = network.WLAN(network.STA_IF)
servo.duty(115)
if not sta_if.isconnected():
servo.duty(77)
print('connecting to network...')
sta_if.active(True)
sta_if.connect('<essid>', '<password>')
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
</syntaxhighlight>
</syntaxhighlight>


== Boot Process ==
*Random movements:
#As a final step of boot procedure, ''main.py'' is executed from filesystem
#This file is a hook to start up a user application each time on boot (instead of going to REPL).
#For small test applications, you may name them directly as ''main.py''
#But instead it’s recommended to keep your application(s) in separate files, and have just the following in main.py:

<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import my_app
servo = machine.PWM(machine.Pin(12), freq=50)
my_app.main()
while True:
servo.duty(urandom.getrandbits(8))
time.sleep(1)
</syntaxhighlight>
</syntaxhighlight>


== boot.py File ==
=== One Wire DS18B20 Temp Sensor ===

<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# This file is executed on every boot (including wake-boot from deepsleep)
import time
import esp
import uos
import machine
import machine
import onewire, ds18x20
import gc
import webrepl
import network
import ntptime
#from machine import RTC
import micropython
import time


# the device is on GPIO12
dat = machine.Pin(12)


#esp.osdebug(None)
# create the onewire object
#uos.dupterm(None, 1) # disable REPL on UART(0)
ds = ds18x20.DS18X20(onewire.OneWire(dat))


webrepl.start()
# scan for devices on the bus
gc.collect()
roms = ds.scan()
print('found devices:', roms)


# loop 10 times and print all temperatures
for i in range(10):
print('temperatures:', end=' ')
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(ds.read_temp(rom), end=' ')
print()
</syntaxhighlight>


# Determine if waking from Deep Sleep
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print('Woke from a deep sleep')

# Machine Stats
print("Freq: ", machine.freq()/1000000, "MHz")
#print("ESP Flash size: ", esp.flash_size())
#print("ESP Free Mem: ", esp.freemem())
print("Free Mem: ", gc.mem_free()/1000,"KB")
#print("Micropython Info: ")
#micropython.mem_info()


# Flash Space stats
space = uos.statvfs('/')
total_space = (space[1] * space[3])/1000000
used_space = (space[2] * space[4])/1000000
free_space = total_space - used_space
print("Total:", total_space, "MB Used:", used_space,"MB Free:", free_space,"MB")


# WiFi Config
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True) # allow auto reconnect

if not sta_if.isconnected():
print('Connecting to WiFi...')
sta_if.active(True)
sta_if.connect('TP-Link_6A31', 'Kirat#291011')
while not sta_if.isconnected():
pass
print('STA Config: ', sta_if.config('essid'), sta_if.ifconfig())


# Wifi Access Point config
ap = network.WLAN(network.AP_IF)
ap.config(essid='MicroPythonAP', authmode=network.AUTH_WPA_WPA2_PSK, password='Admin@123') # Password should be min 8 char
#ap.active(False)
print('AP Config: ', ap.config('essid'), ap.ifconfig())


# synchronize with ntp need to be connected to wifi
rtc = machine.RTC()
try:
ntptime.settime() # set the rtc datetime from the remote server
print("Time: ", rtc.datetime()) # get the date and time in UTC
except OSError:
print("Time: Unable to get data from Server")


# Deep Sleep config
def deep_sleep(delta):
delay = delta*1000*60
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
rtc.alarm(rtc.ALARM0, delay)
print("Deep Sleep for: ", delta," min")
machine.deepsleep()


# Flash Onboard LED
def flash_led(n,x,y):
pin = machine.Pin(2, machine.Pin.OUT)
pin.on()
for i in range(n):
pin.off()
time.sleep(x)
pin.on()
time.sleep(y)
</syntaxhighlight>


<br />
<br />

Latest revision as of 15:30, 5 June 2020


Micropython

  • Documentation:
http://docs.micropython.org/en/latest/esp8266/quickref.html

Installation

  • Flashing Micropython

Download firmware file from micropython.org

sudo pip install esptool
esptool.py --port /dev/ttyUSB0 erase_flash
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 ~/Desktop/esp8266-20171101-v1.9.3.bin
  • Check the firmware integrity:
import esp
esp.check_fw()

Console Access

  • Via Terminal:
sudo apt install picocom
picocom /dev/ttyUSB0 -b115200

Exiting from picocom:

Cntrl + A 
Cntrl + X
  • Via REPL(web):
import webrepl_setup
  • If you disabled automatic start-up on boot, you may run configured daemon on demand using:
import webrepl
webrepl.start()
  • Upload data using Serial Port
sudo pip install adafruit-ampy
ampy --port /dev/ttyUSB0 put ~/Desktop/main.py
ampy --port /dev/ttyUSB0 ls

Error Codes

Error Code Details:

https://github.com/micropython/micropython-lib/blob/master/errno/errno.py

File System

  • Checking filesystem:
import os
os.listdir()
  • Create directories:
os.mkdir('dir')
  • Remove Files:
os.remove('data.txt')
  • Reading data:
f = open('data.txt')
f.read()
f.close()
  • Writing Data to files:
f = open('data.txt', 'w')
f.write('some data')
f.close()
  • Execute a script called foo.py
import foo

Information

  • Checking Machine Frequency & Overclocking:
import machine
machine.freq()                # get the current frequency of the CPU
machine.freq(160000000)       # set the CPU frequency to 160 MHz
  • Diagnostics
import port_diag

Networking

AP Mode

  • Check AP Name:
import network
ap = network.WLAN(network.AP_IF)
print(ap.config('essid'))
  • Change AP name and password:
import network
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid='MyESP8266', authmode=network.AUTH_WPA_WPA2_PSK, password='mypassword')    # Password should be min 8 char
print(ap.config('essid'))
  • Turning off AP:
ap = network.WLAN(network.AP_IF)
ap.active(False)

Station Mode

Connecting to WIFI AP:

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('<your ESSID>', '<your password>')

To check if the connection is established:

sta_if.isconnected()

Once established you can check the IP address:

sta_if.ifconfig()

You can then disable the access-point interface if you no longer need it:

ap_if.active(False)

Disconnecting from Station:

sta_if = network.WLAN(network.STA_IF)
sta_if.active(False)

Here is a function you can run (or put in your boot.py file) to automatically connect to your WiFi network:

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

Boot Process

  1. As a final step of boot procedure, main.py is executed from filesystem
  2. This file is a hook to start up a user application each time on boot (instead of going to REPL).
  3. For small test applications, you may name them directly as main.py
  4. But instead it’s recommended to keep your application(s) in separate files, and have just the following in main.py:
import my_app
my_app.main()

boot.py File

# This file is executed on every boot (including wake-boot from deepsleep)
import esp
import uos
import machine
import gc
import webrepl
import network
import ntptime
#from machine import RTC
import micropython
import time


#esp.osdebug(None)
#uos.dupterm(None, 1)    # disable REPL on UART(0)

webrepl.start()
gc.collect()


# Determine if waking from Deep Sleep    
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
    print('Woke from a deep sleep')

# Machine Stats
print("Freq: ", machine.freq()/1000000, "MHz")
#print("ESP Flash size: ", esp.flash_size())
#print("ESP Free Mem: ", esp.freemem())
print("Free Mem: ", gc.mem_free()/1000,"KB")
#print("Micropython Info: ") 
#micropython.mem_info()


# Flash Space stats
space = uos.statvfs('/')
total_space = (space[1] * space[3])/1000000
used_space = (space[2] * space[4])/1000000
free_space = total_space - used_space
print("Total:", total_space, "MB Used:", used_space,"MB Free:", free_space,"MB")


# WiFi Config
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True) # allow auto reconnect

if not sta_if.isconnected():
    print('Connecting to WiFi...')
    sta_if.active(True)
    sta_if.connect('TP-Link_6A31', 'Kirat#291011')
    while not sta_if.isconnected():
        pass
print('STA Config: ', sta_if.config('essid'), sta_if.ifconfig())


# Wifi Access Point config
ap = network.WLAN(network.AP_IF)
ap.config(essid='MicroPythonAP', authmode=network.AUTH_WPA_WPA2_PSK, password='Admin@123')   # Password should be min 8 char
#ap.active(False)
print('AP Config: ', ap.config('essid'), ap.ifconfig())


# synchronize with ntp need to be connected to wifi
rtc = machine.RTC()
try:
    ntptime.settime() # set the rtc datetime from the remote server
    print("Time: ", rtc.datetime())    # get the date and time in UTC
except OSError:
    print("Time: Unable to get data from Server")


# Deep Sleep config
def deep_sleep(delta):
    delay = delta*1000*60
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    rtc.alarm(rtc.ALARM0, delay)
    print("Deep Sleep for: ", delta," min")
    machine.deepsleep()


# Flash Onboard LED
def flash_led(n,x,y):
    pin = machine.Pin(2, machine.Pin.OUT)
    pin.on()
    for i in range(n):
        pin.off()
        time.sleep(x)
        pin.on()
        time.sleep(y)


References





{{#widget:DISQUS |id=networkm |uniqid=NodeMCU Config |url=https://aman.awiki.org/wiki/NodeMCU_Config }}