python获取英文单词库

清洗文章获得单词库,生成域名

f = open("/home/peter/danci.txt")               # 返回一个文件对象
t = open("/home/peter/dan.txt","a")
line = f.readline()               # 调用文件的 readline()方法
while line:
    print(line)                   # 后面跟 ',' 将忽略换行符
#    print(line, end = " ")     # 在 Python 3 中使用
    line = f.readline() [0:-5]
    t.writelines(line+'\n')
f.close()  

ESP32-C3/S2 快速参考手册

通用控制

MicroPython 的串口交互调试(REPL)在 UART0 (GPIO21=TX, GPIO20=RX),波特率为:115200。 Tab按键补全功能对于找到每个对象的使用方法非常有用。 粘贴模式 (ctrl-E) 对需要复制比较多 的python代码到REPL是非常有用。

The machine module:

import machine

machine.freq()          # 获取CPU当前工作频率

machine.freq(240000000) # 设置CPU的工作频率为 240 MHz

The esp module:

import esp

esp.osdebug(None)       # 关闭原厂 O/S 调试信息

esp.osdebug(0)          # 将原厂 O/S 调试信息重定向到 UART(0) 输出

# flash交互的低级方法

esp.flash_size()

esp.flash_user_start()

esp.flash_erase(sector_no)

esp.flash_write(byte_offset, buffer)

esp.flash_read(byte_offset, buffer)

The esp32 module:

import esp32

esp32.hall_sensor()     # 读取内部霍尔传感器

esp32.raw_temperature() # 读取内部温度传感器,在MCU, 单位:华氏度F

esp32.ULP()             # 使用超低功耗协处理器(ULP

请注意ESP32内部温度读取数值会比实际要高,因为芯片工作时候回发热。 从睡眠状态唤醒后立即读取温度传感器可以最大限度地减少这种影响。

Networking

The network module:

import network

wlan = network.WLAN(network.STA_IF) # 创建 station 接口

wlan.active(True)       # 激活接口

wlan.scan()             # 扫描允许访问的SSID

wlan.isconnected()      # 检查创建的station是否连已经接到AP

wlan.connect(‘essid’, ‘password’) # 连接到指定ESSID网络

wlan.config(‘mac’)      # 获取接口的MAC地址

wlan.ifconfig()         # 获取接口的 IP/netmask(子网掩码)/gw(网关)/DNS 地址

ap = network.WLAN(network.AP_IF) # 创捷一个AP热点接口

ap.config(essid=’ESP-AP’) # 激活接口

ap.config(max_clients=10) # 设置热点允许连接数量

ap.active(True)         # 设置APESSID名称

连接到本地WIFI网络的函数参考:

def do_connect():

    import network

    wlan = network.WLAN(network.STA_IF)

    wlan.active(True)

    if not wlan.isconnected():

        print(‘connecting to network…’)

        wlan.connect(‘essid’, ‘password’)

        while not wlan.isconnected():

            pass

    print(‘network config:’, wlan.ifconfig())

一旦网络建立成功,你就可以通过 socket 模块创建和使用 TCP/UDP sockets 通讯, 以及通过 urequests 模块非常方便地发送 HTTP 请求。

延时和时间

Use the time module:

import time

time.sleep(1)           # 睡眠1

time.sleep_ms(500)      # 睡眠500毫秒

time.sleep_us(10)       # 睡眠10微妙

start = time.ticks_ms() # 获取毫秒计时器开始值

delta = time.ticks_diff(time.ticks_ms(), start) # 计算从开始到当前时间的差值

定时器

ESP32-C3拥有2个定时器。使用 machine.Timer 类通过设置timer ID号为 0-1

from machine import Timer

tim0 = Timer(0)

tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0))

tim1 = Timer(1)

tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))

该周期的单位为毫秒(ms)

Virtual timers are not currently supported on this port.

引脚和GPIO

使用 machine.Pin 模块:

from machine import Pin

p0 = Pin(0, Pin.OUT)    # 创建对象p0,对应GPIO0口输出

p0.on()                 # 设置引脚为 “on” (1)高电平

p0.off()                # 设置引脚为 “off” (0)低电平

p0.value(1)             # 设置引脚为 “on” (1)高电平

p2 = Pin(2, Pin.IN)     # 创建对象p2,对应GPIO2口输入

print(p2.value())       # 获取引脚输入值, 0(低电平)或者 1(高电平)

p4 = Pin(4, Pin.IN, Pin.PULL_UP) # 打开内部上拉电阻

p5 = Pin(5, Pin.OUT, value=1) # 初始化时候设置引脚的值为 1(高电平)

可以使用引脚排列如下 (包括首尾): 0-10, 18-21.分别对应ESP32-C3芯片的实际引脚编号。 请注意,用户使用自己其它的开发板有特定的引脚命名方式(例如:DO, D1, …)。 由于MicroPython致力于支持不同的开发板和模块,因此我们采用最原始简单具且有共同特征的引 脚命名方式。如果你使用自己的开发板,请参考其原理图。

注意:

  • 引脚21和20分别是串口交互(REPL)的TX和RX。
  • 引脚19和18分是USB的D+和D-。
  • 部分引脚的pull值可以设置为 Pin.PULL_HOLD 以降低深度睡眠时候的功耗。

UART (serial bus)

See machine.UART.

from machine import UART

uart1 = UART(1, baudrate=115200, tx=6, rx=7)

uart1.write(‘hello’)  # write 5 bytes

uart1.read(5)         # read up to 5 bytes

The ESP32-C3 has 2 hardware UARTs: UART0, UART1. They each have default GPIO assigned to them, however depending on your ESP32-C3 variant and board, these pins may conflict with embedded flash, onboard PSRAM or peripherals.

Any GPIO can be used for hardware UARTs using the GPIO matrix, so to avoid conflicts simply provide tx and rx pins when constructing. The default pins listed below.


UART0UART1
tx21任意IO
rx20任意IO

PWM (脉宽调制)

There’s a higher-level abstraction machine.Signal which can be used to invert a pin. Useful for illuminating active-low LEDs using on() or value(1).

PWM 能在所有可输出引脚上实现。基频的范围可以从 40Hz 到 40MHz 但需要权衡: 随着基频的 增加 占空分辨率 下降. 详情请参阅: LED Control . 现在占空比范围为 0-1023

Use the machine.PWM class:

from machine import Pin, PWM

pwm0 = PWM(Pin(0))      # 1个引脚中创建PWM对象

pwm0.freq()             # 获取当前频率

pwm0.freq(1000)         # 设置频率

pwm0.duty()             # 获取当前占空比

pwm0.duty(200)          # 设置占空比

pwm0.deinit()           # 关闭引脚的 PWM

pwm2 = PWM(Pin(2), freq=20000, duty=512) # 在同一语句下创建和配置 PWM

ADC (模数转换)

ADC功能在ESP32-C3引脚0-4上可用(ADC1的5个输入通道)。请注意,使用默认配置时,ADC引脚 上的输入电压必须介于0.0v和1.0v之间(任何高于1.0v的值都将读为4095)。如果需要增加测 量范围,需要配置衰减器。

Use the machine.ADC class:

from machine import ADC

adc = ADC(Pin(0))          # ADC引脚上创建ADC对象

adc.read()                  # 读取测量值, 0-4095 表示电压从 0.0v – 1.0v

adc.atten(ADC.ATTN_11DB)    # 设置 11dB 衰减输入 (测量电压大致从 0.0v – 3.6v)

adc.width(ADC.WIDTH_9BIT)   # 设置 9位精度输出 (返回值 0-511)

adc.read()                  # 获取重新配置后的测量值

ESP32-C3 特定的 ADC 类使用方法说明:

ADC.atten(attenuation)

