当前位置:网站首页>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 
边栏推荐
- 【592. 分数加减运算】
- 一款入门神器TensorFlowPlayground
- Dn-detr paper accuracy, and analyze its model structure & 2022 CVPR paper
- F - Jealous Two-二维逆序对
- MySQL 8.0.30 GA
- 19c SYSAUX表空间SQLOBJ$PLAN表过大,如何清理
- 正负数值的正则表达式
- What is it like to use gbase C API to execute stored procedures?
- 2022 high voltage electrician examination simulated 100 questions and simulated examination
- Oracle-11gr2 default system job
猜你喜欢

Detailed introduction of v-bind instruction

什么是跨域?如何解决请跨域问题?

Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022

Modify virtual machine IP address

Personal blog applet

对话MySQL之父:代码一次性完成才是优秀程序员

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

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

IntelliJ idea associated database

Recommend an artifact to get rid of the entanglement of variable names and a method to modify file names in batches
随机推荐
Force deduction question (1) -- sum of two numbers
一款入门神器TensorFlowPlayground
Rgb-t tracking: [multimodal fusion] visible thermal UAV tracking: a large scale benchmark and new baseline
golang升级到1.18.4版本 遇到的问题
数据泄漏、删除事件频发,企业应如何构建安全防线?
【解决】ERROR in [eslint] ESLint is not a constructor
[JVM] JVM refers to floating point number
2022年起重机司机(限桥式起重机)考试题库及模拟考试
ES6 变量的解构赋值
力扣题(1)—— 两数之和
2022年安全员-B证考试模拟100题及答案
3D全景展示新模式,成为破局的关键
[vscode] vscode usage
FPGA development learning open source website summary
How does gbase 8A use preprocessing to quickly insert data?
mysql 最大建议行数2000w,靠谱吗?
19c sysaux tablespace sqlobj$plan table is too large. How to clean it up
AMQ streams (1) of openshift 4 - multiple consumers receive data from partition
Alibaba cloud server setup and pagoda panel connection
Final keyword and enumeration type