Quick reference for the ESP8266
Micropython on ESP8266 Workshop Documentation (2017,3,28)
boot.py
>>> import os >>> os.listdir() ['boot.py', 'port_config.py']
# This file is executed on every boot (including wake-boot from deepsleep) import gc import webrepl webrepl.start() gc.collect()
FIile Content
>>> f = open('boot.py') >>> f.read() '# This file is executed on every boot (including wake-boot from deepsleep)\nimport gc\n#import webrepl\n#webrepl.start()\ngc.collect()\n'
Micropython ESP8266 Boot.py & Main.py Example
boot.py
# This file is executed on every boot (including wake-boot from deepsleep)
import
network
import
gc
import
webrepl
ap_if
=
network.WLAN(network.AP_IF)
sta_if
=
network.WLAN(network.STA_IF)
ap_if.active(
False
)
sta_if.active(
True
)
sta_if.connect(
'filewalker'
,
'mypasswd'
)
#import esp
#esp.osdebug(None)
webrepl.start()
gc.collect()
---------------------------------------------------------------
micropython-esp8266-scheduler.py
esp8266_relays.py
Boot process
Once the filesystem is mounted, boot.py
is executed from it. The standard version of this file is created during first-time module set up and has commands to start a WebREPL daemon (disabled by default, configurable with webrepl_setup
module), etc. This file is customizable by end users (for example, you may want to set some parameters or add other services which should be run on a module start-up). But keep in mind that incorrect modifications to boot.py may still lead to boot loops or lock ups, requiring to reflash a module from scratch. (In particular, it’s recommended that you use either webrepl_setup
module or manual editing to configure WebREPL, but not both).
As a final step of boot procedure, main.py
is executed from filesystem, if exists. 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
, and upload to module, 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()
MicroPython v1.9.1-8-g7213e78d on 2017-06-12; ESP module with ESP8266
Type "help()" for more information.
>>>
import port_diag
FlashROM:
Flash ID: 1640ef (Vendor: ef Device: 4016)
Flash bootloader data:
Byte @2: 02
Byte @3: 40 (Flash size: 4MB Flash freq: 40MHZ)
Firmware checksum:
size: 598416
md5: dae90ece36362127bce73f27cefe47fd
True
Networking:
STA ifconfig: ('192.168.1.105', '255.255.255.0', '192.168.1.1', '61.64.127.1')
AP ifconfig: ('192.168.4.1', '255.255.255.0', '192.168.4.1', '61.64.127.1')
Free WiFi driver buffers of type:
0: 8 (1,2 TX)
1: 0 (4 Mngmt TX(len: 0x41-0x100))
2: 8 (5 Mngmt TX (len: 0-0x40))
3: 4 (7)
4: 7 (8 RX)
lwIP PCBs:
Active PCB states:
Listen PCB states:
TIME-WAIT PCB states:
#---------------------------
After a fresh install and boot the device configures itself as a WiFi access point (AP) that you can connect to. The ESSID is of the form MicroPython-xxxxxx
where the x’s are replaced with part of the MAC address of your device (so will be the same everytime, and most likely different for all ESP8266 chips).
The password for the WiFi is micropythoN (note the upper-case N). Its IP address will be 192.168.4.1 once you connect to its network.
WiFi configuration will be discussed in more detail later in the tutorial.
Controlling relays using Micropython and an ESP8266
MicroPython http_server_simplistic.py example
http cleint & server
http://www.instructables.com/id/ESP8266-Light-Sensor/
#--------------------------------------------
Micropython PWM control
- import time
- import machine
- pwm = machine.PWM(machine.Pin(15))
- pwm.freq(60)
- while True:
- for i in range(1024):
- pwm.duty(i)
- time.sleep(0.001)
- for i in range(1023, -1, -1):
- pwm.duty(i)
- time.sleep(0.001)
Micropython GPIO control
- from machine import Pin #匯入 Pin 類別
- pin=Pin(2, Pin.OUT) #定義 GPIO 2 為輸出腳
- import time #匯入時間模組
- while True: #無窮迴圈
- pin.high() #點亮 LED
- time.sleep(1.0) #暫停 1 秒
- pin.low() #熄滅 LED
- time.sleep(1.0) #暫停 1 秒
Micropython GPIO as Input control with switch bound problem
- import time
- from machine import Pin
- swPin=Pin(0, Pin.IN, Pin.PULL_UP)
- ledPin=Pin(2, Pin.OUT)
- while True:
- if not swPin.value(): #若按鈕被按下 (接地)
- ledPin.value(not ledPin.value()) #反轉 LED 狀態
- time.sleep_ms(300) #暫停 0.3 秒
- while not swPin.value(): #按鈕若還在按下狀態就在迴圈繞, 否則跳出去
- pass
MicroPython: External interrupts
import
machine
interruptCounter
=
0
totalInterruptsCounter
=
0
def
callback(pin):
global
interruptCounter
interruptCounter
=
interruptCounter
+
1
p25
=
machine.Pin(
25
, machine.Pin.IN, machine.Pin.PULL_UP)
p25.irq(trigger
=
machine.Pin.IRQ_FALLING, handler
=
callback)
while
True
:
if
interruptCounter>
0
:
state
=
machine.disable_irq()
interruptCounter
=
interruptCounter
-
1
machine.enable_irq(state)
totalInterruptsCounter
=
totalInterruptsCounter
+
1
print
(
"Interrupt has occurred: "
+
str
(totalInterruptsCounter))
MicroPython: Timer interrupts
import
machine
interruptCounter
=
0
totalInterruptsCounter
=
0
timer
=
machine.Timer(
0
)
def
handleInterrupt(timer):
global
interruptCounter
interruptCounter
=
interruptCounter
+
1
timer.init(period
=
1000
, mode
=
machine.Timer.PERIODIC, callback
=
handleInterrupt)
while
True
:
if
interruptCounter>
0
:
state
=
machine.disable_irq()
interruptCounter
=
interruptCounter
-
1
machine.enable_irq(state)
totalInterruptsCounter
=
totalInterruptsCounter
+
1
print
(
"Interrupt has occurred: "
+
str
(totalInterruptsCounter))
MicroPython: Creating a thread(1)
import
machine
import
_thread
import
time
def
testThread():
while
True
:
print
(
"Hello from thread"
)
time.sleep(
2
)
_thread.start_new_thread(testThread, ())
MicroPython: Creating a thread(2)
import
_thread
import
time
- def th_func(delay, id):
- while True:
- time.sleep(delay)
- print('Running thread %d' % id)
- for i in range(2):
- _thread.start_new_thread(th_func, (i + 1, i))
MicroPython: Passing arguments to a thread function(3)
import
_thread
def
threadFunction(description, count):
print
(description)
i
=
0
while
i < count:
print
(
"Iteration: "
+
str
(i) )
i
=
i
+
1
_thread.start_new_thread(threadFunction, (
"Thread test function"
,
5
))
MicroPython: : thread function with lock(4)
import _thread
import time
lock=_thread.allocate_lock()
def funcA(sec):
time.sleep(sec)
with lock:
print('Running thread A')
_thread.exit()
def funcB(sec):
time.sleep(sec)
with lock:
print('Running thread B')
print('Thread B sleep 5 seconds')
time.sleep(5)
print('thread B weakup')
_thread.exit()
def funcC():
print('Running thread C')
_thread.exit()
_thread.start_new_thread(funcA, (2,))
_thread.start_new_thread(funcB, (1,))
_thread.start_new_thread(funcC, ())
while True:
pass
Expected results
1. A sleeps for 2 seconds
2. B sleeps for 1 second
3. Executes C in priority without any limitation
4. B wakes up and get the lock then sleep for 5 seconds
5. A wakes up and failed to get lock, blocked until B releases the lock
6. B sleeps for 5 seconds and releases the lock
7. Executes A
MicroPython: thread(5)
-
import _thread
import time# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.time() ))# Create two threads as follows
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")while 1:
Thread-1: 5582
pass
Thread-2: 5584
Thread-1: 5584
Thread-1: 5586
Thread-2: 5588
Thread-1: 5588
Thread-1: 5590
Thread-2: 5592
Thread-2: 5596
Thread-2: 5600
MicroPython: thread(6)
-
import _thread
import timeexitFlag = 0
class myThread ():
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.time()))
counter -= 1# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)# Start new Threads
Starting Thread-1
thread1.run()
thread2.run()
print ("Exiting Main Thread")
Thread-1: 7023
Thread-1: 7024
Thread-1: 7025
Thread-1: 7026
Thread-1: 7027
Exiting Thread-1
Starting Thread-2
Thread-2: 7029
Thread-2: 7031
Thread-2: 7033
Thread-2: 7035
Thread-2: 7037
Exiting Thread-2
Exiting Main Thread
MicroPython: : Reading a file
file
=
open
(
"initialFile.txt"
,
"w"
)
file
.write(
"First Line \n"
)
file
.write(
"Second Line"
)
file
.close()
import
os
os.listdir()
file
=
open
(
"initialFile.txt"
,
"r"
)
file
.read()
file
.close()
-
MicroPython: : Writing a file
file
=
open
(
"myTestFile.txt"
,
"w"
)
print
(
type
(
file
))
file
.write(
"Writing content from MicroPython"
)
file
.close()
-
MicroPython: Running a script from the file system
def
echo(content):
print
(content)
print
(
"Running a script from the file system!"
)
echo(
"Invoking a function"
)
import
os
- os.listdir()
import
script
script.echo(
"Running the imported function"
)
MicroPython: String split method
myString
=
"one|two|three"
print
(myString.split(
"|"
,
0
))
print
(myString.split(
"|"
,
1
))
print
(myString.split(
"|"
,
2
))
print
(myString.split(
"|"
,
3
))
留言列表