main
dugulingping 2023-10-25 00:26:36 +08:00
commit 71b3cd5d87
24 changed files with 1930 additions and 0 deletions

113
Bemfa_MQTT/Bemfa_MQTT.ino Normal file
View File

@ -0,0 +1,113 @@
/*
* google Assistent
* webapp
* QQ566565915
* onoff
* bemfa.com
*/
#include <ESP8266WiFi.h> //默认加载WIFI头文件
#include "PubSubClient.h" //默认加载MQTT库文件
//********************需要修改的部分*******************//
const char* ssid = "mdd520"; //修改你的路由去WIFI名字
const char* password = "mj1688888888"; //你的WIFI密码
#define ID_MQTT "ba6c540974354e998818b47472a8407d" //用户私钥,控制台获取
const char* topic = "lutaiValveSwitch006"; //主题名字,可在巴法云控制台自行创建,名称随意
const int B_led = 0; //单片机LED引脚值D系列是NodeMcu引脚命名方式其他esp8266型号将D2改为自己的引脚
//**************************************************//
const char* mqtt_server = "bemfa.com"; //默认MQTT服务器
const int mqtt_server_port = 9501; //默认MQTT服务器
WiFiClient espClient;
PubSubClient client(espClient);
//灯光函数及引脚定义
void turnOnLed();
void turnOffLed();
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Topic:");
Serial.println(topic);
String msg = "";
for (int i = 0; i < length; i++) {
msg += (char)payload[i];
}
Serial.print("Msg:");
Serial.println(msg);
if (msg == "on") {//如果接收字符on亮灯
turnOnLed();//开灯函数
} else if (msg == "off") {//如果接收字符off亮灯
turnOffLed();//关灯函数
}
msg = "";
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(ID_MQTT)) {
Serial.println("connected");
Serial.print("subscribe:");
Serial.println(topic);
//订阅主题如果需要订阅多个主题可发送多条订阅指令client.subscribe(topic2);client.subscribe(topic3);
client.subscribe(topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(B_led, OUTPUT); //设置引脚为输出模式
digitalWrite(B_led, HIGH);//默认引脚上电高电平
Serial.begin(115200); //设置波特率115200
setup_wifi(); //设置wifi的函数连接wifi
client.setServer(mqtt_server, mqtt_server_port);//设置mqtt服务器
client.setCallback(callback); //mqtt消息处理
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
//打开灯泡
void turnOnLed() {
Serial.println("turn on light");
digitalWrite(B_led, LOW);
}
//关闭灯泡
void turnOffLed() {
Serial.println("turn off light");
digitalWrite(B_led, HIGH);
}

590
Bemfa_MQTT/PubSubClient.cpp Normal file
View File

@ -0,0 +1,590 @@
/*
PubSubClient.cpp - A simple client for MQTT.
Nick O'Leary
http://knolleary.net
*/
#include "PubSubClient.h"
#include "Arduino.h"
PubSubClient::PubSubClient() {
this->_state = MQTT_DISCONNECTED;
this->_client = NULL;
this->stream = NULL;
setCallback(NULL);
}
PubSubClient::PubSubClient(Client& client) {
this->_state = MQTT_DISCONNECTED;
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(addr, port);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(addr,port);
setClient(client);
setStream(stream);
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(addr, port);
setCallback(callback);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(addr,port);
setCallback(callback);
setClient(client);
setStream(stream);
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(ip, port);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(ip,port);
setClient(client);
setStream(stream);
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(ip, port);
setCallback(callback);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(ip,port);
setCallback(callback);
setClient(client);
setStream(stream);
}
PubSubClient::PubSubClient(const char* domain, uint16_t port, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(domain,port);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(const char* domain, uint16_t port, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(domain,port);
setClient(client);
setStream(stream);
}
PubSubClient::PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client) {
this->_state = MQTT_DISCONNECTED;
setServer(domain,port);
setCallback(callback);
setClient(client);
this->stream = NULL;
}
PubSubClient::PubSubClient(const char* domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client& client, Stream& stream) {
this->_state = MQTT_DISCONNECTED;
setServer(domain,port);
setCallback(callback);
setClient(client);
setStream(stream);
}
boolean PubSubClient::connect(const char *id) {
return connect(id,NULL,NULL,0,0,0,0);
}
boolean PubSubClient::connect(const char *id, const char *user, const char *pass) {
return connect(id,user,pass,0,0,0,0);
}
boolean PubSubClient::connect(const char *id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage) {
return connect(id,NULL,NULL,willTopic,willQos,willRetain,willMessage);
}
boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage) {
if (!connected()) {
int result = 0;
if (domain != NULL) {
result = _client->connect(this->domain, this->port);
} else {
result = _client->connect(this->ip, this->port);
}
if (result == 1) {
nextMsgId = 1;
// Leave room in the buffer for header and variable length field
uint16_t length = 5;
unsigned int j;
#if MQTT_VERSION == MQTT_VERSION_3_1
uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p', MQTT_VERSION};
#define MQTT_HEADER_VERSION_LENGTH 9
#elif MQTT_VERSION == MQTT_VERSION_3_1_1
uint8_t d[7] = {0x00,0x04,'M','Q','T','T',MQTT_VERSION};
#define MQTT_HEADER_VERSION_LENGTH 7
#endif
for (j = 0;j<MQTT_HEADER_VERSION_LENGTH;j++) {
buffer[length++] = d[j];
}
uint8_t v;
if (willTopic) {
v = 0x06|(willQos<<3)|(willRetain<<5);
} else {
v = 0x02;
}
if(user != NULL) {
v = v|0x80;
if(pass != NULL) {
v = v|(0x80>>1);
}
}
buffer[length++] = v;
buffer[length++] = ((MQTT_KEEPALIVE) >> 8);
buffer[length++] = ((MQTT_KEEPALIVE) & 0xFF);
length = writeString(id,buffer,length);
if (willTopic) {
length = writeString(willTopic,buffer,length);
length = writeString(willMessage,buffer,length);
}
if(user != NULL) {
length = writeString(user,buffer,length);
if(pass != NULL) {
length = writeString(pass,buffer,length);
}
}
write(MQTTCONNECT,buffer,length-5);
lastInActivity = lastOutActivity = millis();
while (!_client->available()) {
unsigned long t = millis();
if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
_state = MQTT_CONNECTION_TIMEOUT;
_client->stop();
return false;
}
}
uint8_t llen;
uint16_t len = readPacket(&llen);
if (len == 4) {
if (buffer[3] == 0) {
lastInActivity = millis();
pingOutstanding = false;
_state = MQTT_CONNECTED;
return true;
} else {
_state = buffer[3];
}
}
_client->stop();
} else {
_state = MQTT_CONNECT_FAILED;
}
return false;
}
return true;
}
// reads a byte into result
boolean PubSubClient::readByte(uint8_t * result) {
uint32_t previousMillis = millis();
while(!_client->available()) {
uint32_t currentMillis = millis();
if(currentMillis - previousMillis >= ((int32_t) MQTT_SOCKET_TIMEOUT * 1000)){
return false;
}
}
*result = _client->read();
return true;
}
// reads a byte into result[*index] and increments index
boolean PubSubClient::readByte(uint8_t * result, uint16_t * index){
uint16_t current_index = *index;
uint8_t * write_address = &(result[current_index]);
if(readByte(write_address)){
*index = current_index + 1;
return true;
}
return false;
}
uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
uint16_t len = 0;
if(!readByte(buffer, &len)) return 0;
bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
uint32_t multiplier = 1;
uint16_t length = 0;
uint8_t digit = 0;
uint16_t skip = 0;
uint8_t start = 0;
do {
if(!readByte(&digit)) return 0;
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) != 0);
*lengthLength = len-1;
if (isPublish) {
// Read in topic length to calculate bytes to skip over for Stream writing
if(!readByte(buffer, &len)) return 0;
if(!readByte(buffer, &len)) return 0;
skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
start = 2;
if (buffer[0]&MQTTQOS1) {
// skip message id
skip += 2;
}
}
for (uint16_t i = start;i<length;i++) {
if(!readByte(&digit)) return 0;
if (this->stream) {
if (isPublish && len-*lengthLength-2>skip) {
this->stream->write(digit);
}
}
if (len < MQTT_MAX_PACKET_SIZE) {
buffer[len] = digit;
}
len++;
}
if (!this->stream && len > MQTT_MAX_PACKET_SIZE) {
len = 0; // This will cause the packet to be ignored.
}
return len;
}
boolean PubSubClient::loop() {
if (connected()) {
unsigned long t = millis();
if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) {
if (pingOutstanding) {
this->_state = MQTT_CONNECTION_TIMEOUT;
_client->stop();
return false;
} else {
buffer[0] = MQTTPINGREQ;
buffer[1] = 0;
_client->write(buffer,2);
lastOutActivity = t;
lastInActivity = t;
pingOutstanding = true;
}
}
if (_client->available()) {
uint8_t llen;
uint16_t len = readPacket(&llen);
uint16_t msgId = 0;
uint8_t *payload;
if (len > 0) {
lastInActivity = t;
uint8_t type = buffer[0]&0xF0;
if (type == MQTTPUBLISH) {
if (callback) {
uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2];
char topic[tl+1];
for (uint16_t i=0;i<tl;i++) {
topic[i] = buffer[llen+3+i];
}
topic[tl] = 0;
// msgId only present for QOS>0
if ((buffer[0]&0x06) == MQTTQOS1) {
msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
payload = buffer+llen+3+tl+2;
callback(topic,payload,len-llen-3-tl-2);
buffer[0] = MQTTPUBACK;
buffer[1] = 2;
buffer[2] = (msgId >> 8);
buffer[3] = (msgId & 0xFF);
_client->write(buffer,4);
lastOutActivity = t;
} else {
payload = buffer+llen+3+tl;
callback(topic,payload,len-llen-3-tl);
}
}
} else if (type == MQTTPINGREQ) {
buffer[0] = MQTTPINGRESP;
buffer[1] = 0;
_client->write(buffer,2);
} else if (type == MQTTPINGRESP) {
pingOutstanding = false;
}
}
}
return true;
}
return false;
}
boolean PubSubClient::publish(const char* topic, const char* payload) {
return publish(topic,(const uint8_t*)payload,strlen(payload),false);
}
boolean PubSubClient::publish(const char* topic, const char* payload, boolean retained) {
return publish(topic,(const uint8_t*)payload,strlen(payload),retained);
}
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength) {
return publish(topic, payload, plength, false);
}
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength, boolean retained) {
if (connected()) {
if (MQTT_MAX_PACKET_SIZE < 5 + 2+strlen(topic) + plength) {
// Too long
return false;
}
// Leave room in the buffer for header and variable length field
uint16_t length = 5;
length = writeString(topic,buffer,length);
uint16_t i;
for (i=0;i<plength;i++) {
buffer[length++] = payload[i];
}
uint8_t header = MQTTPUBLISH;
if (retained) {
header |= 1;
}
return write(header,buffer,length-5);
}
return false;
}
boolean PubSubClient::publish_P(const char* topic, const uint8_t* payload, unsigned int plength, boolean retained) {
uint8_t llen = 0;
uint8_t digit;
unsigned int rc = 0;
uint16_t tlen;
unsigned int pos = 0;
unsigned int i;
uint8_t header;
unsigned int len;
if (!connected()) {
return false;
}
tlen = strlen(topic);
header = MQTTPUBLISH;
if (retained) {
header |= 1;
}
buffer[pos++] = header;
len = plength + 2 + tlen;
do {
digit = len % 128;
len = len / 128;
if (len > 0) {
digit |= 0x80;
}
buffer[pos++] = digit;
llen++;
} while(len>0);
pos = writeString(topic,buffer,pos);
rc += _client->write(buffer,pos);
for (i=0;i<plength;i++) {
rc += _client->write((char)pgm_read_byte_near(payload + i));
}
lastOutActivity = millis();
return rc == tlen + 4 + plength;
}
boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
uint8_t lenBuf[4];
uint8_t llen = 0;
uint8_t digit;
uint8_t pos = 0;
uint16_t rc;
uint16_t len = length;
do {
digit = len % 128;
len = len / 128;
if (len > 0) {
digit |= 0x80;
}
lenBuf[pos++] = digit;
llen++;
} while(len>0);
buf[4-llen] = header;
for (int i=0;i<llen;i++) {
buf[5-llen+i] = lenBuf[i];
}
#ifdef MQTT_MAX_TRANSFER_SIZE
uint8_t* writeBuf = buf+(4-llen);
uint16_t bytesRemaining = length+1+llen; //Match the length type
uint8_t bytesToWrite;
boolean result = true;
while((bytesRemaining > 0) && result) {
bytesToWrite = (bytesRemaining > MQTT_MAX_TRANSFER_SIZE)?MQTT_MAX_TRANSFER_SIZE:bytesRemaining;
rc = _client->write(writeBuf,bytesToWrite);
result = (rc == bytesToWrite);
bytesRemaining -= rc;
writeBuf += rc;
}
return result;
#else
rc = _client->write(buf+(4-llen),length+1+llen);
lastOutActivity = millis();
return (rc == 1+llen+length);
#endif
}
boolean PubSubClient::subscribe(const char* topic) {
return subscribe(topic, 0);
}
boolean PubSubClient::subscribe(const char* topic, uint8_t qos) {
if (qos < 0 || qos > 1) {
return false;
}
if (MQTT_MAX_PACKET_SIZE < 9 + strlen(topic)) {
// Too long
return false;
}
if (connected()) {
// Leave room in the buffer for header and variable length field
uint16_t length = 5;
nextMsgId++;
if (nextMsgId == 0) {
nextMsgId = 1;
}
buffer[length++] = (nextMsgId >> 8);
buffer[length++] = (nextMsgId & 0xFF);
length = writeString((char*)topic, buffer,length);
buffer[length++] = qos;
return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-5);
}
return false;
}
boolean PubSubClient::unsubscribe(const char* topic) {
if (MQTT_MAX_PACKET_SIZE < 9 + strlen(topic)) {
// Too long
return false;
}
if (connected()) {
uint16_t length = 5;
nextMsgId++;
if (nextMsgId == 0) {
nextMsgId = 1;
}
buffer[length++] = (nextMsgId >> 8);
buffer[length++] = (nextMsgId & 0xFF);
length = writeString(topic, buffer,length);
return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-5);
}
return false;
}
void PubSubClient::disconnect() {
buffer[0] = MQTTDISCONNECT;
buffer[1] = 0;
_client->write(buffer,2);
_state = MQTT_DISCONNECTED;
_client->stop();
lastInActivity = lastOutActivity = millis();
}
uint16_t PubSubClient::writeString(const char* string, uint8_t* buf, uint16_t pos) {
const char* idp = string;
uint16_t i = 0;
pos += 2;
while (*idp) {
buf[pos++] = *idp++;
i++;
}
buf[pos-i-2] = (i >> 8);
buf[pos-i-1] = (i & 0xFF);
return pos;
}
boolean PubSubClient::connected() {
boolean rc;
if (_client == NULL ) {
rc = false;
} else {
rc = (int)_client->connected();
if (!rc) {
if (this->_state == MQTT_CONNECTED) {
this->_state = MQTT_CONNECTION_LOST;
_client->flush();
_client->stop();
}
}
}
return rc;
}
PubSubClient& PubSubClient::setServer(uint8_t * ip, uint16_t port) {
IPAddress addr(ip[0],ip[1],ip[2],ip[3]);
return setServer(addr,port);
}
PubSubClient& PubSubClient::setServer(IPAddress ip, uint16_t port) {
this->ip = ip;
this->port = port;
this->domain = NULL;
return *this;
}
PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
this->domain = domain;
this->port = port;
return *this;
}
PubSubClient& PubSubClient::setCallback(MQTT_CALLBACK_SIGNATURE) {
this->callback = callback;
return *this;
}
PubSubClient& PubSubClient::setClient(Client& client){
this->_client = &client;
return *this;
}
PubSubClient& PubSubClient::setStream(Stream& stream){
this->stream = &stream;
return *this;
}
int PubSubClient::state() {
return this->_state;
}

