数码之家

 找回密码
 立即注册

QQ登录

只需一步,快速开始

微信登录

微信扫一扫,快速登录

搜索
查看: 6632|回复: 6

[AVR] ESP8266 使用 micropython 编程ntp数显tm1637 mqtt 上传 温湿度 气压到Domoticz 集中...

[复制链接]
发表于 2019-4-28 22:21:53 | 显示全部楼层 |阅读模式
本帖最后由 qingkong 于 2019-4-28 22:32 编辑

听说标题长了好。。。够长吧。。。。 :lol:

esp8266 NTP了时间给DS1307 然后读DS1307的时间给TM1637

然后采集DHT11和BMP180的数据通过MQTT协议发给 Domoticz 服务器做展示 只是做个表的话放着感觉有点浪费 于是顺便采集一下环境情况了

至于外观么 就是这样的。。。外面我也套了一个 ardunino的亚克力壳 算是抄袭坛子里一位朋友的创意了

联接也简单 I2C 的 BMP180 DS1307
自己联的TM1637 和 DHT11




上源码吧
能运行,但是就是写的不好看,反正是自己玩。。。也不优化和美观了,能给各位提供点灵感就好了。。。。

import json
import ntptime
import utime
import machine
from machine import Pin
from machine import I2C, Pin
import tm1637
import time
import urtc
from simple import MQTTClient
import dht
# from machine import WDT
import json
from bmp180 import BMP180
bus = I2C(scl=Pin(5), sda=Pin(4))   # on esp8266
bmp180 = BMP180(bus)
bmp180.oversample_sett = 2
bmp180.baseline = 101140


def bytesToHexString(bs):
    # hex_str = ''
    # for item in bs:
    #     hex_str += str(hex(item))[2:].zfill(2).upper() + " "
    # return hex_str
    return ''.join(['%02X' % b for b in bs])





count = 0
tm = tm1637.TM1637(clk=Pin(14), dio=Pin(12))
rtc_ds1307 = urtc.DS1307(bus)
# button = Pin(2, Pin.IN)
led = Pin(2, Pin.OUT)
IF_NTP = 0
tm.brightness(1)
tm.numbers(88, 88, True)
Point = True
ntp_time = 30*60*2  # NTP同步时间
MQTT_time = 5*60*2  # MQTT同步时间
# wdt=WDT(5000)
# wdt.feed



pin = 13
topic = 'domoticz/in'
decim_digits = 2  # 2位小数
sleep_time = 5  # 推送失败的话5秒重试
deviceIDX_BMP180 = 2
deviceIDX_DHT11 = 3
mqtt_svr = 'MQTT服务器'
dht11 = dht.DHT11(Pin(13))
user = 'MQTT用户名'
password = 'MQTT密码'
port = 34782 #MQTT端口
CLIENT_ID = bytesToHexString(machine.unique_id())
#修正采集值
MOD_BMP180_T=-1.98 #BMP180 温度
MOD_BMP180_P=0.4#BMP180 压力
MOD_DHT11_T=-1#DHT11温度
MOD_DHT11_H=5#DHT11湿度

def on_connect(CLIENT_ID, mqtt_svr, suser, spassword, sport):
    #print("Connected to " + mqtt_svr + " with result code {}")
# (self, client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}):
    client = MQTTClient(CLIENT_ID, mqtt_svr,  user=suser,
                        password=spassword, port=sport)
   # client.set_callback(sub_cb)
    try:
        client.connect()
    except:
        print('XXX')

    while True:
        try:
            dht11.measure()
            temperature = dht11.temperature()+MOD_DHT11_T
            humidity = dht11.humidity()+MOD_DHT11_H
            if humidity is not None and temperature is not None:
                temperature = round(temperature, decim_digits)
                humidity = round(humidity, decim_digits)
                str_temp = str(temperature)
                str_humidity = str(humidity)
                temp_hum = str_temp + ';' + str_humidity + ';' + '0;0;'
                publish_data = {'idx': deviceIDX_DHT11, 'RSSI': 8,
                                'nvalue': 0, 'svalue': temp_hum}
                client.publish(topic, json.dumps(publish_data))
               # print('Published!')
            else:
                print('Failed to get temperature reading. Pause and retry.')
        except:
            print('Failed to get temperature reading. Pause and retry.')

        try:
            temp = bmp180.temperature+MOD_BMP180_T
            p = bmp180.pressure+MOD_BMP180_P
            if temp is not None and p is not None:
                temp = round(temp, decim_digits)
                p = round(p/100, decim_digits)
                str_temp = str(temp)
                str_p = str(p)
                temp_hum = str_temp + ';' + str_p + ';' + '0;0;'
                publish_data = {'idx': deviceIDX_BMP180, 'RSSI': 8,
                                'nvalue': 0, 'svalue': temp_hum}
                client.publish(topic, json.dumps(publish_data))
             #   print('Published!')
                break
            else:
              #  print('Failed to get temperature reading. Pause and retry.')
                break
               # time.sleep(sleep_time)
        except:
            break
           # time.sleep(sleep_time)

   # print('Finished!')
    client.disconnect()


def show_time():
    global Point, tm
    # (year, month, mday, hour, minute, second, weekday, yearday)=utime.localtime()
    (year, month, day, weekday, hour, minute,
     second, millisecond) = rtc_ds1307.datetime()
    # year=2019, month=4, day=27, weekday=0, hour=8, minute=58, second=26, millisecond=None
