Skip to content

Instantly share code, notes, and snippets.

@artistio
Created December 9, 2018 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artistio/a0144d90931ed3c9e2e937c37f438766 to your computer and use it in GitHub Desktop.
Save artistio/a0144d90931ed3c9e2e937c37f438766 to your computer and use it in GitHub Desktop.
File ini berisi fungsi untuk mengirimkan data ke ThingSpeak
/**
* File sendThingSpeak.ino
*
* int sendThingSpeak(float temp, float hum)
*
* Fungsi: Mengirimkan suhu (field0) dan kelembaban(field1) ke ThingSpeak
*
* Return Value: TBD
*
* Hak cipta (c) 2018 x.benny.id.
* https://x.benny.id
*
* Lisensi Creative Commons Atribusi-NonKomersial-BerbagiSerupa 4.0 Internasional
*/
#define DEC 2
int sendThingSpeak (float temp, float hum) {
char mqttUserName[] = "NodeMCUWX";
WiFiClient client; // Initialize the Wifi client library.
PubSubClient mqttClient(client); // Initialize the PuBSubClient library.
const char* server = "mqtt.thingspeak.com";
mqttClient.setServer(server, 1883); // Set the MQTT broker details.
// Loop until reconnected.
while (!mqttClient.connected())
{
Serial.print("Attempting MQTT connection...");
// Connect to the MQTT broker
if (mqttClient.connect(THINGSPEAK_CLIENT_ID,mqttUserName,THINGSPEAK_MQTT_API))
{
Serial.print("Connected with Client ID: ");
Serial.print(String(clientID));
Serial.print(" , Passwword: ");
Serial.println(THINGSPEAK_MQTT_API);
} else
{
Serial.print("failed, rc=");
// Print to know why the connection failed.
// See https://pubsubclient.knolleary.net/api.html#state for the failure code explanation.
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
// Create data string to send to ThingSpeak
String data = String("field1=" + String(temp, DEC) + "&field2=" + String(hum, DEC));
int length = data.length();
char msgBuffer[length];
data.toCharArray(msgBuffer,length+1);
Serial.println(msgBuffer);
// Create a topic string and publish data to ThingSpeak channel feed.
String topicString ="channels/" + String( THINGSPEAK_CHANNEL_ID ) + "/publish/"+String(THINGSPEAK_CHANNEL_API);
length=topicString.length();
char topicBuffer[length];
topicString.toCharArray(topicBuffer,length+1);
mqttClient.publish( topicBuffer, msgBuffer );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment