当前位置:网站首页>Salted fish esp32 instance - mqtt lit LED
Salted fish esp32 instance - mqtt lit LED
2022-07-28 09:28:00 【Salted fish shell】
Salted fish ESP32 example —MQTT Lighten up LED
Please call me lamplighter QAQ
Materials and wiring
ESP32
** Communication cat debugging software **
( Get yourself a server ) It's easy to see with a cat , Make a web page for yourself later . In addition, please download Baidu by yourself. Thank you .

Constructors
| Constructors |
|---|
| client=simple. MQTTClient (client_id, server, port) |
| structure MQTT Client object . |
| client_id: client ID, Have uniqueness ;server: Server address , It can be IP Or the website ;port: Server port .( The port usually used by the server , You can customize .) |
| Usage method |
| client.connect() |
| Connect to the server . |
| client.publish(TOPIC,message) |
| Release .TOPIC: Subject number ;message: information content , example :‘Hello~’ |
| client.subscribe(TOPIC) |
| subscribe .TOPIC: Subject number . |
| client.set_callback(callback) |
| Set the callback function .callback: If you receive information after subscription , Execute the callback function of the phase name . |
| client.check_msg() |
| Check subscription information . If you receive the message, execute the set callback function callback. |
| Constructors |
|---|
| client=simple. MQTTClient (client_id, server, port) |
| structure MQTT Client object . |
| client_id: client ID, Have uniqueness ;server: Server address , It can be IP Or the website ;port: Server port .( The port usually used by the server , You can customize .) |
| Usage method |
| client.connect() |
| Connect to the server . |
| client.publish(TOPIC,message) |
| Release .TOPIC: Subject number ;message: information content , example :‘Hello~’ |
| client.subscribe(TOPIC) |
| subscribe .TOPIC: Subject number . |
| client.set_callback(callback) |
| Set the callback function .callback: If you receive information after subscription , Execute the callback function of the phase name . |
| client.check_msg() |
| Check subscription information . If you receive the message, execute the set callback function callback. |
Sample code
MQTT After connection , Control by sending and publishing messages ESP32 Development board LED.
Throw a brick and attract jade , Several libraries in it are in firmware and cannot be displayed . Interested friends can simplify the code by themselves . This is just a reference , After all, I can't write too much without releasing the board .
Tips :MQTT Search the Library github,ztcomm Before Library 3.5 Inch screen should have been sent . No more writing , If you write too much, the official will come to me (QAQ)
main.py
from machine import Pin
import socket
import network
import struct
import time
import json
import ztcomm
from mqttclient import MQTTClient
import _thread
# wifi Account password of
SSID="XXX"
PASSWORD="XXX"
# LED Pin
led=Pin(2, Pin.OUT, value=0)
# initialization
wlan=None
mymac=None
zt=None
config=None
wifilist=None
# MQTT Information
SERVER = '0,0,0,0' #IP Address
CLIENT_ID = 'esp32client' # name
TOPIC = 'xx' # Subject number
username='xx' # account number
password='xx' # password
state = 0
c=None
# open json File read content ( Namely wifi and MQTT The information of )
def zt_config():
global SSID,PASSWORD,SERVER,CLIENT_ID,TOPIC,username,password,config
with open('ztconfig.json','r') as f:
config = json.loads(f.read())
SSID=config['SSID']
PASSWORD=config['PASSWORD']
SERVER=config['SERVER']
CLIENT_ID=config['CLIENT_ID']
TOPIC=config['TOPIC']
username=config['username']
password=config['password']
f.close()
# link wifi
def connectWifi(ssid,passwd):
global wlan,mymac,zt
restr='0'
nn=0
try:
wlan=network.WLAN(network.STA_IF) # establish wlan object
wlan.active(True) # Activate
wlan.disconnect() # Disconnect the last wifi Connect
wlan.connect(ssid,passwd) # Connect wifi
time.sleep(8)
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
nn+=1
print('network config err ap:%s|num:%d' % (ssid,nn))
if(nn>5):
wlan.active(False)
return False
break
s=wlan.config('mac')
mymac=('%02x-%02x-%02x-%02x-%02x-%02x') %(s[0],s[1],s[2],s[3],s[4],s[5]) # obtain mac Address
time.sleep(4)
ptstr='ip:%s,mask:%s\r\ngateway:%s,dns:%s\r\nmac:%s' %(wlan.ifconfig()[0],wlan.ifconfig()[1],wlan.ifconfig()[2],wlan.ifconfig()[3],mymac.upper())
print(ptstr) # Output ip mask gateway dns mac
return True
except Exception as e:
print(Exception,'BBB:',e,type(Exception),type(e))
wlan.active(False)
def disconnect():
global wlan
wlan.disconnect()
wlan.active(False)
# Lighting function , Others can be ignored , Just look at this ~
def sub_cb(topic, msg):
global state
print((topic, msg))
if msg == b"on":
led.value(1)
state = 0
print("1")
elif msg == b"off":
led.value(0)
state = 1
print("0")
elif msg == b"toggle":
led.value(state)
state = 1 - state
def waitmqmsg(c):
while True:
c.wait_msg()
time.sleep(1)
def main():
global wlan,zt,c,config,wifilist
shunum=-1
zt=ztcomm.ztcomm()
try:
zt_config()
time.sleep(1)
# Return after successful connection IP、MAC Etc
if connectWifi(SSID,PASSWORD):
led.value(1)
server=SERVER
c = MQTTClient(CLIENT_ID, server,0,username,password) # Connect
c.set_callback(sub_cb) # Execute callback function
c.connect() # Connect to server
c.subscribe(TOPIC) # Subscribe to topics
tpstr="Connected to %s, subscribed to %s topic" % (server, TOPIC)
print(tpstr)
# Sending data
headstr=('(%s,%s,%s,%s,%s)') %(wlan.ifconfig()[0],wlan.ifconfig()[1],wlan.ifconfig()[2],wlan.ifconfig()[3],mymac.upper())
# Group character
a="xxx"
pubstr='%s-%s-%s' %(TOPIC,headstr,a)
c.publish(TOPIC,pubstr)
# Receive data ( Open a thread to accept data )
_thread.start_new_thread(waitmqmsg(c), ())
led.value(0)
# Anti stop operation
while True:
time.sleep(1)
except Exception as e:
print(Exception,':AAAA:',e,type(Exception),type(e))
finally:
if(c is not None):
c.disconnect()
disconnect()
if __name__ == '__main__':
main()
ztconfig
{
"SSID": "wifi account number ", "PASSWORD": "wifi password ", "CLIENT_ID": "x", "username": "x", "SERVER": "ip Address ", "TOPIC": " name ", "password": " password "}
Effect display

After successful connection, the communication cat will display various information of the development board (IP dns mac), Test development board LED For open state , Enter toggle Flip LED state 
You can also type ‘on’ and ‘off’ To control the switch light . At this time, the serial port will return data 
边栏推荐
- IT行业数据与应用关系的变迁
- 3D全景展示新模式,成为破局的关键
- 2.9.5 ext JS object type processing and convenient methods
- 2022 examination question bank and simulation examination of crane driver (limited to bridge crane)
- [Download] several tools for brute force cracking and dictionary generation are recommended
- 对话MySQL之父:代码一次性完成才是优秀程序员
- Personal blog applet
- Recommend an artifact to get rid of the entanglement of variable names and a method to modify file names in batches
- 【打包部署】
- QT basic hand training applet - simple calculator design (with source code, analysis)
猜你喜欢

2022年安全员-B证考试模拟100题及答案

IP protocol of network layer

376. 摆动序列【贪心、动态规划------】

Recommend an artifact to get rid of the entanglement of variable names and a method to modify file names in batches
![[vscode] vscode usage](/img/0d/d6edbad047ecd7a092d4d7aa06e04d.png)
[vscode] vscode usage
![[one flower, one world - Professor Zheng Yi - the way of simplicity] interpretable neural network](/img/fd/8ae7c00061491ad78a0fd68b7c21b0.png)
[one flower, one world - Professor Zheng Yi - the way of simplicity] interpretable neural network

技术分享| 快对讲综合调度系统

Magic Bracelet-【群论】【Burnside引理】【矩阵快速幂】

2022高压电工考试模拟100题及模拟考试

12 common design ideas of design for failure
随机推荐
IP protocol of network layer
Promise实例如何解决地狱回调
2022年起重机司机(限桥式起重机)考试题库及模拟考试
19c sysaux tablespace sqlobj$plan table is too large. How to clean it up
How does gbase 8A use preprocessing to quickly insert data?
Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022
Activiti startup error: cannot create poolableconnectionfactory (could not create connection to database server
【AUTOSAR-RTE】-3-Runnable及其Task Mapping映射
MQTT. JS introductory tutorial: learning notes
Conference OA system
FPGA development learning open source website summary
LeetCode_ 406_ Rebuild the queue based on height
MQTT.js 入门教程:学习笔记
01-TensorFlow计算模型(一)——计算图
一款入门神器TensorFlowPlayground
VR全景拍摄,助力民宿多元化宣传
Informatics Olympiad all in one 1617: circle game | 1875: [13noip improvement group] circle game | Luogu p1965 [noip2013 improvement group] circle game
[solution] error in [eslint] eslint is not a constructor
【英语考研词汇训练营】Day 15 —— analyst,general,avoid,surveillance,compared
Oracle creates users with query permission only