该方法允许设置ADC输入的衰减量,以获取更大的电压测量范围,但是以精度为代价的。 (配置后相同的位数表示更宽的范围)。衰减选项如下:

  • ADC.ATTN_0DB: 0dB 衰减, 最大输入电压为 1.00v – 这是默认配置
  • ADC.ATTN_2_5DB: 2.5dB 衰减, 最大输入电压约为 1.34v
  • ADC.ATTN_6DB: 6dB 衰减, 最大输入电压约为 2.00v
  • ADC.ATTN_11DB: 11dB 衰减, 最大输入电压约为3v

Warning

尽管通过配置11dB衰减可以让测量电压到达3.6v,但由于ESP32-C3芯片的最大允许输入电压是3.6V, 因此输入接近3.6V的电压可能会导致IC烧坏!

ADC.width(width)

该方法允许设置ADC输入的位数精度。 选项如下:

  • ADC.WIDTH_9BIT: 9 bit data
  • ADC.WIDTH_10BIT: 10 bit data
  • ADC.WIDTH_11BIT: 11 bit data
  • ADC.WIDTH_12BIT: 12 bit data – 这是默认配置

软件SPI总线

EPS32内部有两个SPI驱动。其中1个是通过软件实现 (bit-banging),并允许配置到所有引脚, 通过 machine.SoftSPI 类模块配置:

from machine import Pin, SoftSPI

# 在给定的引脚上创建SoftSPI总线

# (极性)polarity是指 SCK 空闲时候的状态

# (相位)phase=0 表示SCK在第1个边沿开始取样,phase=1 表示在第2个边沿开始。

spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))

spi.init(baudrate=200000) # 设置频率

spi.read(10)            # MISO引脚读取10字节数据

spi.read(10, 0xff)      # MISO引脚读取10字节数据同时在MOSI输出0xff

buf = bytearray(50)     # 建立缓冲区

spi.readinto(buf)       # 读取数据并存放在缓冲区 (这里读取50个字节)

spi.readinto(buf, 0xff) # 读取数据并存放在缓冲区,同时在MOSI输出0xff

spi.write(b’12345′)     # MOSI引脚上写5字节数据

buf = bytearray(4)      # 建立缓冲区

spi.write_readinto(b’1234′, buf) # MOSI引脚上写数据并将MISO读取数据存放到缓冲区

spi.write_readinto(buf, buf) # MOSI引脚上写缓冲区的数据并将MISO读取数据存放到缓冲区

Warning

目前在创建软件SPI对象时,sck, mosi 和 miso 所有 的引脚 必须 定义。

硬件SPI总线

有两个硬件SPI通道允许更高速率传输(到达80MHz)。 也可以配置成任意引脚,但相关引脚要 符合输入输出的方向性,这可以参阅(see 引脚和GPIO口)内容。通过自定义引脚而非 默认引脚,会降低传输速度,上限为40MHz。以下是硬件SPI总线默认引脚:


HSPI (id=1)VSPI (id=2)
sck1418
mosi1323
miso1219

Hardware SPI is accessed via the machine.SPI class and has the same methods as software SPI above:

from machine import Pin, SPI

hspi = SPI(1, 10000000)

hspi = SPI(1, 10000000, sck=Pin(14), mosi=Pin(13), miso=Pin(12))

vspi = SPI(2, baudrate=80000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))

SoftI2C总线

I2C总线分软件和硬件对象,硬件可以定义0和1,通过配置可以在任意引脚上实现改功能, 详情请看 machine.SoftI2C 类模块:

from machine import Pin, SoftI2C

# 构建1I2C对象

i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000)

# 构建一个硬件 I2C 总线

i2c = I2C(0)

i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)

i2c.scan()              # 扫描从设备

i2c.readfrom(0x3a, 4)   # 从地址为0x3a的从机设备读取4字节数据

i2c.writeto(0x3a, ’12’) # 向地址为0x3a的从机设备写入数据“12”

buf = bytearray(10)     # 创建110字节缓冲区

i2c.writeto(0x3a, buf)  # 写入缓冲区数据到从机

Hardware I2C bus

There are two hardware I2C peripherals with identifiers 0 and 1. Any available output-capable pins can be used for SCL and SDA but the defaults are given below.


I2C(0)I2C(1)
scl1825
sda1926

The driver is accessed via the machine.I2C class and has the same methods as software I2C above:

from machine import Pin, I2C

i2c = I2C(0)

i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)

实时时钟(RTC)

See machine.RTC

from machine import RTC

rtc = RTC()

rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # 设置时间(年,月,日,星期,时,分,秒,微秒)

                                             # 其中星期使用0-6表示星期一至星期日。

rtc.datetime() # 获取当前日期和时间

WDT (Watchdog timer)

See machine.WDT.

from machine import WDT

# enable the WDT with a timeout of 5s (1s is the minimum)

wdt = WDT(timeout=5000)

wdt.feed()

深度睡眠模式

下面代码可以用来睡眠、唤醒和检测复位唤醒:

import machine

# 检测设备是否从深度睡眠中唤醒

if machine.reset_cause() == machine.DEEPSLEEP_RESET:

    print(‘woke from a deep sleep’)

# 使设备进入深度睡眠,时间10秒。

machine.deepsleep(10000)

注意事项:

  • 调用深度睡眠函数 deepsleep() 如果不提供参数(时间)的话可能会让设备无限期休眠。
  • 软件复位不能触发复位事件(reset cause)。
  • 可能会出现一些泄漏电流流经内部上下拉电阻,为了进一步降低功耗,可以关闭GPIO的上下拉电阻:
    p1 = Pin(4, Pin.IN, Pin.PULL_HOLD)



  • 退出深度睡眠后,有必要恢复GPIO原来的状态 (例如:原来是输出引脚)
    p1 = Pin(4, Pin.OUT, None)


RMT

The RMT is ESP32-specific and allows generation of accurate digital pulses with 12.5ns resolution. See esp32.RMT for details. Usage is:

import esp32

from machine import Pin

r = esp32.RMT(0, pin=Pin(18), clock_div=8)

r   # RMT(channel=0, pin=18, source_freq=80000000, clock_div=8)

# The channel resolution is 100ns (1/(source_freq/clock_div)).

r.write_pulses((1, 20, 2, 40), start=0) # Send 0 for 100ns, 1 for 2000ns, 0 for 200ns, 1 for 4000ns

