#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 版本:V2.0
# author: zhulin
# 硬件:
# 1. Pico + Esp8285开发板
# 2. LED灯 2个
# 3. DS18B20温度传感器 1个
# 4. 1602液晶LCD显示屏 1个
# 5. 10K可调电阻 1个,调整液晶屏的对比度
# 说明:
# 1. HTTP服务器,绿色LED,有访问闪烁
# 2. 温度传感器,读取温度时,红灯闪烁
# 3. LCD1602显示,文字
#---------------------------------------
from machine import UART, Pin, PWM
import utime,time
import _thread
import sys
import machine
import onewire, ds18x20
# ----- 蜂鸣器 --------
BuzzerObj=PWM(Pin(6))
# ------------- 引脚定义 ------------
board_led = machine.Pin(25, machine.Pin.OUT) # 板载LED灯
# ************* 18B20 温度传感器 *************
temperature_sensor = machine.Pin(4) # 温度传感器
led_extern_temperature_status = machine.Pin(3, machine.Pin.OUT) # 温度传感器状态灯
ds = ds18x20.DS18X20(onewire.OneWire(temperature_sensor))
# ************* ESP8285 无线WIFI模块 **************
led_extern_httpserver_status = machine.Pin(5, machine.Pin.OUT)
# 串口映射到GP0和GP1端口上,在使用该端口和WIFI模块通讯时,不要使用GP0和GP1端口
esp_uart = UART(0, 115200) # 串口0,波特率为115200
# WIFI 路由器信息,请填上自己的WIFI路由器信息
SSID='XXXXXX' # WIFI名称
password = 'xxxxxxx' # WIFI密码
Port = '8080' # 自定义端口号
# ************* LCD1602液晶显示屏 *****************
#---------------引脚-------------
# 数据或命令 读写
rs = machine.Pin(16,machine.Pin.OUT)
e = machine.Pin(17,machine.Pin.OUT)
d4 = machine.Pin(18,machine.Pin.OUT)
d5 = machine.Pin(19,machine.Pin.OUT)
d6 = machine.Pin(20,machine.Pin.OUT)
d7 = machine.Pin(21,machine.Pin.OUT)
global bIsInit # 已经初始化
bIsInit = False
def buzzer(buzzerPinObject,frequency,sound_duration,silence_duration):
# Set duty cycle to a positive value to emit sound from buzzer
buzzerPinObject.duty_u16(int(65536*0.2))
# Set frequency
buzzerPinObject.freq(frequency)
# wait for sound duration
time.sleep(sound_duration)
# Set duty cycle to zero to stop sound
buzzerPinObject.duty_u16(int(65536*0))
# Wait for sound interrumption, if needed
time.sleep(silence_duration)
# Play following notes by changing frequency:
def Note_1():
#C (DO)
buzzer(BuzzerObj,523,0.5,0.1)
def Note_1_3():
#C (DO)
buzzer(BuzzerObj,523,1.5,0.1)
def Note_2():
#D (RE)
buzzer(BuzzerObj,587,0.5,0.1)
def Note_3():
#E (MI)
buzzer(BuzzerObj,659,0.5,0.1)
def Note_4():
#F (FA)
buzzer(BuzzerObj,698,0.5,0.1)
def Note_5():
#G (SOL)
buzzer(BuzzerObj,784,0.5,0.1)
def Note_6():
#A (LA)
buzzer(BuzzerObj,880,0.5,0.1)
def Note_7():
#B (SI)
buzzer(BuzzerObj,987,0.5,0.1)
def marryAndSheep():
Note_3()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_1()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_5()
time.sleep_ms(50)
Note_5()
time.sleep_ms(50)
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_1()
time.sleep_ms(50)
Note_2()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
Note_3()
time.sleep_ms(50)
time.sleep_ms(50)
Note_1_3()
# 休眠,防止烧坏
BuzzerObj.deinit()
# 闪烁并点亮板载LED灯
def board_led_toggle():
board_led.toggle()
time.sleep(2)
board_led.value(1)
def LCD1602_pulseE():
e.value(1)
utime.sleep_us(40)
e.value(0)
utime.sleep_us(40)
# 发送给LCD
def LCD1602_send2LCD4(BinNum):
d4.value((BinNum & 0b00000001) >>0)
d5.value((BinNum & 0b00000010) >>1)
d6.value((BinNum & 0b00000100) >>2)
d7.value((BinNum & 0b00001000) >>3)
LCD1602_pulseE()
def LCD1602_send2LCD8(BinNum):
d4.value((BinNum & 0b00010000) >>4)
d5.value((BinNum & 0b00100000) >>5)
d6.value((BinNum & 0b01000000) >>6)
d7.value((BinNum & 0b10000000) >>7)
LCD1602_pulseE()
d4.value((BinNum & 0b00000001) >>0)
d5.value((BinNum & 0b00000010) >>1)
d6.value((BinNum & 0b00000100) >>2)
d7.value((BinNum & 0b00001000) >>3)
LCD1602_pulseE()
def LCD1602_setUpLCD():
rs.value(0)
LCD1602_send2LCD4(0b0011)#8 bit
LCD1602_send2LCD4(0b0011)#8 bit
LCD1602_send2LCD4(0b0011)#8 bit
LCD1602_send2LCD4(0b0010)#4 bit
LCD1602_send2LCD8(0b00101000)#4 bit,2 lines?,5*8 bots
LCD1602_send2LCD8(0b00001100)#lcd on, blink off, cursor off.
LCD1602_send2LCD8(0b00000110)#increment cursor, no display shift
LCD1602_send2LCD8(0b00000001)#clear screen
utime.sleep_ms(2)#clear screen needs a long delay
def LCD1602_ShowText(text):
LCD1602_setUpLCD()
# 选择数据寄存器
rs.value(1)
# strText = 'Temp: 23.5`C'
strText = text
for x in strText:
intVal = ord(x) # 字符转化为数字,比如'A' ->
LCD1602_send2LCD8(intVal)
# print(intVal)
# 全局变量
global g_cur_tempture
g_cur_tempture = "999.01"
# 发送命令函数
def esp_sendCMD(cmd,ack,timeout=2000):
esp_uart.write(cmd+'\r\n')
i_t = utime.ticks_ms()
while (utime.ticks_ms() - i_t) < timeout:
s_get=esp_uart.read()
if(s_get != None):
s_get=s_get.decode()
print(s_get)
if(s_get.find(ack) >= 0):
return True
return False
# 发送数据
def esp_sendData(ID,data):
esp_sendCMD('AT+CIPSEND='+str(ID)+','+str(len(data)),'>')
esp_uart.write(data)
# 接收数据
def esp_ReceiveData():
s_get=esp_uart.read()
if(s_get != None):
print(s_get)
s_get=s_get.decode()
if(s_get.find('+IPD') >= 0):
n1=s_get.find('+IPD,')
n2=s_get.find(',',n1+5)
ID=int(s_get[n1+5:n2])
n3=s_get.find(':')
s_get=s_get[n3+1:]
return ID,s_get
return None,None
def esp_StartTcpServer():
esp_uart.write('+++') # 初始化退出透传模式
time.sleep(1)
if(esp_uart.any()>0):
esp_uart.read()
esp_sendCMD("AT","OK") # AT指令
esp_sendCMD("AT+CWMODE=3","OK") # 配置 WiFi 模式
esp_sendCMD("AT+CWJAP=\""+SSID+"\",\""+password+"\"","OK",20000) # 连接路由器
esp_sendCMD("AT+CIPMUX=1","OK") # 使能多连接
esp_sendCMD("AT+CIPSERVER=1,"+Port,"OK") # 建⽴ TCP server
esp_sendCMD("AT+CIFSR","OK") # 查询 WIFI模块的 IP 地址
print('-- ESP8285 Webserver --port: %s' % Port)
def http_SetText(pkgid, body):
head = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n'
rawhtml = "{}{}\r\n".format(head, body)
esp_sendData(pkgid,rawhtml)
time.sleep_ms(50)
esp_sendCMD("AT+CIPCLOSE=0","OK")
led_extern_httpserver_status.value(1)
time.sleep_ms(200)
led_extern_httpserver_status.value(0)
def print_time(thread_name, delay):
while True:
time.sleep(delay)
print("%s: %s" % (thread_name, time.gmtime()))
def thread_getTemperture(thread_name, delay):
while True:
# scan for devices on the bus
roms = ds.scan()
print('found devices:', roms)
lenRoms = len(roms)
if lenRoms == 0:
print('没找到DS18B20温度传感器')
text = 'Temp: 18B20 Err'
LCD1602_ShowText(text)
time.sleep(1)
else:
try:
# loop 10 times and print all temperatures
for i in range(10 * 10):
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
tupTime = time.gmtime()
strCurTime = "{}-{}-{} {}:{}:{}".format(tupTime[0], tupTime[1], tupTime[2], tupTime[3], tupTime[4],tupTime[5])
print(strCurTime , '| temperatures:', end=' ')
global g_cur_tempture
g_cur_tempture = ds.read_temp(rom)
#g['tempture'] = g_cur_tempture
print(g_cur_tempture, end=' ')
print()
led_extern_temperature_status.toggle()
#print(g_cur_tempture)
text = 'Temp: %s`C' % g_cur_tempture
LCD1602_ShowText(text)
global bIsInit
if bIsInit == False:
bIsInit = True
print('---> play song')
marryAndSheep()
time.sleep_ms(5250)
except:
text = 'Except ERR'
LCD1602_ShowText(text)
# time.sleep(1)
time.sleep(delay)
def led_on():
# led_extern_temperature_status.value(1)
# time.sleep_ms(200)
board_led.value(1)
time.sleep_ms(100)
print('func[led_on]')
def led_off():
#led_extern_temperature_status.value(0)
#time.sleep_ms(200)
board_led.value(0)
time.sleep_ms(100)
print('func[led_off]')
# 程序入口
if __name__ == "__main__":
board_led_toggle()
text = 'Loading...'
LCD1602_ShowText(text)
esp_StartTcpServer()
text = 'PicoSite Hi!'
LCD1602_ShowText(text)
#_thread.start_new_thread(print_time, ("Thread 1", 1, ))
_thread.start_new_thread(thread_getTemperture, ("thread_ds18b20", 30))
while True:
ID,s_get=esp_ReceiveData() # 接收数据
if(ID != None):
if s_get.find("/led?led=on") != -1:
print('----> led on')
led_on()
html = '''<!DOCTYPE HTML><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MyPicoSite</title></head><body>led=on</body></html>'''
http_SetText(ID, html)
#board_led.value(1)
#time.sleep_ms(100)
continue
elif s_get.find("/led?led=off") != -1:
print('----> led off')
led_off()
#board_led.value(0)
#time.sleep_ms(100)
html = '''<!DOCTYPE HTML><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MyPicoSite</title></head><body>led=off</body></html>'''
http_SetText(ID, html)
continue
else:
print('--recv: {}bytes', len(s_get))
# 设备时间
tupTime = time.gmtime()
strCurTime = "{}-{}-{} {}:{}:{}".format(tupTime[0], tupTime[1], tupTime[2], tupTime[3], tupTime[4],tupTime[5])
# 硬件信息
deviceInfo = sys.implementation
print("当前温度: {}".format(g_cur_tempture))
strBody = '''device: {}<br>
time: {}<br>
tempture: {}<br>'''.format(deviceInfo,strCurTime, g_cur_tempture)
html = """
<!DOCTYPE html>
<html>
<head>
<title>PicoStie-JG</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
text-align: center;
max-width: 100%;
margin: 0 auto;
}
button {
background-color: #4CAF50;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
button.green {
background-color: #4CAF50;
color: #FFFFFF;
}
button.red {
background-color: #FF5733;
color: #FFFFFF;
}
button.refresh {
background-color: #56452d;
color: #FFFFFF;
}
</style>
</head>
<body>
<h1>This My Pico Site!</h1>
<hr>
<button class="green" onclick="fetch('/led?led=on');">led=on</button><br>
<button class="red" onclick="fetch('/led?led=off');">led=off</button><br>
<button class="refresh" onclick="location.reload()">refresh</button>
<br>
<hr>"""
strTail = '</body></html>'
html = html + strBody + strTail
http_SetText(ID, html)