Article Catalog

  • Introduction to Hardware ESP8266
  • Configure Arduino environment
  • Configure Alibaba Cloud
  • Connect ESP8266


1 Introduction to Hardware ESP8266

The ESP8266 chip is a serial to wireless module chip with built-in firmware, making it easy for users to operate and eliminating the need to write timing signals. I used the ESP8266-12F series for this experiment. This chip uses a 3.3V DC power supply, has a small size, low power consumption, supports transparent transmission, does not cause serious packet loss, and is priced low. ESP8266 also allows users to write their own ROMs, which can not only achieve data transmission functions, but also control the establishment of WiFi hotspots, or connect to a designated router as a WiFi client. It can also programmatically control all GPIOs.



2 Configure Arduino environment

2.1 Preferences settings

Open Arduino, click on “File” - “Preferences”, and change the development board manager address:http://arduino.esp8266.com/stable/package_esp8266com_index.json

2.2 Add ESP8266 module support

Click on “Tools” - “Development Board: Arduino UNO” - “Development Board Manager”, search for “esp8266”, find the corresponding one, and click download and install.

Click on “Project” - “Load Library” - “Manage Library Interface”

Search for “PubSubClient” and locate “EspMQTTclient” for installation

2.4 Modify PubSubClient source file

Find the location of the “library” of Arduino through “Preferences”

Open the PubSubClient. h file

Configuration modification as shown in the figure

1
2
3
4
5
6
7
8
9
// MQTT_MAX_PACKET_SIZE : Maximum packet size. Override with setBufferSize().
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 1024
#endif

// MQTT_KEEPALIVE : keepAlive interval in Seconds. Override with setKeepAlive()
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 30
#endif

2.5 Arduino Json & U8g2lib

Install ArduinoJson

Install U8g2



3 Configure Alibaba Cloud

Search for “Internet of Things Platform” on Alibaba Cloud and select it. Click on “Management Console” to enter the console

Click on “Public Instance” in the console

On the left side, there is a “Device Management” option. Click on “Product” and then click on “Create Product”

Click on the project to enter and add a new product to the project, successfully creating it and obtaining ternary information

Create a device “pre test”

“Edit Draft” - “Add Custom Features”, add controls for the main light switch function and potentiometer function

Added successfully



4 Connect ESP8266

Using code reference, modify and compile the code successfully. Modify the code based on the ternary information of the device and select the mobile hotspot in WiFi, which avoids the problem of requiring user account login on the campus network and allows for quick viewing of the device status connected to the hotspot on the mobile end.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

#include <aliyun_mqtt.h>


#define SENSOR_PIN 13 //pin define
#define LED D4
#define LED2 D5
#define PRODUCT_KEY "a1d9dhNb6fp"//exchange PRODUCT_KEY
#define DEVICE_NAME "led1"//exchange DEVICE_NAME
#define DEVICE_SECRET "82b6da7e47de212fb63918ba3717a1e0"//exchange DEVICE_SECRET

#define DEV_VERSION "S-TH-WIFI-v1.0-20190220"

#define WIFI_SSID "abc"//exchange WIFI
#define WIFI_PASSWD "hl20011115"//exchange WIFI password

#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"%s\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
#define ALINK_TOPIC_PROP_POSTRSP "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post_reply"
#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
#define ALINK_METHOD_PROP_POST "thing.event.property.post"
#define ALINK_TOPIC_DEV_INFO "/ota/device/inform/" PRODUCT_KEY "/" DEVICE_NAME ""
#define ALINK_VERSION_FROMA "{\"id\": 123,\"params\": {\"version\": \"%s\"}}"
unsigned long lastMs = 0;
int val=0;

WiFiClient espClient;
PubSubClient mqttClient(espClient);

void init_wifi(const char *ssid, const char *password)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("WiFi does not connect, try again ...");
delay(500);
}

Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void mqtt_callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
Serial.println((char *)payload);

Serial.println("");
Serial.println((char *)payload);
Serial.println("");

if (strstr(topic, ALINK_TOPIC_PROP_SET))
{
StaticJsonBuffer<100> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(payload);
int params_LightSwitch = root["params"]["LightSwitch"];
if(params_LightSwitch==1)
{ Serial.println("Led on");
digitalWrite(LED,HIGH);}
else
{ Serial.println("Led off");
digitalWrite(LED,LOW);}



if (!root.success())
{
Serial.println("parseObject() failed");
return;
}
}
}
void mqtt_version_post()
{
char param[512];
char jsonBuf[1024];

//sprintf(param, "{\"MotionAlarmState\":%d}", digitalRead(13));
sprintf(param, "{\"id\": 123,\"params\": {\"version\": \"%s\"}}", DEV_VERSION);
// sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.println(param);
mqttClient.publish(ALINK_TOPIC_DEV_INFO, param);
}
void mqtt_check_connect()
{
while (!mqttClient.connected())//mqtt���
{
while (connect_aliyun_mqtt(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET))
{
Serial.println("MQTT connect succeed!");
//client.subscribe(ALINK_TOPIC_PROP_POSTRSP);
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);

Serial.println("subscribe done");
mqtt_version_post();
}
}

}

void mqtt_interval_post()
{
char param[512];
char jsonBuf[1024];

//sprintf(param, "{\"MotionAlarmState\":%d}", digitalRead(13));
sprintf(param, "{\"LightSwitch\":%d,\"range\":%d}",!digitalRead(LED),val);
sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.println(jsonBuf);
mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}


void setup()
{

pinMode(SENSOR_PIN, INPUT);
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
/* initialize serial for debugging */
Serial.begin(115200);

Serial.println("Demo Start");

init_wifi(WIFI_SSID, WIFI_PASSWD);

mqttClient.setCallback(mqtt_callback);
}

// the loop function runs over and over again forever
void loop()
{
val= analogRead(A0);
if (val>500)
{digitalWrite(LED2,HIGH);}
else
{digitalWrite(LED2,LOW);}

if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqtt_check_connect();
/* Post */
mqtt_interval_post();
}

mqttClient.loop();

unsigned int WAIT_MS = 2000;
if (digitalRead(SENSOR_PIN) == HIGH)
{
Serial.println("Motion detected!");
}
else
{
Serial.println("Motion absent!");
}
delay(WAIT_MS); // ms
Serial.println(millis() / WAIT_MS);
}

Upload the code to the development board. When the blue light on the development board is constantly on, it indicates that WiFi is connected


Control of lights through Alibaba Cloud

The layout of the circuit and the arrangement of components are shown in the diagram

Control light on

Control light off

Can read the value of port A0, LED2 lights up when the value is greater than 500
“Get” to obtain the current potentiometer value

Change the potentiometer value and observe the red light on and off



Reference

https://blog.csdn.net/JAVA_EE_J/article/details/126691230
https://blog.csdn.net/qq_51963216/article/details/121408579
https://perfect-anger-34c.notion.site/2021-Toast-9d52603d5d39409b8337738a551b5df1?p=857a698108444f3e90ae347f7eafccc6&pm=c
https://richengaa.wixsite.com/woohoo/%E5%89%AF%E6%9C%AC-project-2