单总线驱动(Onewire

单总线驱动允许通过软件在各个引脚上实现:

from machine import Pin

import onewire

ow = onewire.OneWire(Pin(12)) # 在引脚 GPIO12 创建单总线对象ow

ow.scan()               # 扫描设备,返回设备编号列表

ow.reset()              # 复位总线

ow.readbyte()           # 读取1字节

ow.writebyte(0x12)      # 写入1个字节(0x12

ow.write(‘123’)         # 写入多个字节(‘123’)

ow.select_rom(b’12345678′) # 根据ROM编号选择总线上的指定设备

下面是一个DS18B20设备的驱动函数:

import time, ds18x20

ds = ds18x20.DS18X20(ow)

roms = ds.scan()

ds.convert_temp()

time.sleep_ms(750)

for rom in roms:

    print(ds.read_temp(rom))

确保数据引脚连接了 4.7k 的上拉电阻。另外请注意每次采集温度都需要用到 convert_temp() 模块。

NeoPixel and APA106 driver

Use the neopixel and apa106 modules:

from machine import Pin

from neopixel import NeoPixel

pin = Pin(0, Pin.OUT)   # 设置引脚GPIO0来驱动 NeoPixels

np = NeoPixel(pin, 8)   # GPIO0上创建一个 NeoPixel对象,包含8个灯珠

np[0] = (255, 255, 255) # 设置第一个灯珠显示数据为白色

np.write()              # 写入数据

r, g, b = np[0]         # 获取第一个灯珠的颜色

The APA106 driver extends NeoPixel, but internally uses a different colour order:

from apa106 import APA106

ap = APA106(pin, 8)

r, g, b = ap[0]

APA102 (DotStar) uses a different driver as it has an additional clock pin.

低级别的 NeoPixel 驱动:

import esp

esp.neopixel_write(pin, grb_buf, is800khz)

Warning

默认情况下 NeoPixel 被配置成控制更常用的 800kHz 单元设备。用户可以通过使用替代的定时器 来说控制其他频率的设备 (通常是 400kHz)。 可以通过使用定时器 timing=0 当构建 NeoPixel 对象的时候。

DHT 驱动

DHT 温湿度驱动允许通过软件在各个引脚上实现:

import dht

import machine

d = dht.DHT11(machine.Pin(4))

d.measure()

d.temperature() # eg. 23 (°C)

d.humidity()    # eg. 41 (% RH)

d = dht.DHT22(machine.Pin(4))

d.measure()

d.temperature() # eg. 23.6 (°C)

d.humidity()    # eg. 41.3 (% RH)

WebREPL (Web浏览器交互提示)

WebREPL (通过WebSockets的REPL, 可以通过浏览器使用) 是ESP8266端口实验的功能。 可以从 https://github.com/micropython/webrepl 下载并打开html文件运行。 (在线托管版可以通过访问 http://micropython.org/webrepl)直接使用, 通过执行 以下命令进行配置:

import webrepl_setup

按照屏幕的提示操作。重启后,允许使用WebREPL。如果你禁用了开机自动启动WebREPL, 可以通过以下命令使用:

import webrepl

webrepl.start()

# 也可在在开始时候设置一个密码

webrepl.start(password=’mypass’)

这个 WebREPL 通过连接到ESP32-C3的AP使用,如果你的路由器配网络配置正确,这个功能 也可以通过STA方式使用,那意味着你可以同时上网和调试ESP32-C3。(如果遇到不可行的 特殊情况, 请先使用ESP32-C3 AP方式)。

除了终端/命令符的访问方式, WebREPL同时允许传输文件 (包含上传和下载)。Web客户端有相应的 功能按钮,也可以通过 webrepl_cli.py 模块上存储的命令行进行操作。

有关将文件传输到ESP32-C3其他支持的替代方法,请参阅MicroPython论坛

自动生成域名

最近想注册个好一点的域名,而且长度不能超过5个字母的短域名,否则不容易记,另外因.com的权威性,当然选择后缀com,但注册时发现好域名都已经被注册了,自己一个一个试挺麻烦的,写了一个python程序,很容易就随机生成了短域名,一般域名查询网站都不允许一次查询超过50个域名,那每次生成50个即可,上代码:

list1=[]
for i in range(97,123):
    list1.append(chr(i))
import random
for i in range(50):
	str1=''.join(random.choices(list1,k=5))
	print(f'{str1}')

改进版本

list1=[]
s=''
j=0
t=2
for i in range(97,123):
    list1.append(chr(i))
import random
for i in range(26**t):
    str1='tip'+''.join(random.choices(list1,k=t))
    s=str1+','+s
a = s.split(',')
b = list(set(a))
for str2 in b:
    j=j+1
    if j % 50 ==0:
        print('\n\n')
    if str2!='':
        print(str2)

优化版本(非随机抽取,这样可以防止部分域名丢失)

baseword=[];domain='';spliti=0
t=26;k=0
keystart='zero'
keyend=''
for i in range(97,123):
    baseword.append(chr(i))
for i in range(t):
    if k>0:
        for j in range(k):
            domain=domain+keystart+baseword[i]+baseword[j]+keyend+','
    elif k==0:
        domain=domain+keystart+baseword[i]+keyend+','
domainlist = domain.split(',')
print(len(domainlist))
for regdomain in domainlist:
    spliti=spliti+1
    if spliti % 50 ==0:
        print('')
    if regdomain!='':
        print(regdomain)

递进版本

import itertools
spliti=0
baseword=[]
domainlist=''
abc=0
keystart='pid'
for i in range(97,123):
    baseword.append(chr(i))
for item in itertools.product(keystart,baseword,baseword,baseword):
    spliti=spliti+1
    if spliti % 1000 ==0:
        abc=abc+1
    if item!='':
        with open(str(abc)+'.txt',mode='a',encoding='utf-8') as f:
            f.write(domainlist.join(item)+'\n')

更迭版本

import itertools
spliti=0
baseword=[]
domainlist=''
abc=0
keystart='way'
for i in range(97,123):
    baseword.append(chr(i))
for item in itertools.product(keystart[0],keystart[1],keystart[2],baseword,baseword):
    spliti=spliti+1
    if spliti % 1000 ==0:
        print('')
        abc=abc+1
    if item!='':
#        print(domainlist.join(item))
        with open(str(abc)+'.txt',mode='a',encoding='utf-8') as f:
            f.write(domainlist.join(item)+'\n')

跃升版本

from itertools import product
spliti=0
domainlist=''
filename=0
li=[]
'''
s=list(keystart)
print(len(keystart))
s.extend(keystart)
s0=(','.join(keystart))
'''
def getdomainword(key,nums,flag):
    baseword=[]
    a=list(key)
    for i in range(97,123):
        baseword.append(chr(i))
    if flag==0:
        for i in range(nums):
            a.append(baseword)
    elif flag==1:
        for i in range(nums):
            a.insert(i,baseword)
    return a
print('请输入域名关键词: ',end='')
domain=input()
print('请输入位数(穷举英文位数): ',end='')
numbs=int(input())
print('请输入关键词 "'+domain+'" 在域名中的位置("0"在头部,"1"在尾部): ',end='')
flag=int(input())
li=getdomainword(domain,numbs,flag)
for item in product(*li):
    spliti=spliti+1
    if spliti % 1000 ==0:
        print('')
        filename=filename+1
    if item!='':
        print(domainlist.join(item))
#        with open(str(filename)+'.txt',mode='a',encoding='utf-8') as f:
#            f.write(domainlist.join(item)+'\n')

下面是各个系统的可执行文件,直接下载解压执行即可

Mac OS

Windows(64Bit)

Linux(32Bit)

从英文名著中获取英文单词

#keyword.txt为英文名著txt文件
import re
#a='Beautiful, is; better*than\nugly'
file=open('keyword.txt','r')
a=file.read()
# 四个分隔符为:,  ;  *  \n
x= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'',a)
lista=list(set(x))
lista.sort(key=len)
for t in sorted(lista,key = len):
    print(t)
file.close()  #文件打开,使用完毕后需要关闭

改进版本

import re
file=open('69004.txt','r')
a=file.read()
listb = []
listc = []
# 分隔符为:,  ;  *  \n
x= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$',a)
file.close()  #文件打开,使用完毕后需要关闭
lista=list(set(x))
lista.sort(key=len)
lista.sort(key=str.lower)
for t in lista:
    listb.append(t.lower())
listc=sorted(set(listb))
for t in sorted(listc,key=len):
    print(t)

改进版本(去重/去数字/叠加关键词)

import re
file=open('69004.txt','r')
txt=file.read()
worda = []
wordb = []
word = []
# 分隔符为:,  ;  *  \n
pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]',txt)
file.close()  #文件打开,使用完毕后需要关闭
for t in pre_word:
    worda.append(t.lower())
wordb=sorted(set(worda))
for t in sorted(wordb,key=len):
    if not t.isdigit():   #判断非数字
        word.append(t)

for i in word:
    if len(i)<=3:
        print("nest"+i)

英文经典资料来源

