MicroPython简易闹钟

创意展示、DIY分享、经验交流
回复
头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

MicroPython简易闹钟

#1

帖子 shaoziyang »

来自:https://www.hackster.io/alankrantas/sim ... ock-0e1a2f

通过NTP协议进行校准的时钟

图片

使用的硬件
  • Wemos D1 Mini
  • OLED 64x128
  • 蜂鸣器
  • 倾斜开关
网络时钟部分类似于我之前的项目Very Simple MicroPython ESP8266 / ESP-12网络时钟。主要区别在于它通过NTP(网络时间协议)而不是使用第三方API来查询时间。

所述ntptime 是MicroPython的内置库,其可以通过简单地调用被容易地用于将ESP8266 / ESP32板更新系统时间(本地时间)ntptime.settime() 。(请注意,取决于您的WiFi连接质量,您的NTP查询可能并不总是成功。)

您从NTP获得的时间为UTC + 0;在代码中,变量timezone_hour 可用于设置时区调整。例如,如果您的时区为UTC + 8,则设置timezone_hour = 8。该项目还使用非阻塞式Web服务器来提供闹钟设置界面(它不会阻塞循环过程以等待新的客户端连接,因此时钟时间仍然可以正常显示)。我写了一段代码,可以将任何名称的任意数量的参数解析到URL 的列表para_array中。这对于想要建立类似项目的人可能很有用。


图片


REPL输出

代码: 全选

Connecting to WiFi...
Connected.
Web server is now online on xxx, IP: 192.168.100.155
NTP server query successful.
System time updated: (2019, 12, 4, 7, 56, 25, 2, 338)
New client connected, IP: ('192.168.100.164', 54551)
Alarm has been set to 7:30
Alarm enabled
Sending web page...
Client connection ended.
蜂鸣器用作警报,倾斜开关可用于通过摇动来关闭警报。0.96英寸的OLED显示屏显示时钟时间和警报时间,警报状态(启用“ o”而未启用“ x”)以及服务器IP(在您的本地WiFI网络上)。如果没有人摇动倾斜开关,警报将在一分钟后自动关闭。该代码已在MicroPython固件v1.11上进行了测试。

原理图图片


代码
 

Code: Select all

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import network, usocket, utime, ntptime


ssid = "your_wifi_id"
pw = "your_wifi_password"

pic_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Wheelock_mt2.jpg/675px-Wheelock_mt2.jpg"
web_query_delay = 600000
timezone_hour = 0
alarm = [7, 30, 0]


oled = SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
buzzer = Pin(14, Pin.OUT)
buzzer.off
shake_sensor = Pin(12, Pin.IN, Pin.PULL_UP)


print("Connecting to WiFi...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, pw)
while not wifi.isconnected():
pass
print("Connected.")


s = usocket.socket()
s.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
s.bind(("", 80))
s.setblocking(False)
s.settimeout(1)
s.listen(1)
print("Web server is now online on " + ssid + ", IP: " + str(wifi.ifconfig()[0]))


def webpage(data):
html = "<!DOCTYPE html>"
html += "<html>"
html += "<head>"
html += "<title>MicroPython Alarm Clock</title>"
html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
html += "<link rel=\"icon\" href=\"#\">"
html += "<style>body {background-color: Moccasin;} h1 {color: SaddleBrown;} h2 {color: Olive;} </style>"
html += "</head>"
html += "<body><center>"
html += "<h1>MicroPython Alarm Clock</h1>"
html += "<h2>When the hell would you sir like to wake up?</h2>"
html += "<p><img src=\"" + pic_url + "\" width=300px></p>"
html += "<form methon=\"GET\" action=\"\">"
html += "<p>Set at (hour/minute) "
html += "<input type=\"text\" name=\"hour\" size=\"2\" maxlength=\"2\" value=\"" + str(data[0]) + "\">"
html += " : <input type=\"text\" name=\"minute\" size=\"2\" maxlength=\"2\" value=\"" + str(data[1]) + "\">"
html += "</p><p>Enable: <select name=\"enable\">"
if data[2] == 1:
html += "<option value=\"0\">No</option>"
html += "<option value=\"1\" selected>Yes</option>"
else:
html += "<option value=\"0\" selected>No</option>"
html += "<option value=\"1\">Yes</option>"
html += "</select></p>"
html += "<p><input type=\"submit\" value=\"Update\"></p>"
html += "</form>"
html += "<p><input type=\"button\" value=\"Refresh\" onclick=\"window.location.href=''\"></p>"
html += "</center></body>"
html += "</html>"
return html


update_time = utime.ticks_ms() - web_query_delay
clients = []


while True:

try:
client, addr = s.accept()
print("New client connected, IP: " + str(addr))
clients.append(client)

except:
pass

for client in clients:

try:
request = client.recv(1024)
request_text = str(request.decode("utf-8"))
para_pos = request_text.find("/?")

if para_pos > 0:
para_str = request_text[para_pos + 2:(request_text.find("HTTP/") - 1)]
para_array = para_str.split('&')

for i in range(len(para_array)):
para_array[i] = (para_array[i])[para_array[i].find('=') + 1:]

for i in range(3):
if para_array[i].isdigit():
alarm[i] = int(para_array[i])
else:
print("!!! Alarm time set error !!!")

print("Alarm has been set to " + str(alarm[0]) + ":" + str(alarm[1]))
if alarm[2] == 1:
print("Alarm enabled")
else:
print("Alarm disabled")

response = webpage(alarm)
print("Sending web page...")
client.send("HTTP/1.1 200 OK\n")
client.send("Content-Type: text/html; charset=utf-8\n")
client.send("Connection: close\n\n")
client.send(response)
client.close()
clients.remove(client)
print("Client connection ended.")

except:
pass

if utime.ticks_ms() - update_time >= web_query_delay:

try:
ntptime.settime()
print("NTP server query successful.")
print("System time updated: ", utime.localtime())
update_time = utime.ticks_ms()

except:
print("NTP server query failed.")

local_time_sec = utime.time() + timezone_hour * 3600
local_time = utime.localtime(local_time_sec)
time_str = "{:02}:{:02}:{:02}".format(local_time[3], local_time[4], local_time[5])
alarm_str = "{:02}:{:02}".format(alarm[0], alarm[1])
alarm_str += " [O]" if alarm[2] == 1 else " [X]"

oled.fill(0)
oled.text("Alarm: " + alarm_str, 0, 8)
oled.text("Time: " + time_str, 0, 24)
oled.text(wifi.ifconfig()[0], 0, 48)
oled.show()

if alarm[2] == 1 and alarm[0] == local_time[3] and alarm[1] == local_time[4]:

print("!!! Alarm triggered !! Shake to turn off !!!")
buzzer.on()

if shake_sensor.value() == 1:
alarm[2] = 0
buzzer.off()
print("Alarm turned off.")[/sytax]

dexter
帖子: 298
注册时间: 2019年 10月 24日 12:41

Re: MicroPython简易闹钟

#2

帖子 dexter »

很有参考价值!

回复

  • 随机主题
    回复总数
    阅读次数
    最新文章