144
Bemfa_MQTT/PubSubClient.h Normal file
View File

@ -0,0 +1,144 @@
/*
PubSubClient.h - A simple client for MQTT.
Nick O'Leary
http://knolleary.net
*/
#ifndef PubSubClient_h
#define PubSubClient_h
#include <Arduino.h>
#include "IPAddress.h"
#include "Client.h"
#include "Stream.h"
#define MQTT_VERSION_3_1 3
#define MQTT_VERSION_3_1_1 4
// MQTT_VERSION : Pick the version
//#define MQTT_VERSION MQTT_VERSION_3_1
#ifndef MQTT_VERSION
#define MQTT_VERSION MQTT_VERSION_3_1_1
#endif
// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 128
#endif
// MQTT_KEEPALIVE : keepAlive interval in Seconds
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 15
#endif
// MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds
#ifndef MQTT_SOCKET_TIMEOUT
#define MQTT_SOCKET_TIMEOUT 15
#endif
// MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client
// in each write call. Needed for the Arduino Wifi Shield. Leave undefined to
// pass the entire MQTT packet in each write call.
//#define MQTT_MAX_TRANSFER_SIZE 80
// Possible values for client.state()
#define MQTT_CONNECTION_TIMEOUT -4
#define MQTT_CONNECTION_LOST -3
#define MQTT_CONNECT_FAILED -2
#define MQTT_DISCONNECTED -1
#define MQTT_CONNECTED 0
#define MQTT_CONNECT_BAD_PROTOCOL 1
#define MQTT_CONNECT_BAD_CLIENT_ID 2
#define MQTT_CONNECT_UNAVAILABLE 3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED 5
#define MQTTCONNECT 1 << 4 // Client request to connect to Server
#define MQTTCONNACK 2 << 4 // Connect Acknowledgment
#define MQTTPUBLISH 3 << 4 // Publish message
#define MQTTPUBACK 4 << 4 // Publish Acknowledgment
#define MQTTPUBREC 5 << 4 // Publish Received (assured delivery part 1)
#define MQTTPUBREL 6 << 4 // Publish Release (assured delivery part 2)
#define MQTTPUBCOMP 7 << 4 // Publish Complete (assured delivery part 3)
#define MQTTSUBSCRIBE 8 << 4 // Client Subscribe request
#define MQTTSUBACK 9 << 4 // Subscribe Acknowledgment
#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request
#define MQTTUNSUBACK 11 << 4 // Unsubscribe Acknowledgment
#define MQTTPINGREQ 12 << 4 // PING Request
#define MQTTPINGRESP 13 << 4 // PING Response
#define MQTTDISCONNECT 14 << 4 // Client is Disconnecting
#define MQTTReserved 15 << 4 // Reserved
#define MQTTQOS0 (0 << 1)
#define MQTTQOS1 (1 << 1)
#define MQTTQOS2 (2 << 1)
#ifdef ESP8266
#include <functional>
#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback
#else
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)
#endif
class PubSubClient {
private:
Client* _client;
uint8_t buffer[MQTT_MAX_PACKET_SIZE];
uint16_t nextMsgId;
unsigned long lastOutActivity;
unsigned long lastInActivity;
bool pingOutstanding;
MQTT_CALLBACK_SIGNATURE;
uint16_t readPacket(uint8_t*);
boolean readByte(uint8_t * result);
boolean readByte(uint8_t * result, uint16_t * index);
boolean write(uint8_t header, uint8_t* buf, uint16_t length);
uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos);
IPAddress ip;
const char* domain;
uint16_t port;
Stream* stream;
int _state;
public:
PubSubClient();
PubSubClient(Client& client);
PubSubClient(IPAddress, uint16_t, Client& client);
PubSubClient(IPAddress, uint16_t, Client& client, Stream&);
PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);
PubSubClient(uint8_t *, uint16_t, Client& client);
PubSubClient(uint8_t *, uint16_t, Client& client, Stream&);
PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);
PubSubClient(const char*, uint16_t, Client& client);
PubSubClient(const char*, uint16_t, Client& client, Stream&);
PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);
PubSubClient& setServer(IPAddress ip, uint16_t port);
PubSubClient& setServer(uint8_t * ip, uint16_t port);
PubSubClient& setServer(const char * domain, uint16_t port);
PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE);
PubSubClient& setClient(Client& client);
PubSubClient& setStream(Stream& stream);
boolean connect(const char* id);
boolean connect(const char* id, const char* user, const char* pass);
boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
void disconnect();
boolean publish(const char* topic, const char* payload);
boolean publish(const char* topic, const char* payload, boolean retained);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
boolean subscribe(const char* topic);
boolean subscribe(const char* topic, uint8_t qos);
boolean unsubscribe(const char* topic);
boolean loop();
boolean connected();
int state();
};
#endif