https://gutenberg.org/

import re
file=open('words.txt','r')
txt=file.read()
worda = []
wordb = []
word = []
# 分隔符为:,  ;  *  \n
pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[',txt)
file.close()  #文件打开,使用完毕后需要关闭
for t in pre_word:
    worda.append(t.lower())
wordb=sorted(set(worda))
for t in sorted(wordb,key=len):
    if not t.isdigit():   #判断非数字
        word.append(t)

for i in word:
    if len(i)<=3:
        print("mix"+i)

读取链接文件

import re
from lxml import etree

html = etree.parse('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt',etree.HTMLParser())
result = etree.tostring(html)
#print(result.decode('utf-8'))
#file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
#txt=file.read()
txt = result.decode('utf-8')
worda = []
wordb = []
word = []
# 分隔符为:,  ;  *  \n
pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[',txt)
for t in pre_word:
    worda.append(t.lower())
wordb=sorted(set(worda))
for t in sorted(wordb,key=len):
    if not t.isdigit():   #判断非数字
        word.append(t)

for i in word:
    if len(i)<=3:
        print("mix"+i)

升级版本

import re
from lxml import etree

html = etree.parse('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt',etree.HTMLParser())
result = etree.tostring(html)
#print(result.decode('utf-8'))
#file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
#txt=file.read()
txt = result.decode('utf-8')
worda = []
wordb = []
word = []
# 分隔符为:,  ;  *  \n
pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt)
for t in pre_word:
    worda.append(t.lower())
wordb=sorted(set(worda))
for t in sorted(wordb,key=len):
    if not t.isdigit():   #判断非数字
        word.append(t)
print("请输入域名关键词:")
keyword=input()
print("输入关键词在组合单词的位置:1=关键字前置,2=关键字后置")
flag=input()

for i in word:
    if len(i)<=3:
        if flag=='1':
            print(keyword+i)
        elif flag=='2':
            print(i+keyword)
        else:
            pass

图形版本

from tkinter import *

def Mysel():
      dic = {0:'1',1:'2'}
      s = dic.get(var.get())
      return s

def run1():
    a = inp1.get()
    b = Mysel()

    import re
    from lxml import etree

    html = etree.parse('http://andoq.com/words.txt',etree.HTMLParser())
    result = etree.tostring(html)
    #print(result.decode('utf-8'))
    #file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
    #txt=file.read()
    txt1 = result.decode('utf-8')
    worda = []
    wordb = []
    word = []
    # 分隔符为:,  ;  *  \n
    pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt1)
    for t in pre_word:
        worda.append(t.lower())
    wordb=sorted(set(worda))
    for t in sorted(wordb,key=len):
        if not t.isdigit():   #判断非数字
            word.append(t)
            
    for i in word:
        if len(i)<=3:
            if b=='1':
                txt.insert(END, a+i+'\n')   # 追加显示运算结果
            elif b=='2':
                txt.insert(END, i+a+'\n')   # 追加显示运算结果
            else:
                pass

 
root = Tk()
root.geometry('400x800')
root.title('域名生成器')
 
var = IntVar()
rd1 = Radiobutton(root,text="前置",variable=var,value=0,command=Mysel)
rd1.place(relx=0.6, rely=0.02, relwidth=0.3, relheight=0.04)
 
rd2 = Radiobutton(root,text="后置",variable=var,value=1,command=Mysel)
rd2.place(relx=0.6, rely=0.06, relwidth=0.3, relheight=0.04)

lb1 = Label(root, text='请输入关键词')
lb1.place(relx=0.1, rely=0.01, relwidth=0.2, relheight=0.05)
inp1 = Entry(root)
inp1.place(relx=0.1, rely=0.05, relwidth=0.3, relheight=0.04)
#inp2 = Entry(root)
#inp2.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
 
# 方法-直接调用 run1()
btn1 = Button(root, text='生成域名', command=run1)
btn1.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04)

 
# 在窗体垂直自上而下位置60%处起,布局相对窗体高度40%高的文本框
txt = Text(root)
txt.place(rely=0.15, relheight=0.85)
 
root.mainloop()
from tkinter import *

def Mysel():
      dic = {0:'1',1:'2'}
      s = dic.get(var.get())
      return s

def run1():
    a = inp1.get()
    b = Mysel()

    import re
    from lxml import etree

    html = etree.parse('http://andoq.com/words.txt',etree.HTMLParser())
    result = etree.tostring(html)
    #print(result.decode('utf-8'))
    #file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
    #txt=file.read()
    txt1 = result.decode('utf-8')
    worda = []
    wordb = []
    word = []
    # 分隔符为:,  ;  *  \n
    pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt1)
    for t in pre_word:
        worda.append(t.lower())
    wordb=sorted(set(worda))
    for t in sorted(wordb,key=len):
        if not t.isdigit():   #判断非数字
            word.append(t)
            
    for i in word:
        if len(i)<=3:
            if b=='1':
                txt.insert(END, a+i+'\n')   # 追加显示运算结果
            elif b=='2':
                txt.insert(END, i+a+'\n')   # 追加显示运算结果
            else:
                pass

 
root = Tk()
root.geometry('400x800')
root.resizable(0,0)
root.title('域名生成器')
 
var = IntVar()
rd1 = Radiobutton(root,text="前置",variable=var,value=0,command=Mysel)
rd1.place(relx=0.6, rely=0.02, relwidth=0.3, relheight=0.04)
 
rd2 = Radiobutton(root,text="后置",variable=var,value=1,command=Mysel)
rd2.place(relx=0.6, rely=0.06, relwidth=0.3, relheight=0.04)

lb1 = Label(root, text='请输入关键词')
lb1.place(relx=0.1, rely=0.01, relwidth=0.2, relheight=0.05)
inp1 = Entry(root)
inp1.place(relx=0.1, rely=0.05, relwidth=0.3, relheight=0.04)
#inp2 = Entry(root)
#inp2.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
 
# 方法-直接调用 run1()
btn1 = Button(root, text='生成域名', command=run1)
btn1.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04)

 
# 在窗体垂直自上而下位置60%处起,布局相对窗体高度40%高的文本框
txt = Text(root)
txt.config(bg='#aad5df')
txt.place(rely=0.15, relheight=0.85)
 
root.mainloop()
from tkinter import *
import tkinter
from tkinter import ttk
num='1'
def Mysel():
      dic = {0:'1',1:'2'}
      s = dic.get(var.get())
      return s

def choose(event):
    global num
    # 选中事件
    num=format(combobox.get())


def run1():
    global num
    a = inp1.get()
    b = Mysel()

    import re
    from lxml import etree

    html = etree.parse('http://www.mixdiy.com/wp-content/uploads/2022/09/words.txt',etree.HTMLParser())
    result = etree.tostring(html)
    #print(result.decode('utf-8'))
    #file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
    #txt=file.read()
    txt1 = result.decode('utf-8')
    worda = []
    wordb = []
    word = []
    # 分隔符为:,  ;  *  \n
    pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt1)
    for t in pre_word:
        worda.append(t.lower())
    wordb=sorted(set(worda))
    for t in sorted(wordb,key=len):
        if not t.isdigit():   #判断非数字
            word.append(t)
    txt.delete('1.0','end')
    for i in word:
        if len(i)<=int(num):
            if b=='1':
                txt.insert(END, a+i+'\n')   # 追加显示运算结果
            elif b=='2':
                txt.insert(END, i+a+'\n')   # 追加显示运算结果
            else:
                pass

 
root = Tk()
root.geometry('400x800+120+120')
root.resizable(0,0)
root.title('域名生成器')
scroll = tkinter.Scrollbar()



