数码之家

 找回密码
 立即注册
搜索
查看: 1267|回复: 0

[Arduino] [Arduino] [esp8266_micropython] hc-sr04超声波距离传感器数据读取与mqtt上报

[复制链接]
发表于 2023-7-22 23:26:16 | 显示全部楼层 |阅读模式

爱科技、爱创意、爱折腾、爱极致,我们都是技术控

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

x
代码

  1. import time
  2. from machine import Pin
  3. import network
  4. from umqtt.simple import MQTTClient
  5. import json
  6. import gc

  7. device_id = "esp0004"
  8. wifi_ssid='FAST_20CC'
  9. wifi_password='409409409'
  10. mqtt_serverip='192.168.1.113'
  11. mqtt_serverport=1883
  12. mqtt_clientid=device_id
  13. mqtt_publishtopic=b'espiot'

  14. message_template = {}
  15. message_template['source_device'] = mqtt_clientid
  16. message_template['target_device'] = 'server'
  17. message_template['msg_type'] = 'ReportDistance'

  18. led=Pin(2,Pin.OUT)
  19. led.on()

  20. # D2
  21. trig = machine.Pin(4,machine.Pin.OUT)
  22. # D1
  23. echo = machine.Pin(5,machine.Pin.IN)

  24. def distance():
  25.     trig.value(1)
  26.     time.sleep_us(10)
  27.     trig.value(0)
  28.     while echo.value() == 0:
  29.         pass
  30.     while echo.value() == 1:
  31.         ts = time.ticks_us()
  32.         while echo.value() == 1:
  33.             pass
  34.         te = time.ticks_us()
  35.         tc = te - ts
  36.         distance = round((tc*170)/10000, 2)
  37.     return distance

  38. def connectionWifi(ssid, password):
  39.   wlan = network.WLAN(network.STA_IF)
  40.   wlan.active(True)
  41.   wlan.connect(ssid, password)
  42.   while True:
  43.     if not wlan.isconnected():
  44.       led.on()
  45.       time.sleep_ms(1000)
  46.       led.off()
  47.       time.sleep_ms(1000)
  48.     else:
  49.       print('connected to network')
  50.       led.on()
  51.       break

  52. if __name__=='__main__':
  53.   print ("start")
  54.   
  55.   connectionWifi(wifi_ssid,wifi_password)
  56.   
  57.   client = MQTTClient(mqtt_clientid,mqtt_serverip,mqtt_serverport)
  58.   client.connect()
  59.   
  60.   while True:
  61.     time.sleep(3)
  62.     message_template['distance'] = str(distance())
  63.    
  64.     client.publish(mqtt_publishtopic,json.dumps(message_template))
  65.    
  66.     gc.collect()
复制代码


截图

开发板与传感器

开发板与传感器

mqtt数据接收

mqtt数据接收
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

闽公网安备35020502000485号

闽ICP备2021002735号-2

GMT+8, 2024-4-27 23:58 , Processed in 0.218401 second(s), 13 queries , Redis On.

Powered by Discuz!

© 2006-2023 smzj.net

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