#        subtrs="temp  " +str(temp)+  "   \nhum  " +str(hum) + "  "+ str(count)
#  subtrs=year+ "-"+ month+ "-"+ mday+ " "+  hour+ ":"+   minute+":"+  second+ "  Week:"+str(weekday+1)+   "   \nhum  " +"temp:" +str(temp)+  " hum:" +str(hum)

    # print(hour+'  ', end='')
    # print(minute)
    subtrs = '{:0>2d}'.format(
        hour) + '{:0>2d}'.format(minute)  # +":"+  str(second)
    # tm.numbers(""+'%2d' % hour, ""+'%2d' % minute, Point)
    # print(rtc_ds1307.datetime())
    tm.show(subtrs, Point)
#  datetime = rtc_ds1307.datetime()
#  print(datetime)
    Point = not Point
#  print (year,'-','%02d' % month, '-','%02d'% mday, ' ', '%02d'% hour, ':', '%02d'% minute, ':','%02d'% second, '  Week:',weekday+1, sep = '')


def ntpsettime(IF_NTP):
    try:
        led.off()
        ntptime.time()
        ntptime.settime()
        rtc = machine.RTC()
        tampon1 = utime.time()
        tampon2 = tampon1+8*60*60
        rtc.datetime(utime.localtime(tampon2)[
                     0:3] + (0,) + utime.localtime(tampon2)[3:6] + (0,))
        # The datetime is an 8-tuple of the format (year, month, day, weekday, hour, minute, second, millisecond) describing the time to be set. If not specified, the method returns a tuple in the same format.
        (year, month, mday, hour, minute, second,
         weekday, yearday) = utime.localtime()
        datetime = urtc.datetime_tuple(
            year=year, month=month, day=mday, weekday=(weekday+1) % 7, hour=hour, minute=minute, second=second)
        rtc_ds1307.datetime(datetime)
        # print(rtc.datetime())
        # print(rtc_ds1307.datetime())
        IF_NTP = 1
        led.on()
        # wdt.feed
    except:
        # print('XXX')
        datetime = rtc_ds1307.datetime()
        rtc.datetime([datetime.year, datetime.month, datetime.day,
                      datetime.weekday,  datetime.hour, datetime.minute, datetime.second, 0, ])
        print(datetime)
        IF_NTP = 0
        # wdt.feed
    return IF_NTP
# time.localtime()
# 开始循环


utime.sleep(1)
IF_NTP = ntpsettime(IF_NTP)
while 1:
    show_time()

    if ((count % (MQTT_time) == 0)):
        on_connect(CLIENT_ID, mqtt_svr, user, password, port)
    count = count+1
    # wdt.feed
    if ((count % (ntp_time) == 0) or (count % 10 == 0 and IF_NTP == 0)):
        IF_NTP = ntpsettime(IF_NTP)
        count = 0
    utime.sleep(0.5)



为何我传PYTHON的代码 使用代码那个总是没了缩进。。。又加了个附加 内容一样的





本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册 微信登录

x

打赏

参与人数 3家元 +118 收起 理由
devcang + 10 不错。。。。对python,不太喜欢那样的缩进.
数码家园 + 8 謝謝分享
家睦 + 100

查看全部打赏

 楼主| 发表于 2019-4-28 22:26:15 | 显示全部楼层
本帖最后由 qingkong 于 2019-4-28 22:31 编辑

上面的就是主程序的 但是没有联网部分
因为 那部分是我在mircopython的控制台下面直接操作的。。。。。

  1. 关闭WIFI和AP
  2. import network
  3. sta_if = network.WLAN(network.STA_IF)
  4. sta_if.active(False)
  5. AP_if = network.WLAN(network.AP_IF)
  6. AP_if.active(False)


  7. import network
  8. sta_if = network.WLAN(network.STA_IF)
  9. sta_if.active(True)
  10. #sta_if.scan()                             #  扫描当前可连接的WiFi名称
  11. sta_if.connect("sss", "sssssss")                # 设置要连接WiFi的名称和连接密码
  12. sta_if.isconnected()                      # 检查是否连接成功

  13. import  webrepl_setup
  14. webrepl.start()
复制代码

这些是手工执行

执行完了以后就可以从网络上用uPyLoader联接ESP8266的IP上传修改程序了
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-4-28 22:29:14 | 显示全部楼层
至于MQTT服务器和Domoticz 服务器的搭建 网上有很多  大家可以搜搜,找不到的话我再截屏
如果不要那个数字显示,只是传结果的话,使用ESPEASY固件更加简单 可以做到0编码搞定下图。。。

从浏览器上查看的结果



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册 微信登录

x
回复 支持 反对

使用道具 举报

发表于 2019-4-29 20:07:07 | 显示全部楼层
:victory:6666666666666666666666666666
回复 支持 反对

使用道具 举报

发表于 2019-4-29 20:34:35 | 显示全部楼层
外面我也套了一个 ardunino的亚克力壳 算是抄袭坛子里一位朋友的创意了
:lol:

我就是那位朋友:lol:
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-4-30 08:11:07 | 显示全部楼层
lyy-cy 发表于 2019-4-29 20:34
外面我也套了一个 ardunino的亚克力壳 算是抄袭坛子里一位朋友的创意了

对啊
要不是看了你的帖子,我还真没想出那个外壳能干点啥。。。

多谢啊
回复 支持 反对

使用道具 举报

发表于 2019-5-9 09:57:48 | 显示全部楼层
6666啊,完全看不懂!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册 微信登录

本版积分规则

APP|手机版|小黑屋|关于我们|联系我们|法律条款|技术知识分享平台

闽公网安备35020502000485号

闽ICP备2021002735号-2

GMT+8, 2025-7-22 07:07 , Processed in 0.280801 second(s), 13 queries , Redis On.

Powered by Discuz!

© 2006-2025 MyDigit.Net

快速回复 返回顶部 返回列表