value = StringVar()
value.set("1")
values = ["0", "1", "2", "3", "4", "5", "6"]
combobox = ttk.Combobox(
    master=root, # 父容器
    height=50, # 高度,下拉显示的条目数量
    width=20, # 宽度
    state="readonly", # 设置状态 normal(可选可输入)、readonly(只可选)、 disabled
    cursor="arrow", # 鼠标移动时样式 arrow, circle, cross, plus...
    font=("", 10), # 字体
    textvariable=value, # 通过StringVar设置可改变的值
    values=values, # 设置下拉框的选项
    )
print(combobox.keys()) # 可以5查看支持的参数
combobox.place(relx=0.55, rely=0.03, relwidth=0.15, relheight=0.02)
combobox.bind("<<ComboboxSelected>>", choose)


var = IntVar()
rd1 = Radiobutton(root,text="前置",variable=var,value=0,command=Mysel)
rd1.place(relx=0.75, rely=0.02, relwidth=0.3, relheight=0.04)
 
rd2 = Radiobutton(root,text="后置",variable=var,value=1,command=Mysel)
rd2.place(relx=0.75, rely=0.06, relwidth=0.3, relheight=0.04)

lb1 = Label(root, text='请输入关键词')
lb1.place(relx=0.1, rely=0.01, relwidth=0.2, relheight=0.05)
inp1 = Entry(root)
inp1.place(relx=0.1, rely=0.05, relwidth=0.3, relheight=0.04)
#inp2 = Entry(root)
#inp2.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
 
# 方法-直接调用 run1()
btn1 = Button(root, text='生成域名', command=run1)
btn1.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04)

scroll.place(relx=0.95, rely=0.15, relheight=0.85, relwidth=0.05) 
# 在窗体垂直自上而下位置60%处起,布局相对窗体高度40%高的文本框
txt = Text(root)
scroll.config(command=txt.yview)
txt.config(bg='#aad5df')
txt.config(yscrollcommand=scroll.set)
txt.place(relx=0, rely=0.15, relheight=0.85 ,relwidth=0.95)
 
root.mainloop()
from tkinter import *
import tkinter
from tkinter import ttk
num='1'
def Mysel():
      dic = {0:'1',1:'2'}
      s = dic.get(var.get())
      return s

def choose(event):
    global num
    # 选中事件
    num=format(combobox.get())

def run1():
    global num
    a = inp1.get()
    b = Mysel()

    import re
    from lxml import etree

    html = etree.parse('http://www.mixdiy.com/wp-content/uploads/2022/09/words.txt',etree.HTMLParser())
    result = etree.tostring(html)
    #print(result.decode('utf-8'))
    #file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
    #txt=file.read()
    txt1 = result.decode('utf-8')
    worda = []
    wordb = []
    word = []
    # 分隔符为:,  ;  *  \n
    pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt1)
    for t in pre_word:
        worda.append(t.lower())
    wordb=sorted(set(worda))
    for t in sorted(wordb,key=len):
        if not t.isdigit():   #判断非数字
            word.append(t)
    txt.delete('1.0','end')
    for i in word:
        if len(i)<=int(num):
            if b=='1':
                txt.insert(END, a+i+'\n')   # 追加显示运算结果
            elif b=='2':
                txt.insert(END, i+a+'\n')   # 追加显示运算结果
            else:
                pass

root = Tk()
root.geometry('400x800+120+120')
root.resizable(0,0)
root.title('域名生成器')
scroll = tkinter.Scrollbar()

value = StringVar()
value.set("1")
values = ["0", "1", "2", "3", "4", "5", "6"]
combobox = ttk.Combobox(
    master=root, # 父容器
    height=50, # 高度,下拉显示的条目数量
    width=20, # 宽度
    state="readonly", # 设置状态 normal(可选可输入)、readonly(只可选)、 disabled
    cursor="arrow", # 鼠标移动时样式 arrow, circle, cross, plus...
    font=("", 12), # 字体
    textvariable=value, # 通过StringVar设置可改变的值
    values=values, # 设置下拉框的选项
    )
#print(combobox.keys()) # 可以5查看支持的参数
combobox.place(relx=0.57, rely=0.052, relwidth=0.15, relheight=0.025)
combobox.bind("<<ComboboxSelected>>", choose)

var = IntVar()
rd1 = Radiobutton(root,text="前置",variable=var,value=0,command=Mysel)
rd1.place(relx=0.75, rely=0.02, relwidth=0.3, relheight=0.04)
 
rd2 = Radiobutton(root,text="后置",variable=var,value=1,command=Mysel)
rd2.place(relx=0.75, rely=0.06, relwidth=0.3, relheight=0.04)

lb1 = Label(root, text='域名主关键词')
lb1.place(relx=0.1, rely=0.01, relwidth=0.2, relheight=0.05)

lb1 = Label(root, text='匹配单词字母个数')
lb1.place(relx=0.4, rely=0.02, relwidth=0.4, relheight=0.03)

inp1 = Entry(root)
inp1.place(relx=0.1, rely=0.05, relwidth=0.3, relheight=0.03)
#inp2 = Entry(root)
#inp2.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
 
# 方法-直接调用 run1()
btn1 = Button(root, text='生成域名', command=run1)
btn1.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04)

scroll.place(relx=0.95, rely=0.15, relheight=0.85, relwidth=0.05) 
# 在窗体垂直自上而下位置60%处起,布局相对窗体高度40%高的文本框
txt = Text(root)
scroll.config(command=txt.yview)
txt.config(bg='#aad5df')
txt.config(yscrollcommand=scroll.set)
txt.place(relx=0, rely=0.15, relheight=0.85 ,relwidth=0.95)
 
root.mainloop()
from tkinter import *
import tkinter
from tkinter import ttk
num='1'
domaintogal=0
def Mysel():
      dic = {0:'1',1:'2'}
      s = dic.get(var.get())
      return s

def choose(event):
    global num
    # 选中事件
    num=format(combobox.get())

def run1():
    global num,domaintogal
    a = inp1.get()
    b = Mysel()
    j = 0
    import re
    from lxml import etree

    html = etree.parse('http://www.mixdiy.com/wp-content/uploads/2022/09/words.txt',etree.HTMLParser())
    result = etree.tostring(html)
    #print(result.decode('utf-8'))
    #file=open('http://xn--ogtw0vdov42a.xn--fiqs8s/words.txt','r')
    #txt=file.read()
    txt1 = result.decode('utf-8')
    worda = []
    wordb = []
    word = []
    # 分隔符为:,  ;  *  \n
    pre_word= re.split(' |,|; |\!|\?|\_|\:|\-|\.|\*|\n|\'|\"|\‘|\/|\”|\“|\%|\’|\(|\)|\$|\&|\]|\—|\;|\#|\[|\<|\>',txt1)
    for t in pre_word:
        worda.append(t.lower())
    wordb=sorted(set(worda))
    for t in sorted(wordb,key=len):
        if not t.isdigit():   #判断非数字
            word.append(t)
    txt.delete('1.0','end')
    for i in word:
        j=j+1
        if len(i)<=int(num):
            if j % 1000 ==0:
                txt.insert(END, '-----------------------------------\n')
            if b=='1':
                txt.insert(END, a+i+'\n')   # 追加显示运算结果
            elif b=='2':
                txt.insert(END, i+a+'\n')   # 追加显示运算结果
            else:
                pass
    domaintogal=int(txt.index('end-1c').split('.')[0])-1
    lb3 = Label(root, text='生成的域名总数: '+str(domaintogal))
    print(domaintogal)
    lb3.place(relx=0.4, rely=0.1, relwidth=0.4, relheight=0.03)
    
root = Tk()
root.geometry('400x800+120+120')
root.resizable(0,0)
root.title('域名生成器')
scroll = tkinter.Scrollbar()