20
Blink/Blink.ino Normal file
View File

@ -0,0 +1,20 @@
/*
* @Author: dugulingping
* @Date: 2022-04-13 03:06:22
* @LastEditTime: 2022-05-22 19:55:46
* @LastEditors: dugulingping
* @Description: testLED
* @FilePath: \test\Blink\Blink.ino
*/
int LED = 2;
void setup(){
pinMode(LED,OUTPUT);
digitalWrite(LED,0);
}
void loop(){
digitalWrite(LED,1);
delay(1000);
digitalWrite(LED,0);
delay(1000);
}

BIN
Blink/Blink.ino.nodemcu.bin Normal file

Binary file not shown.

29
ButtonLED/ButtonLED.ino Normal file
View File

@ -0,0 +1,29 @@
/*
* @Author: dugulingping
* @Date: 2022-04-14 17:39:45
* @LastEditTime: 2022-06-17 23:19:00
* @LastEditors: dugulingping
* @Description: ButtonLED
* @FilePath: \test\ButtonLED\ButtonLED.ino
*/
#define LED 2
#define LED2 5
#define BUTTON 12
void setup(){
pinMode(LED,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(BUTTON,INPUT_PULLUP);
digitalWrite(LED,HIGH);
}
void loop(){
if(digitalRead(BUTTON)==LOW){
digitalWrite(LED,LOW);
digitalWrite(LED2,HIGH);
}
else{
digitalWrite(LED,HIGH);
digitalWrite(LED2,LOW);
}
}

50
DHT11/DHT11.ino Normal file
View File

@ -0,0 +1,50 @@
/*
* @Author: dugulingping
* @Date: 2022-04-15 21:25:51
* @LastEditTime: 2022-05-23 16:57:02
* @LastEditors: dugulingping
* @Description: DHT11
* @FilePath: \test\DHT11\DHT11.ino
*/
#include "DHT.h"
#define DHTPIN 4
#define DHTTYPE DHT22 // DHT 11`
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println(F("\nDHT11 test!"));
dht.begin();
}
void loop() {
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature(false);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)){
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("湿度: "));
Serial.print(h);
Serial.print(F("%\t温度: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(F("\t体感温度: "));
Serial.print(hic);
Serial.print(F("°C \n"));
}

116
DHTdisplay/DHTdisplay.ino Normal file
View File

@ -0,0 +1,116 @@
/*
* @Author: dugulingping
* @Date: 2022-04-17 16:00:40
* @LastEditTime: 2022-05-23 16:57:11
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\DHTdisplay\DHTdisplay.ino
*/
#include "DHT.h"
// DHT11
#define DHTPIN 4
#define DHTTYPE DHT22 // DHT 11
//LED
#define SCLK 14
#define RCLK 13
#define DIO 15
DHT dht(DHTPIN, DHTTYPE);
//定义字库
unsigned char LED_0F[] = {
// 0 1 2 3 4 5 6 7 8 9 A b C d E F -
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x8C,0xBF,0xC6,0xA1,0x86,0xFF,0xbf
};
//定义位
unsigned char LED_BIT[] = {
// 1 2 3 4 1+2 3+4 1~4
0x01,0x02,0x04,0x08,0x03,0x0C,0x0F
};
//定义dht数据
int dhtdata[3] = {0};
void setup() {
Serial.begin(115200);
dht.begin();
//让三个脚都是输出状态
pinMode(SCLK,OUTPUT);
pinMode(RCLK,OUTPUT);
pinMode(DIO,OUTPUT);
}
//定时
int delay_date = 0;
void loop() {
if(delay_date < 2000){
delay_date+=4;
}else{
delay_date = 0;
DHT_Data();
}
if(!dhtdata[1]||!dhtdata[2]){
LED_display(LED_BIT[6], 0xBF);
return;
}
int num1 = dhtdata[0]%10;
int num2 = dhtdata[0]/10;
int num3 = dhtdata[2]%10;
int num4 = dhtdata[2]/10;
LED_display(LED_BIT[2], LED_0F[num1]-128);
LED_display(LED_BIT[3], LED_0F[num2]);
LED_display(LED_BIT[0], LED_0F[num3]-128);
LED_display(LED_BIT[1], LED_0F[num4]);
//LED_display(LED_BIT[2], LED_0F[data_split(dhtdata[0])[0]]-128);
//LED_display(LED_BIT[1], LED_0F[data_split(dhtdata[2])[1]]);
//LED_display(LED_BIT[0], LED_0F[data_split(dhtdata[2])[0]]);
}
void LED_display(unsigned char bit, unsigned char digit ){
LED_OUT(digit);
LED_OUT(bit);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(1);
}
void LED_OUT(unsigned char X){
unsigned char i;
for(i=8;i>=1;i--)
{
if(X&0x80)
digitalWrite(DIO,HIGH);
else
digitalWrite(DIO,LOW);
X<<=1;
digitalWrite(SCLK,LOW);
digitalWrite(SCLK,HIGH);
}
}
int * data_split(int num){
int res[2] = {0};
for(int i = 0; num > 0; i++){
res[i] = num%10;
}
return res;
}
void DHT_Data(){
float h = dht.readHumidity();
float t = dht.readTemperature(false);
float hic = dht.computeHeatIndex(t, h, false);
if (isnan(h) || isnan(t)){
Serial.println(F("Failed to read from DHT sensor!"));
dhtdata[0] = 0;
dhtdata[1] = 0;
dhtdata[2] = 0;
return;
}
dhtdata[0] = h;
dhtdata[1] = t;
dhtdata[2] = hic;
Serial.println(h);
}

21
SerialTest/SerialTest.ino Normal file
View File

@ -0,0 +1,21 @@
/*
* @Author: dugulingping
* @Date: 2022-04-15 11:26:46
* @LastEditTime: 2022-04-15 15:40:53
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\SerialTest\SerialTest.ino
*/
void setup(){
Serial.begin(115200);
Serial.println("hello world");
}
void loop(){
for(int i = 0; i < 100; i++){
Serial.println(i);
delay(500);
}
}

30
ServoTest/ServoTest.ino Normal file
View File

@ -0,0 +1,30 @@
/*
* @Author: dugulingping
* @Date: 2022-04-14 19:52:10
* @LastEditTime: 2022-04-14 20:23:57
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\ServoTest\ServoTest.ino
*/
#include <Servo.h>
Servo myservo;
void setup(){
myservo.attach(4);
}
void loop(){
int pos;
for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 90; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

View File

@ -0,0 +1,46 @@
/*
* @Author: dugulingping
* @Date: 2022-06-09 17:14:49
* @LastEditTime: 2022-06-16 15:35:00
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\SmartComfigWIFI\SmartComfigWIFI.ino
*/
#include <ESP8266WiFi.h>
void smartConfig()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA); //设置WIFI模块为STA模式
Serial.println("\r\nWaiting for connection");
//smartconfig进行初始化
WiFi.beginSmartConfig();
while (1) //等待连接成功
{
Serial.print(">");
digitalWrite(LED_BUILTIN, 0);
delay(100);
digitalWrite(LED_BUILTIN, 1);
delay(100);
//如果连接成功后就打印出连接的WIFI信息
if (WiFi.smartConfigDone())
{
Serial.println("SmartConfig Success");
Serial.printf("SSID:%s", WiFi.SSID().c_str());
Serial.printf("PW:%s", WiFi.psk().c_str());//打印出密码
break;
}
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
smartConfig();
}
void loop() {
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
delay(1000); // Wait for a second
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
delay(1000); // Wait for two seconds (to demonstrate the active low LED)
}

View File

@ -0,0 +1,4 @@
1、库文件使用请将库文件解压后以文件夹格式拖至Arduino文件夹下的Libraries文件夹里。
C:\Program Files (x86)\Arduino\libraries
无库文件的为Arduino IDE自带库无需添加。
2、原理图与技术手册为厂家提供仅供参考使用不提供技术支持。

28
analogLED/analogLED.ino Normal file
View File

@ -0,0 +1,28 @@
/*
* @Author: dugulingping
* @Date: 2022-04-14 18:00:26
* @LastEditTime: 2022-04-15 17:05:34
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\analogLED\analogLED.ino
*/
#define LEDMAX 256
#define LEDMIN 0
#define LED 4
void setup(){
pinMode(LED,OUTPUT);
digitalWrite(LED,0);
}
void loop(){
for(int i = LEDMIN; i <= LEDMAX; i++){
analogWrite(LED,i);
delay(5);
}
for(int i = LEDMAX; i >= LEDMIN; i--){
analogWrite(LED,i);
delay(5);
}
delay(300);
}

50
colorLED/colorLED.ino Normal file
View File

@ -0,0 +1,50 @@
/*
* @Author: dugulingping
* @Date: 2022-04-21 18:35:09
* @LastEditTime: 2022-04-22 14:57:29
* @LastEditors: dugulingping
* @Description: colorLED
* @FilePath: \test\colorLED\colorLED.ino
*/
#define RED 5
#define GREEN 4
#define BLUE 14
void RGBLed(unsigned char red, unsigned char green, unsigned char blue, bool type);
void setup(){
pinMode(RED,OUTPUT);
pinMode(GREEN,OUTPUT);
pinMode(BLUE,OUTPUT);
digitalWrite(RED,1);
digitalWrite(GREEN,1);
digitalWrite(BLUE,1);
}
void loop(){
int rgbColour[3];
rgbColour[0] = 255;
rgbColour[1] = 0;
rgbColour[2] = 0;
for (int decColour = 0; decColour < 3; decColour += 1) {
int incColour = decColour == 2 ? 0 : decColour + 1;
for(int i = 0; i < 255; i += 1) {
rgbColour[decColour] -= 1;
rgbColour[incColour] += 1;
RGBLed(rgbColour[0], rgbColour[1], rgbColour[2],true);
delay(10);
}
}
}
void RGBLed(unsigned char red, unsigned char green, unsigned char blue, bool type = false){
//处理共阳RGB LED
if(type){
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
}
analogWrite(RED, red);
analogWrite(GREEN, green);
analogWrite(BLUE, blue);
}

37
iicAddress/iicAddress.ino Normal file
View File

@ -0,0 +1,37 @@
/*
* @Author: dugulingping
* @Date: 2022-05-27 03:22:20
* @LastEditTime: 2022-05-27 03:58:45
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\iicAddress\iicAddress.ino
*/
#include <Wire.h>
/**
* SCL <--> D1
* SDA <--> D2
*/
//0x3C
void setup(){
Wire.begin(4, 5);
Serial.begin(9600);
Serial.println("\nI2C Scanner");
}
void loop(){
Serial.println("Scanning...");
for(int address = 1; address < 127; address++){
Wire.beginTransmission(address);
byte code = Wire.endTransmission();
if (code == 0) {
Serial.print("Found: 0x");
Serial.println(address, HEX);
}
}
delay(5000);
}

View File

@ -0,0 +1,225 @@
/*
1.PC connect the wifi : tunc5555
password :123456789
2.Browser open: http://192.168.4.1/
3.click the on or off button
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#define USE_SERIAL Serial
static const char ssid[] = "tunc5555";
static const char password[] = "123456789";
MDNSResponder mdns;
static void writeLED(bool);
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
<title>ESP8266 WebSocket Demo</title>
<style>
"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }"
</style>
<script>
var websock;
function start() {
websock = new WebSocket('ws://' + window.location.hostname + ':81/');
websock.onopen = function(evt) { console.log('websock open'); };
websock.onclose = function(evt) { console.log('websock close'); };
websock.onerror = function(evt) { console.log(evt); };
websock.onmessage = function(evt) {
console.log(evt);
var e = document.getElementById('ledstatus');
if (evt.data === 'ledon') {
e.style.color = 'red';
}
else if (evt.data === 'ledoff') {
e.style.color = 'black';
}
else {
console.log('unknown event');
}
};
}
function buttonclick(e) {
websock.send(e.id);
}
</script>
</head>
<body onload="javascript:start();">
<h1>ESP8266 WebSocket Demo</h1>
<div id="ledstatus"><b>LED</b></div>
<button id="ledon" type="button" onclick="buttonclick(this);">On</button>
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 0;
// Current LED status
bool LEDStatus;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
USE_SERIAL.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
switch (type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[%u] Disconnected!\r\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// Send the current LED status
if (LEDStatus) {
webSocket.sendTXT(num, LEDON, strlen(LEDON));
}
else {
webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
}
}
break;
case WStype_TEXT:
USE_SERIAL.printf("[%u] get Text: %s\r\n", num, payload);
if (strcmp(LEDON, (const char *)payload) == 0) {
writeLED(true);
}
else if (strcmp(LEDOFF, (const char *)payload) == 0) {
writeLED(false);
}
else {
USE_SERIAL.println("Unknown command");
}
// send data to all connected clients
webSocket.broadcastTXT(payload, length);
break;
case WStype_BIN:
USE_SERIAL.printf("[%u] get binary length: %u\r\n", num, length);
hexdump(payload, length);
// echo data back to browser
webSocket.sendBIN(num, payload, length);
break;
default:
USE_SERIAL.printf("Invalid WStype [%d]\r\n", type);
break;
}
}
void handleRoot()
{
server.send_P(200, "text/html", INDEX_HTML);
}
void handleNotFound()
{
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
static void writeLED(bool LEDon)
{
LEDStatus = LEDon;
// Note inverted logic for Adafruit HUZZAH board
if (LEDon) {
digitalWrite(LEDPIN, 0);
}
else {
digitalWrite(LEDPIN, 1);
}
}
void setup()
{
pinMode(LEDPIN, OUTPUT);
writeLED(false);
USE_SERIAL.begin(115200);
//Serial.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for (uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\r\n", t);
USE_SERIAL.flush();
delay(1000);
}
// WiFiMulti.addAP(ssid, password);
//
// while (WiFiMulti.run() != WL_CONNECTED) {
// Serial.print(".");
// delay(100);
// }
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
USE_SERIAL.print("AP IP address: ");
USE_SERIAL.println(myIP);
USE_SERIAL.println("");
USE_SERIAL.print("Connected to ");
USE_SERIAL.println(ssid);
USE_SERIAL.print("IP address: ");
USE_SERIAL.println(WiFi.localIP());
if (mdns.begin("espWebSock", WiFi.localIP())) {
USE_SERIAL.println("MDNS responder started");
mdns.addService("http", "tcp", 80);
mdns.addService("ws", "tcp", 81);
}
else {
USE_SERIAL.println("MDNS.begin failed");
}
USE_SERIAL.print("Connect to http://espWebSock.local or http://");
USE_SERIAL.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop()
{
webSocket.loop();
server.handleClient();
}

227
relay-esp01s/ESPWebSock.ino Normal file
View File

@ -0,0 +1,227 @@
/*
* ESP8266 Web server with Web Socket to control an LED.
*
* The web server keeps all clients' LED status up to date and any client may
* turn the LED on or off.
*
* For example, clientA connects and turns the LED on. This changes the word
* "LED" on the web page to the color red. When clientB connects, the word
* "LED" will be red since the server knows the LED is on. When clientB turns
* the LED off, the word LED changes color to black on clientA and clientB web
* pages.
*
* References:
*
* https://github.com/Links2004/arduinoWebSockets
*
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
static const char ssid[] = "***********";
static const char password[] = "*************";
MDNSResponder mdns;
static void writeLED(bool);
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
<title>ESP8266 WebSocket Demo</title>
<style>
"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }"
</style>
<script>
var websock;
function start() {
websock = new WebSocket('ws://' + window.location.hostname + ':81/');
websock.onopen = function(evt) { console.log('websock open'); };
websock.onclose = function(evt) { console.log('websock close'); };
websock.onerror = function(evt) { console.log(evt); };
websock.onmessage = function(evt) {
console.log(evt);
var e = document.getElementById('ledstatus');
if (evt.data === 'ledon') {
e.style.color = 'red';
}
else if (evt.data === 'ledoff') {
e.style.color = 'black';
}
else {
console.log('unknown event');
}
};
}
function buttonclick(e) {
websock.send(e.id);
}
</script>
</head>
<body onload="javascript:start();">
<h1>ESP8266 WebSocket Demo</h1>
<div id="ledstatus"><b>LED</b></div>
<button id="ledon" type="button" onclick="buttonclick(this);">On</button>
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 0;
// Current LED status
bool LEDStatus;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\r\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// Send the current LED status
if (LEDStatus) {
webSocket.sendTXT(num, LEDON, strlen(LEDON));
}
else {
webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
}
}
break;
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\r\n", num, payload);
if (strcmp(LEDON, (const char *)payload) == 0) {
writeLED(true);
}
else if (strcmp(LEDOFF, (const char *)payload) == 0) {
writeLED(false);
}
else {
Serial.println("Unknown command");
}
// send data to all connected clients
webSocket.broadcastTXT(payload, length);
break;
case WStype_BIN:
Serial.printf("[%u] get binary length: %u\r\n", num, length);
hexdump(payload, length);
// echo data back to browser
webSocket.sendBIN(num, payload, length);
break;
default:
Serial.printf("Invalid WStype [%d]\r\n", type);
break;
}
}
void handleRoot()
{
server.send_P(200, "text/html", INDEX_HTML);
}
void handleNotFound()
{
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
static void writeLED(bool LEDon)
{
LEDStatus = LEDon;
// Note inverted logic for Adafruit HUZZAH board
if (LEDon) {
digitalWrite(LEDPIN, 0);
}
else {
digitalWrite(LEDPIN, 1);
}
}
void setup()
{
pinMode(LEDPIN, OUTPUT);
writeLED(false);
Serial.begin(115200);
//Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
for(uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password);
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("espWebSock", WiFi.localIP())) {
Serial.println("MDNS responder started");
mdns.addService("http", "tcp", 80);
mdns.addService("ws", "tcp", 81);
}
else {
Serial.println("MDNS.begin failed");
}
Serial.print("Connect to http://espWebSock.local or http://");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop()
{
webSocket.loop();
server.handleClient();
}

81
shumaguan/shumaguan.ino Normal file
View File

@ -0,0 +1,81 @@
unsigned char LED_0F[] = {// 0 1 2 3 4 5 6 7 8 9 A b C d E F -
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x8C,0xBF,0xC6,0xA1,0x86,0xFF,0xbf
};
unsigned char LED[4]; //用于LED的4位显示缓存
int SCLK = 14;
int RCLK = 13;
int DIO = 15; //这里定义了那三个脚
void setup ()
{
pinMode(SCLK,OUTPUT);
pinMode(RCLK,OUTPUT);
pinMode(DIO,OUTPUT); //让三个脚都是输出状态
}
void loop()
{
LED[0]=random(9);
LED[1]=random(9);
LED[2]=random(9);
LED[3]=random(9);
LED4_Display ();
}
void LED4_Display (void)
{
unsigned char *led_table; // 查表指针
unsigned char i;
//显示第1位
led_table = LED_0F + LED[0];
i = *led_table;
LED_OUT(i);
LED_OUT(0x01);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(10);
//显示第2位
led_table = LED_0F + LED[1];
i = *led_table;
LED_OUT(i);
LED_OUT(0x02);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(10);
//显示第3位
led_table = LED_0F + LED[2];
i = *led_table;
LED_OUT(i);
LED_OUT(0x04);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(10);
//显示第4位
led_table = LED_0F + LED[3];
i = *led_table;
LED_OUT(i);
LED_OUT(0x08);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(10);
}
void LED_OUT(unsigned char X)
{
unsigned char i;
for(i=8;i>=1;i--)
{
if (X&0x80)
{
digitalWrite(DIO,HIGH);
}
else
{
digitalWrite(DIO,LOW);
}
X<<=1;
digitalWrite(SCLK,LOW);
digitalWrite(SCLK,HIGH);
}
}

119
turangshidu/turangshidu.ino Normal file
View File

@ -0,0 +1,119 @@
/*
* @Author: dugulingping
* @Date: 2022-06-09 16:14:32
* @LastEditTime: 2022-06-12 23:28:17
* @LastEditors: dugulingping
* @Description:
* @FilePath: \test\turangshidu\turangshidu.ino
*/
// 定义字库
unsigned char LED_0F[] = {
// 0 1 2 3 4 5 6 7 8 9 A b C d E F -
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x8C,0xBF,0xC6,0xA1,0x86,0xFF,0xbf
};
// 定义位
unsigned char LED_BIT[] = {
// 1 2 3 4 1+2 3+4 1~4
0x01,0x02,0x04,0x08,0x03,0x0C,0x0F
};
// 土壤湿度
#define PIN_AO A0
#define PIN_DO 4
// LED
#define SCLK 14
#define RCLK 13
#define DIO 15
int M0 = 1024; // 在空气中AO读取的值最大为1024代表干燥时的读数
int M1 = 550; // 浸泡在水里的最小值 550 最小值会改变代表100%湿度
int data[2] = {0};
void setup(){
pinMode(PIN_AO, INPUT);
pinMode(PIN_DO, INPUT);
// 让三个脚都是输出状态
pinMode(SCLK,OUTPUT);
pinMode(RCLK,OUTPUT);
pinMode(DIO,OUTPUT);
Serial.begin(115200);
}
int delay_date = 0; // 定时
void loop(){
if(delay_date < 2000){
delay_date += 4;
delay(4);
}else{
delay_date = 0;
soilMoisture();
}
if(!data[0]){
LED_display(LED_BIT[6], 0xBF);
return;
}
// 模拟量
int num1 = data[0] / 1000;
int num2 = data[0] / 100 % 10;
int num3 = data[0] / 10 % 10;
int num4 = data[0] % 10;
LED_display(LED_BIT[3], LED_0F[num1]);
LED_display(LED_BIT[2], LED_0F[num2]);
LED_display(LED_BIT[1], LED_0F[num3]);
LED_display(LED_BIT[0], LED_0F[num4]);
// delay(3000);
// num1 = data[1] / 10;
// num2 = data[1] % 10;
// LED_display(LED_BIT[0], LED_0F[0xBF]);
// LED_display(LED_BIT[1], LED_0F[0xBF]);
// LED_display(LED_BIT[2], LED_0F[num1]-128);
// LED_display(LED_BIT[3], LED_0F[num2]);
// delay(3000);
}
void soilMoisture(){
data[0] = analogRead(PIN_AO);
Serial.print("AO:");
Serial.println(data[0]);
Serial.print("DO=");
Serial.println(digitalRead(PIN_DO));
float HUMI = (M0 - analogRead(PIN_AO)) / ((M0 - M1) / 100); // 将湿度模拟量转换成数字量
Serial.print("HUMI= ");
Serial.print(HUMI);
Serial.println("% ");
data[1] = HUMI;
}
void LED_display(unsigned char bit, unsigned char digit ){
LED_OUT(digit);
LED_OUT(bit);
digitalWrite(RCLK,LOW);
digitalWrite(RCLK,HIGH);
delay(1);
}
void LED_OUT(unsigned char X){
unsigned char i;
for(i=8;i>=1;i--)
{
if(X&0x80)
digitalWrite(DIO,HIGH);
else
digitalWrite(DIO,LOW);
X<<=1;
digitalWrite(SCLK,LOW);
digitalWrite(SCLK,HIGH);
}
}