- #include <WiFi.h>
- #include <PubSubClient.h>
- #include <ArduinoJson.h>
- #define PIN_AO 34
- int BUILTIN_LED = 12;
- const char ssid[] = "wang";
- const char password[] = "wanggnaw";
- const char mqtt_server[] = "183.230.40.39";
- WiFiClient espClient;
- PubSubClient client(espClient);
- long lastMsg = 0;
- char msg_buf[200];
- int value = 0;
- char dataTemplete[]="{"shumtest":%d}";
- char msgJson[75];
- char debug_buf[200];
- int i;
- unsigned short json_len=0;
- uint8_t* packet_p;
- uint8_t debug_buffer_start_index = 0;
- 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(".");
- }
- randomSeed(micros());
- 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("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload<i>);
- }
- Serial.println();
- if ((char)payload[0] == '1') { // 收到字节为 1
- digitalWrite(BUILTIN_LED, HIGH); // 将继电器引脚电平拉高
- //delay(1000);
- // digitalWrite(BUILTIN_LED, LOW); // 将继电器引脚电平拉低
- } else {
- // digitalWrite(BUILTIN_LED, HIGH); // 将继电器引脚电平拉高
- // delay(1000);
- digitalWrite(BUILTIN_LED, LOW); // 将继电器引脚电平拉低
- } }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- if (client.connect("736391491","441729","w")) {
- Serial.println("connected");
- client.publish("outTopic", "hello world");
- client.subscribe("inTopic");
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void setup() {
- pinMode(BUILTIN_LED, OUTPUT);
- pinMode(PIN_AO, INPUT);
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 6002);
- client.connect("736391491","441729","w");
- client.setCallback(callback);
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- int shum = analogRead(PIN_AO);
- Serial.println(shum);
- delay(500);
-
- long now = millis();
-
- if (now - lastMsg > 2000){
- lastMsg = now;
-
-
- ++value;
- snprintf(msgJson,40,dataTemplete,shum);
- json_len=strlen(msgJson);
- msg_buf[0]=char(0x03);
- msg_buf[1]=char(json_len>>8);
- msg_buf[2]=char(json_len&0xff);
- memcpy(msg_buf+3,msgJson,strlen(msgJson));
- msg_buf[3+strlen(msgJson)] = 0;
- client.publish("$dp",msg_buf,3+strlen(msgJson),false);
- }
- }</i>
复制代码
这是所有的代码
|