value = StringVar()
value.set("1")
values = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
combobox = ttk.Combobox(
    master=root, # 父容器
    height=50, # 高度,下拉显示的条目数量
    width=20, # 宽度
    state="readonly", # 设置状态 normal(可选可输入)、readonly(只可选)、 disabled
    cursor="arrow", # 鼠标移动时样式 arrow, circle, cross, plus...
    font=("", 12), # 字体
    textvariable=value, # 通过StringVar设置可改变的值
    values=values, # 设置下拉框的选项
    )
#print(combobox.keys()) # 可以5查看支持的参数
combobox.place(relx=0.57, rely=0.052, relwidth=0.15, relheight=0.025)
combobox.bind("<<ComboboxSelected>>", choose)

var = IntVar()
rd1 = Radiobutton(root,text="前置",variable=var,value=0,command=Mysel)
rd1.place(relx=0.75, rely=0.02, relwidth=0.3, relheight=0.04)
 
rd2 = Radiobutton(root,text="后置",variable=var,value=1,command=Mysel)
rd2.place(relx=0.75, rely=0.06, relwidth=0.3, relheight=0.04)

lb1 = Label(root, text='域名主关键词')
lb1.place(relx=0.1, rely=0.01, relwidth=0.2, relheight=0.05)

lb2 = Label(root, text='匹配单词字母个数')
lb2.place(relx=0.4, rely=0.02, relwidth=0.4, relheight=0.03)

lb3 = Label(root, text='生成的域名总数')
lb3.place(relx=0.4, rely=0.1, relwidth=0.4, relheight=0.03)

inp1 = Entry(root)
inp1.place(relx=0.1, rely=0.05, relwidth=0.3, relheight=0.03)
#inp2 = Entry(root)
#inp2.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
 
# 方法-直接调用 run1()
btn1 = Button(root, text='生成域名', command=run1)
btn1.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.03)

scroll.place(relx=0.95, rely=0.15, relheight=0.85, relwidth=0.05) 
# 在窗体垂直自上而下位置60%处起,布局相对窗体高度40%高的文本框
txt = Text(root)
scroll.config(command=txt.yview)
txt.config(bg='black',selectbackground='red',foreground = 'white')
txt.config(yscrollcommand=scroll.set)
txt.place(relx=0, rely=0.15, relheight=0.85 ,relwidth=0.95)

root.mainloop()

ESP32-C3串口通信定时开关机延时摄影

esp32-c3系列因其低廉的价格颇具竞争力,某宝买了个9.9的esp32-c3开发板,用micropython开发uart通信,一开始接上电路板丝印的RX、TX引脚,但一直未能通信甚至干扰了调试,咨询厂家,因C3系列较新,厂家FAE也不熟悉micropython,翻看micropython官网等也找不到相关资料,给调试工作带来很大麻烦。这里提供一个简单的方法找出uart引脚,也就一行代码:

esp32-c3开发板正面
esp32-c3开发板背面
注意点一:
uart = machine.UART(1, baudrate=115200,timeout=10)
print(uart)
#此时可以看到rx=10,tx=9,但如果将树莓派的tx、rx分别接esp32C3的引脚10和9,则不会有任何信息,这是最大的坑,此时需将上述代码更新为
uart = machine.UART(1, baudrate=115200,rx=10,tx=9,timeout=10)
这样就没有任何问题了
注意点二:
上位机程序的timeout数值一定要大于等于下位机time.sleep的时间

全部代码如下:

import ntptime
import network,time
import machine
from machine import Pin,RTC
rtc = RTC()
#print("同步前本地时间:%s" %str(time.localtime()))
led=Pin(2,Pin.OUT)
# 联WIFI
def WIFI_Connect():
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('HUAWEI', 'china') #输入WIFI账号密码
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break
    if wlan.isconnected():
        print('connected!')
        print('network information:', wlan.ifconfig())
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led.value(0)
            time.sleep(0.1)
         print('同步失败')
uart = machine.UART(1, baudrate=115200,rx=10,tx=9,timeout=10)
#uart = machine.UART(1, baudrate=115200, timeout=10)
p22 = Pin(6, Pin.OUT)
readmsg = ''
sendmsg = '1'
WIFI_Connect()
while True:
    sync_ntp()
    dt=time.localtime()
    print(uart)
    time.sleep(20)
    if uart.any() > 0:
        readmsg = uart.read()
        print(readmsg)
        if '2' in readmsg:
            uart.write(sendmsg)
            if dt[3]>=20:
                print('power off')
                p22.on()
                time.sleep(0.5)
                p22.off()
        else:
            print(readmsg)
            print('reset now')
            p22.on()
            time.sleep(0.5)
            p22.off()
    elif uart.any()==0:                             #多次读取,防止有信息丢失导致误判
        print(dt[3])
        if dt[3]>=0 and dt[3]<20:      #如白天读不到信息则开机
            print('power on')
            p22.on()
            time.sleep(0.5)
            p22.off()

改进版本(自动根据上位机发送的串口信息生成包含wifi及开关机时间等信息的配置文件,避免了在烧录程序时写死wifi密码等信息)

import ntptime
import network,time
import machine
from machine import Pin,RTC
uart = machine.UART(1, baudrate=115200,rx=10,tx=9,timeout=10)
readmsg = ''
sendmsg = 'huanghe'
rtc = RTC()
#print("同步前本地时间:%s" %str(time.localtime()))
led=Pin(2,Pin.OUT)
# 联WIFI
def WIFI_Connect():
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid[1])
        wlan.connect(ssid[1], pwd[1]) #输入WIFI账号密码
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break
    if wlan.isconnected():
        print('connected!')
        print('network information:', wlan.ifconfig())
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led.value(0)
            time.sleep(0.1)
         print('同步失败')
#uart = machine.UART(1, baudrate=115200, timeout=10)
p22 = Pin(6, Pin.OUT)
try:
    with open('config.txt',mode='r',encoding='utf-8') as f:
        s=f.read().split(',')
        ssid=s[0].split(':')
        pwd=s[1].split(':')
        startt=s[2].split(':')
        endt=s[3].split(':')
        print(startt[1])
        print(endt[1])
except:
    print('config file error')
    time.sleep(5)   #必不可少,并且时间不能小于上位机发送定时
    if uart.any() > 0:
        readmsg = uart.read()
        print(readmsg)
        if 'SSID' in readmsg:
            content = readmsg
            with open('config.txt',mode='w',encoding='utf-8') as f:
                f.write(content)
            machine.reset()
try:
    WIFI_Connect()
except:
    print('wifi connect error')
while True:
    sync_ntp()
    dt=time.localtime()
    print(uart)
    time.sleep(20)
    if uart.any() > 0:
        readmsg = uart.read()
        print(readmsg)
        if 'changjiang' in readmsg:
            uart.write(sendmsg)
            print('dt[3]='+str(dt[3]))
            print('endt[1]='+endt[1])
            if dt[3]>=int(endt[1]):
                print('power off')
                p22.on()
                time.sleep(0.5)
                p22.off()
        else:
            print(readmsg)
            print('reset now')
            p22.on()
            time.sleep(0.5)
            p22.off()
    elif uart.any()==0:                             #多次读取,防止有信息丢失导致误判
        print(dt[3])
        if dt[3]>=int(startt[1]) and dt[3]<int(endt[1]):      #如白天读不到信息则开机
            print('power on')
            p22.on()
            time.sleep(0.5)
            p22.off()

去错版本

