Seeed-Studio / CodeCraft

Codecraft is a graphical programming software which is based on Scratch 3.0
https://ide.tinkergen.com/
Apache License 2.0
18 stars 3 forks source link

Debugging first code! #11

Closed vongomben closed 5 months ago

vongomben commented 6 months ago

I have this code working! Planning to make more tests soon. Great Job!

image

#include <rpcWiFi.h>
#include <MQTT.h>

const char ssid[] = "wifiname";
const char pass[] = "wifipass";
WiFiClient net;
#define BROKER       "broker.hivemq.com"
#define DEV_NAME     "device"
#define MQTT_USER    ""
#define MQTT_PW      ""
MQTTClient client;
String rev_topic;
String rev_payload;
float channel;

void messageReceived(String &topic, String &payload) {
    rev_topic = topic;
    rev_payload = payload;
}

bool connect() {
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(1000);
    }
    while (!client.connect(DEV_NAME, MQTT_USER, MQTT_PW)) {
        Serial.print(".");
        delay(1000);
    }
    return true;
}

String readPayload(String topic) {
    if (topic == rev_topic) {
        return rev_payload;
    }
    return "";
}

void setup(){
  WiFi.begin("wifiname", "wifipass");
  client.begin(BROKER, net);
  client.onMessage(messageReceived);
  pinMode(WIO_LIGHT, INPUT);

}

void loop(){

  if (connect()) {
    while (client.connected()) {
      client.subscribe("channel");
      client.publish("channel", (String)analogRead(WIO_LIGHT));
      Serial.println(readPayload("channel"));
      delay(1000);
    }
  }

}
chenwenhao568 commented 5 months ago

congratulations!