为了方便扩展,这次将程序设计为主程序和效果程序,上电时,ESP8266搜索磁盘,查找磁盘中所有的效果文件,并载入默认效果文件进行演示。
下面是主程序:
from machine import Pin, lightsleep, Timer, UART, reset
from time import sleep_ms
KEY_CNT_MAX = const(10)
print('\r\nLED start...')
Power = Pin(13, Pin.OPEN_DRAIN, value = 0)
Pin(2, Pin.IN)
import os, gc
from common import *
def init():
clear(np, (18, 0, 0))
sleep_ms(100)
clear(np, (0, 18, 0))
sleep_ms(100)
clear(np, (0, 0, 18))
sleep_ms(100)
clear(np, (5, 0, 0))
init()
fun_list = []
d = os.listdir('')
for i in range(len(d)):
if d[i].find('ef_') == 0:
fun_list.append(d[i].replace('.py', ''))
print(fun_list)
def poweroff():
print('power off!')
for i in range(8, 0, -1):
clear(np, i*30)
sleep_ms(20)
Power = Pin(13, Pin.OPEN_DRAIN, value = 1)
def rand(N = 128):
r = os.urandom(2)
return (r[0]*256 + r[1])%N
KEY1 = Pin(14, Pin.IN)
KEY2 = Pin(12, Pin.IN)
'''
KEY1_cnt KEY2_cnt return
0 0 0
0 1 1
0 2 2
1 0 16
1 1 17
2 0 32
2 2 34
'''
KEY_NONE = const(0)
KEY_PREV = const(1)
KEY_SAV1 = const(2)
KEY_NEXT = const(16)
KEY_RAND = const(17)
KEY_SAV2 = const(32)
KEY_POWEROFF = const(34)
KEY = 0
KEY_cnt = 0
KEY1_cnt = 0
KEY2_cnt = 0
KEYCODE = (KEY_PREV, KEY_NEXT, KEY_RAND, KEY_SAV1, KEY_SAV2, KEY_POWEROFF)
def tm_irq(t):
global KEY, KEY_cnt, KEY1_cnt, KEY2_cnt
if KEY_cnt > 0 and KEY_cnt <= KEY_CNT_MAX:
KEY_cnt += 1
if KEY_cnt > KEY_CNT_MAX:
KEY = KEY1_cnt * 16 + KEY2_cnt
KEY_cnt = 0
KEY1_cnt = 0
KEY2_cnt = 0
if KEY in KEYCODE:
UART(1).write(b'\x03')
tm = Timer(-1)
tm.init(period=100, mode=Timer.PERIODIC, callback=tm_irq)
def KEY1_irq(t):
global KEY_cnt, KEY1_cnt
if KEY_cnt == 0:
KEY_cnt = 1
if KEY_cnt <= KEY_CNT_MAX:
if KEY1_cnt < 3:
KEY1_cnt += 1
def KEY2_irq(t):
global KEY_cnt, KEY2_cnt
if KEY_cnt == 0:
KEY_cnt = 1
if KEY_cnt <= KEY_CNT_MAX:
if KEY2_cnt < 3:
KEY2_cnt += 1
KEY1.irq(trigger = Pin.IRQ_FALLING, handler = KEY1_irq)
KEY2.irq(trigger = Pin.IRQ_FALLING, handler = KEY2_irq)
def main():
global KEY, KEY_cnt
KEY_cnt = 0
n = 0
try:
f = open('last.fun', 'rb')
n = f.read(1)[0]
f.close()
print('load last saved function', n)
except:
n = 0
print('load defaut function')
while 1:
try:
if KEY == KEY_POWEROFF:
poweroff()
elif KEY == KEY_PREV:
n = (n + len(fun_list) - 1)%len(fun_list)
elif KEY == KEY_NEXT:
n = (n + 1)%len(fun_list)
elif KEY == KEY_RAND:
while 1:
nn = rand(len(fun_list))
if nn != n:
n = nn
break
elif KEY == KEY_SAV1 or KEY == KEY_SAV2:
print('save function', n)
f = open('last.fun', 'wb')
f.write(bytes([n]))
f.close()
print('run <'+fun_list[n]+'>')
exec('import '+fun_list[n])
exec(fun_list[n]+'.run()')
except KeyboardInterrupt:
try:
Pin(2, Pin.IN)
exec('del '+fun_list[n])
gc.collect()
sleep_ms(500)
print('continue')
except KeyboardInterrupt:
print('KeyboardInterrupt')
KEY_cnt = KEY_CNT_MAX + 1
Pin(2, Pin.IN)
break
except MemoryError:
clear((32, 0, 0))
print('memory error, free memory {}'.format(gc.mem_free()))
reset()
except Exception as e:
print('except {}'.format(e))
main()
|