#coding:utf-8
import ntptime
import network,time
import machine
import os
from machine import Pin,RTC
uart = machine.UART(1, baudrate=115200,rx=10,tx=9,timeout=10)
readmsg = ''
sendmsg = 'huanghe'
startt=6
endt=20
rtc = RTC()
#print("同步前本地时间:%s" %str(time.localtime()))
led=Pin(2,Pin.OUT)
# 联WIFI
def WIFI_Connect():
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid[1])
        wlan.connect(ssid[1], pwd[1]) #输入WIFI账号密码
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break
    if wlan.isconnected():
        print('connected!')
        print('network information:', wlan.ifconfig())
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led.value(0)
            time.sleep(0.1)
         print('同步失败')
#uart = machine.UART(1, baudrate=115200, timeout=10)
p22 = Pin(6, Pin.OUT)
try:
    with open('config.txt',mode='r',encoding='utf-8') as f:
        s=f.read().split(',')
        if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in s:
            ssid=s[0].split(':')
            pwd=s[1].split(':')
            startt=s[2].split(':')
            endt=s[3].split(':')
            startta=startt[1]
            endta=endt[1]
            print(startta)
            print(endta)
        else:
            print('file format error,will drop it')
            os.remove('config.txt')
except:
    print('config file not find')
    startta=6
    endta=20
    time.sleep(5)   #必不可少,并且时间不能小于上位机发送定时
    if uart.any() > 26:  #接受字符串个数
        readmsg = uart.read()
        print(readmsg)
        if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in str(readmsg):
            content = readmsg
            with open('config.txt',mode='w',encoding='utf-8') as f:
#                f.seek(0)
                f.write(content)
            machine.reset()
        else:
            try:
                os.remove('config.txt')
            except:
                print('未找到待删除文件')
try:
    WIFI_Connect()
except:
    print('wifi connect error')
while True:
    sync_ntp()
    dt=time.localtime()
    readmsg = uart.read()
    print(uart)
    time.sleep(20)
    if uart.any() > 0:
        readmsg = uart.read()
        print(readmsg)
        if 'changjiang' in readmsg:
            uart.write(sendmsg)
            print('dt[3]='+str(dt[3]))
            print('endt[1]='+str(endta))
            if dt[3]>=int(endta):
                print('power off')
                p22.on()
                time.sleep(0.5)
                p22.off()
        else:
            print(readmsg)
            print('reset now')
            p22.on()
            time.sleep(0.5)
            p22.off()
    elif uart.any()==0:                             #多次读取,防止有信息丢失导致误判
        print(dt[3])
        if dt[3]>=int(startta) and dt[3]<int(endta):      #如白天读不到信息则开机
            print('power on')
            p22.on()
            time.sleep(0.5)
            p22.off()

对应上位机程序

import serial #导入模块
with open('/home/pi/config.txt',mode='r',encoding='utf-8') as f:
    s=f.read()
#端口,GNU/Linux上的/dev/ttyUSB0 等或Windows上的 COM3 等
portx="/dev/ttyAMA0"
#波特率,标准值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
bps=115200
#超时设置,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)
timex=5
# 打开串口,并得到串口对象
ser=serial.Serial(portx,bps,timeout=timex)
while True:
    # 写数据
    send=s
    result=ser.write(send.encode())
    print("写总字节数:",result)
    str1 =ser.readline().decode()
    if('huanghe' in str1):
        print(str1)
ser.close()#关闭串口

更新版本

ESP32-C3侧

#coding:utf-8
from machine import UART,Pin,RTC
import machine
import time,network
import ntptime
led=Pin(2,Pin.OUT)
rtc = RTC()
def linedetect():
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=5)
    idsend='huanghe'
    idreceive='changjiang'
    uart.write(idsend)
    time.sleep(15)      #树莓派启动需要的时间,否则会反复重启
    receive_data=uart.readline()
    if (idreceive in str(receive_data)):
        return 1
    else:
        return 0
def onoff(pinnum):
    p = Pin(pinnum, Pin.OUT)
    p.on()
    time.sleep(0.5)
    p.off()
def createconfigfile(filename):
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=5)
    time.sleep(5)
    readmsg = uart.readline()
    if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in str(readmsg):
        content = readmsg
        with open(filename,mode='w',encoding='utf-8') as f:
            f.write(content)
def readconfigfile(filename):
    with open(filename,mode='r',encoding='utf-8') as f:
        s=f.read().split(',')
        if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in s:
            ssid=s[0].split(':')[1]
            pwd=s[1].split(':')[1]
            startt=s[2].split(':')[1]
            endt=s[3].split(':')[1]
            return ssid,pwd,startt,endt
        else:
            print('file format error,will drop it')
            os.remove(filename)
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led.value(0)
            time.sleep(0.1)
         print('同步失败')
# 联WIFI
def WIFI_Connect(ssid,pwd):
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid)
        wlan.connect(ssid, pwd) #输入WIFI账号密码
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break
    if wlan.isconnected():
        print('connected!')
try:
    a,b,c,d=readconfigfile('config.txt')
except:
    print('error')
    createconfigfile('config.txt')
    machine.reset()
WIFI_Connect(a,b)
sync_ntp()
print(a,b,c,d)
while True:
    dt=time.localtime()
    print(dt)
    linestate=linedetect()
    if linestate!=0:
        print('on line')
        if dt[3]>int(d):
            onoff(4)
    else:
        print('off line')
        if (dt[3]<=int(d) and dt[3]>int(c)):
            onoff(4)
'''
while True:
    a=linedetect()
    if a==0:
        print('off line')
    else:
        print('on line')
'''

树莓派侧

import serial
i=0
with open('/home/pi/config.txt',mode='r',encoding='utf-8') as f:
   s=f.read()
Port = '/dev/ttyAMA0'
ser = serial.Serial(Port,115200,timeout=15)
while True:
   send=s
   ser.write(send.encode('utf-8'))
   str1=ser.read(7).decode('utf-8')
   if ('huanghe' in str(str1)):
      print(str1+' '+str(i))
   else:
      print('get info is '+str(str1))
ser.close

注:uart连接一定要接地,否则会报错

开关机时间调整

#coding:utf-8
from machine import UART,Pin,RTC
import machine
import time,network
import ntptime
import os
led1=Pin(12,Pin.OUT)
led2=Pin(13,Pin.OUT)
rtc = RTC()
k=0
def linedetect():
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)  #设置Pin6=tx,Pin7=rx
    idsend='huanghe'
    idreceive='changjiang'
    uart.write(idsend)
    time.sleep(5)      #树莓派启动需要的时间,否则会反复重启
    receive_data=uart.readline()
    if (idreceive in str(receive_data)):
        return 1
    else:
        return 0
def onoff(pinnum):
    p = Pin(pinnum, Pin.OUT)
    p.on()
    time.sleep(0.5)
    p.off()
def createconfigfile(filename):
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)
    time.sleep(5)
    readmsg = uart.readline()
    if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in str(readmsg):
        content = readmsg
        with open(filename,mode='w',encoding='utf-8') as f:
            f.write(content)
def readconfigfile(filename):
    with open(filename,mode='r',encoding='utf-8') as f:
        s=f.read().strip('\n').split(',')
        if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in s:
            ssid=s[0].split(':')[1]
            pwd=s[1].split(':')[1]
            startt=s[2].split(':')[1]
            endt=s[3].split(':')[1]
            return ssid,pwd,startt,endt
        else:
            print('config file format error,will drop it')
            os.remove(filename)
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led1.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led1.value(0)
            time.sleep(0.1)
         print('同步失败')
# 联WIFI
def WIFI_Connect(ssid,pwd):
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid)
        wlan.connect(ssid, pwd) #输入WIFI账号密码
        time.sleep(1)
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('wifi Connected Timeout!')
                os.remove('config.txt')
                machine.reset()
    if wlan.isconnected():
        print('wifi was connected!')
try:
    a,b,c,d=readconfigfile('config.txt')
