haris project 1
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "********"; // cannot be longer than 32 characters!
const char *pass = "********"; //
int buttonState = 0;
String flag;
// device details
char *deviceId = "device-*******************************";
char *deviceUsername = "*******************************";
char *devicePassword = "*******************************";
String deviceCredential = String(deviceUsername) + ":" + String(devicePassword);
WiFiClient wclient;
PubSubClient client(wclient, (String) "geeknesia.com", 1883);
void senddata(char* topic, String credential, char *var1, String nilai1 ) {
String pubString = "{\"code\":\"";
pubString += credential;
pubString += "\",";
pubString += "\"attributes\":{\"";
pubString += String(var1) + "\":\"" + nilai1 + "\"";
pubString += "}}";
char message_buff[pubString.length() + 1];
pubString.toCharArray(message_buff, pubString.length() + 1);
client.publish("iot/data", pubString);
}
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT); // Initialize the BUILTIN_LED pin as an output
pinMode(12, INPUT_PULLUP);
}
// the loop function runs over and over again forever
void loop() {
if (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (client.connect(deviceId, "iot/will", 0, 0, deviceId)) {
}
}
if (client.connected())
client.loop();
}
buttonState = digitalRead(12);
if (buttonState == 1) {
digitalWrite(2, LOW);
flag = "OFF";
}
else {
// turn LED off:
digitalWrite(2, HIGH);
flag = "ON";
}
senddata(deviceId, deviceCredential, "Lamp", flag);
delay(5000);
}