4226|1

1万

帖子

24

TA的资源

版主

楼主
 

MicroPython简易闹钟 [复制链接]

 

来自: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中。这对于想要建立类似项目的人可能很有用。


图片

 

蜂鸣器用作警报,倾斜开关可用于通过摇动来关闭警报。0.96英寸的OLED显示屏显示时钟时间和警报时间,警报状态(启用“ o”而未启用“ x”)以及服务器IP(在您的本地WiFI网络上)。如果没有人摇动倾斜开关,警报将在一分钟后自动关闭。该代码已在MicroPython固件v1.11上进行了测试。

原理图图片


代码

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.")

 

最新回复

有个问题啊   根据usocket文档 This method is a shorthand for certain settimeout() calls: sock.setblocking(True) is equivalent to sock.settimeout(None) sock.setblocking(False) is equivalent to sock.settimeout(0) 你代码里的 s.setblocking(False) s.settimeout(1) 是有问题的   详情 回复 发表于 2020-3-10 11:56
点赞 关注
 
 

回复
举报

6

帖子

0

TA的资源

一粒金砂(初级)

沙发
 

有个问题啊

 

根据usocket文档

This method is a shorthand for certain settimeout() calls:

  • sock.setblocking(True) is equivalent to sock.settimeout(None)
  • sock.setblocking(False) is equivalent to sock.settimeout(0)

你代码里的

  • s.setblocking(False)
  • s.settimeout(1)

是有问题的

 
 
 

回复
您需要登录后才可以回帖 登录 | 注册

查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/6 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表