except:
    print('can not find config.txt,will create it!')
    createconfigfile('config.txt')
    time.sleep(2)
    machine.reset()
WIFI_Connect(a,b)
print(a,b,c,d)
while True:
    led2.value(1)
    time.sleep(0.1)
    led2.value(0)
    time.sleep(0.1)
    sync_ntp()
    dt=time.localtime()
    print(dt)
    linestate=linedetect()
    if linestate!=0:
        print('on line')
        if dt[3]>=int(d):
            onoff(2)
    else:
        print('off line')
        if (dt[3]<int(d) and dt[3]>=int(c)):
            onoff(2)

自动同步上位机配置文件更新

ESP-32-C3程序

#coding:utf-8
from machine import UART,Pin,RTC
import machine
import time,network
import ntptime
import os
led1=Pin(12,Pin.OUT)
led2=Pin(13,Pin.OUT)
rtc = RTC()
k=0
def linedetect():
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)  #设置Pin6=tx,Pin7=rx
    idsend='huanghe'
    idreceive='changjiang'
    uart.write(idsend)
    time.sleep(5)      #树莓派启动需要的时间,否则会反复重启
    receive_data=uart.readline()
    if (idreceive in str(receive_data)):
        return 1
    else:
        return 0
def onoff(pinnum):
    p = Pin(pinnum, Pin.OUT)
    p.on()
    time.sleep(0.5)
    p.off()
def createconfigfile(filename):
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)
    time.sleep(5)
    readmsg = uart.readline()
    if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in str(readmsg):
        content = readmsg
        with open(filename,mode='w',encoding='utf-8') as f:
            f.write(content)
def readconfigfile(filename):
    with open(filename,mode='r',encoding='utf-8') as f:
        s=f.read().strip('\n').split(',')
        if 'SSID' and 'PWD' and 'START' and 'END' and 'changjiang' in s:
            ssid=s[0].split(':')[1]
            pwd=s[1].split(':')[1]
            startt=s[2].split(':')[1]
            endt=s[3].split(':')[1]
            return ssid,pwd,startt,endt
        else:
            print('config file format error,will drop it')
            os.remove(filename)
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led1.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led1.value(0)
            time.sleep(0.1)
         print('同步失败')
# 联WIFI
def WIFI_Connect(ssid,pwd):
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid)
        wlan.connect(ssid, pwd) #输入WIFI账号密码
        time.sleep(1)
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('wifi Connected Timeout!')
                os.remove('config.txt')
                machine.reset()
    if wlan.isconnected():
        print('wifi was connected!')
try:
    a,b,c,d=readconfigfile('config.txt')
except:
    print('can not find config.txt,will create it!')
    createconfigfile('config.txt')
    time.sleep(2)
    machine.reset()
WIFI_Connect(a,b)
print(a,b,c,d)
while True:
    led2.value(1)
    time.sleep(0.1)
    led2.value(0)
    time.sleep(0.1)
    sync_ntp()
    dt=time.localtime()
    print(dt)
    linestate=linedetect()
    if linestate!=0:
        print('on line')
        if dt[3]>=int(d):
            onoff(2)
    else:
        print('off line')
        if (dt[3]<int(d) and dt[3]>=int(c)):
            onoff(2)

树莓派侧程序

#coding:utf-8
import serial
import time
with open('/home/pi/config.txt',mode='r',encoding='utf-8') as f:
   s=f.read()
i=0
Port ="/dev/ttyAMA0"
ser = serial.Serial(Port,115200,timeout=1)
while True:
#   send = 'SSID:HUAWEI-WULIAN,PWD:onlychina,START:6,END:20,changjiang'
   send=s
   i=i+1
   ser.write(send.encode('utf-8'))
#   str = ser.readline().decode()
   str1 = ser.readline().decode('utf-8')
#   time.sleep(5)
   if('huanghe' in str(str1)):
      print(str1+' '+str(i))
   else:
      print('can not get right info ,now info is '+str(str1))
      with open('/home/pi/config.txt',mode='r',encoding='utf-8') as f:
         s=f.read()
ser.close()

改进Ctrl+c的中断事件

#coding:utf-8
import serial
import time
try:
    s=''
    try:
        with open('/home/pi/config.json',mode='r',encoding='utf-8') as f:
           s=f.read()
    except:
        print("File 'config.json' can not find in dir /home/pi/,please create it first and run again.未能在/home/pi/目录下发现文件config.json,请按要求创建后再执行此程序")
    i=0
    Port ="/dev/ttyAMA0"
    ser = serial.Serial(Port,115200,timeout=1)
    while True:
    #   send = 'SSID:HUAWEI-WULIAN,PWD:onlychina,START:6,END:20,changjiang'
       send=s
       i=i+1
       ser.write(send.encode('utf-8'))
    #   str = ser.readline().decode()
       str1 = ser.readline().decode('utf-8')
    #   time.sleep(5)
       if('hello' in str(str1)):
          print(str1+' '+str(i))
       else:
          print('can not get right info ,now info is '+str(str1))
    ser.close()
except KeyboardInterrupt:
    print("Application exit!")
#coding:utf-8
from machine import UART,Pin,RTC
import machine
import time,network
import ntptime
import os
led1=Pin(12,Pin.OUT)
led2=Pin(13,Pin.OUT)
rtc = RTC()
k=0
def linedetect():
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)  #设置Pin6=tx,Pin7=rx
    idsend='hello'
    idreceive='world'
    uart.write(idsend)
    time.sleep(5)      #树莓派启动需要的时间,否则会反复重启
    receive_data=uart.readline()
    if (idreceive in str(receive_data)):
        return 1
    else:
        return 0
def onoff(pinnum):
    p = Pin(pinnum, Pin.OUT)
    p.on()
    time.sleep(0.5)
    p.off()
def createconfigfile(filename):
    uart=UART(1,baudrate=115200,tx=6,rx=7,timeout=1)
    time.sleep(5)
    readmsg = uart.readline()
    if 'SSID' and 'PWD' and 'START' and 'END' and 'world' in str(readmsg):
        content = readmsg
        with open(filename,mode='w',encoding='utf-8') as f:
            f.write(content)
def readconfigfile(filename):
    with open(filename,mode='r',encoding='utf-8') as f:
        s=f.read().strip('\n').split(',')
        if 'SSID' and 'PWD' and 'START' and 'END' and 'world' in s:
            ssid=s[0].split(':')[1]
            pwd=s[1].split(':')[1]
            startt=s[2].split(':')[1]
            endt=s[3].split(':')[1]
            return ssid,pwd,startt,endt
        else:
            print('config file format error,will drop it')
            os.remove(filename)
# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led1.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led1.value(0)
            time.sleep(0.1)
         print('同步失败')
# 联WIFI
def WIFI_Connect(ssid,pwd):
    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...'+ssid)
        wlan.connect(ssid, pwd) #输入WIFI账号密码
        time.sleep(1)
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('wifi Connected Timeout!')
                os.remove('config.json')
                machine.reset()
    if wlan.isconnected():
        print('wifi was connected!')
try:
    a,b,c,d=readconfigfile('config.json')
except:
    print('can not find config.json,will create it!')
    createconfigfile('config.json')
    time.sleep(2)
    machine.reset()
WIFI_Connect(a,b)
print(a,b,c,d)
while True:
    led2.value(1)
    time.sleep(0.1)
    led2.value(0)
    time.sleep(0.1)
    sync_ntp()
    dt=time.localtime()
    print(dt)
    linestate=linedetect()
    if linestate!=0:
        print('on line')
        if dt[3]>=int(d):
            onoff(2)
    else:
        print('off line')
        if (dt[3]<int(d) and dt[3]>=int(c)):
            onoff(2)