close

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()
---------------------------------------------------------------
main.py
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()
This will allow to keep the structure of your application clear, as well as allow to install multiple applications on a board, and switch among them.
#---------------------------
很好用的指令,查看ESP8266的設定值
 
import port_diag
 

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:
#---------------------------

Wifi ap mode default password
 

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

  1.   import time
  2. import machine
  3. pwm = machine.PWM(machine.Pin(15))
  4. pwm.freq(60)
  5. while True:
  6.     for i in range(1024):
  7.         pwm.duty(i)
  8.         time.sleep(0.001)
  9.     for i in range(1023, -1, -1):
  10.         pwm.duty(i)
  11.         time.sleep(0.001)  

Micropython GPIO control

  1. from machine import Pin    #匯入 Pin 類別
  2. pin=Pin(2, Pin.OUT)          #定義 GPIO 2 為輸出腳
  3. import time                         #匯入時間模組
  4. while True:                         #無窮迴圈
  5.     pin.high()                        #點亮 LED
  6.     time.sleep(1.0)                #暫停 1 秒
  7.     pin.low()                         #熄滅 LED
  8.     time.sleep(1.0)                #暫停 1 秒

Micropython GPIO as Input control with switch bound problem

  1. import time   
  2. from machine import Pin
  3. swPin=Pin(0, Pin.IN, Pin.PULL_UP)
  4. ledPin=Pin(2, Pin.OUT)
  5. while True:
  6.     if not swPin.value():      #若按鈕被按下 (接地)
  7.         ledPin.value(not ledPin.value())     #反轉 LED 狀態
  8.         time.sleep_ms(300)                        #暫停 0.3 秒
  9.         while not swPin.value():                 #按鈕若還在按下狀態就在迴圈繞, 否則跳出去
  10.             pass
     

MicroPython: External interrupts

  1. import machine
  2. interruptCounter = 0
  3. totalInterruptsCounter = 0
  4. def callback(pin):
  5.   global interruptCounter
  6.   interruptCounter = interruptCounter+1
  7. p25 = machine.Pin(25, machine.Pin.IN, machine.Pin.PULL_UP)
  8. p25.irq(trigger=machine.Pin.IRQ_FALLING, handler=callback)
  9. while True:
  10.   if interruptCounter>0:
  11.     state = machine.disable_irq()
  12.     interruptCounter = interruptCounter-1
  13.     machine.enable_irq(state)
  14.     totalInterruptsCounter = totalInterruptsCounter+1
  15.     print("Interrupt has occurred: " + str(totalInterruptsCounter))

MicroPython: Timer interrupts

  1. import machine
  2. interruptCounter = 0
  3. totalInterruptsCounter = 0
  4. timer = machine.Timer(0
  5. def handleInterrupt(timer):
  6.   global interruptCounter
  7.   interruptCounter = interruptCounter+1
  8. timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=handleInterrupt)
  9. while True:
  10.   if interruptCounter>0:
  11.     state = machine.disable_irq()
  12.     interruptCounter = interruptCounter-1
  13.     machine.enable_irq(state)
  14.     totalInterruptsCounter = totalInterruptsCounter+1
  15.     print("Interrupt has occurred: " + str(totalInterruptsCounter))

 MicroPython: Creating a thread(1)

  1. import machine
  2. import _thread
  3. import time
  4. def testThread():
  5. while True:
  6.     print("Hello from thread")
  7.     time.sleep(2)
  8.  
  9. _thread.start_new_thread(testThread, ())

 MicroPython: Creating a thread(2)

  1. import _thread
  2. import time
  3.  
  4. def th_func(delay, id):
  5.     while True:
  6.         time.sleep(delay)
  7.         print('Running thread %d' % id)
  8.  
  9. for i in range(2):
  10.     _thread.start_new_thread(th_func, (i + 1, i))

MicroPython: Passing arguments to a thread function(3)

  1. import _thread
  2. def threadFunction(description, count):
  3.   print(description)
  4.   i = 0
  5.   while i < count:
  6.     print("Iteration: " + str(i) )
  7.     i=i+1
  8.  
  9. _thread.start_new_thread(threadFunction, ("Thread test function", 5))

MicroPython: : thread function with lock(4)

  1. import _thread
  2. import time
  3. lock=_thread.allocate_lock()
  4. def funcA(sec):
  5.   time.sleep(sec)
  6.   with lock:
  7.     print('Running thread A')
  8.   _thread.exit()
  9. def funcB(sec):
  10. time.sleep(sec)
  11.  with lock:
  12.    print('Running thread B')
  13.    print('Thread B sleep 5 seconds')
  14.    time.sleep(5)
  15.    print('thread B weakup')
  16.  _thread.exit()
  17. def funcC():
  18.    print('Running thread C')
  19.  _thread.exit()
  20.  
  21. _thread.start_new_thread(funcA, (2,))
  22. _thread.start_new_thread(funcB, (1,))
  23. _thread.start_new_thread(funcC, ())
  24. while True:
  25.    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)

  1. 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:
       pass

    Thread-1: 5582
    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)

  1. import _thread
    import time

    exitFlag = 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
    thread1.run()
    thread2.run()
    print ("Exiting Main Thread")

    Starting Thread-1
    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

  1. file = open ("initialFile.txt", "w")
  2. file.write("First Line \n")
  3. file.write("Second Line")
  4. file.close()
  5.  
  6. import os
  7. os.listdir()
  8.  
  9. file = open("initialFile.txt", "r")
  10. file.read()
  11. file.close()
  12.  

MicroPython: : Writing  a file

  1. file = open("myTestFile.txt", "w")
  2. print(type(file))
  3. file.write("Writing content from MicroPython")
  4. file.close()
  5.  

MicroPython: Running a script from the file system

  1. def echo(content):
  2.    print (content)
  3.  
  4. print("Running a script from the file system!")
  5. echo("Invoking a function")
  6.  
  7. import os
  8. os.listdir()
  9.  
  10. import script
  11. script.echo("Running the imported function")

MicroPython: String split method 

  1. myString = "one|two|three"
  2. print(myString.split("|",0))
  3. print(myString.split("|",1))
  4. print(myString.split("|",2))
  5. print(myString.split("|",3))

 

 

 

 

 

 

  1.  
arrow
arrow
    文章標籤
    MicroPython ESP8266
    全站熱搜

    stanley 發表在 痞客邦 留言(0) 人氣()