Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Inclusão de Bibliotecas
- #include <WiFiClientSecure.h>
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include <DallasTemperature.h>
- #include <OneWire.h>
- //Informações do WIFI
- const char* ssid = "xxxxxxxxxxxxx";
- const char* password = "xxxxxxxxxxxxx";
- WiFiClient wifiClient;
- //Constantes de conexão do IBM Bluemix
- #define DEVICE_TYPE "xxxx"
- #define DEVICE_ID "xxxx"
- #define ORG "xxxxxxxxxxxxx"
- #define TOKEN "xxxxxxxxxxxxx"
- char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
- char topic[] = "iot-2/evt/status/fmt/json";
- char authMeth[] = "use-token-auth";
- char token[] = TOKEN;
- char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
- //Inicialização do cliente MQTT
- PubSubClient client(server, 1883, NULL, wifiClient);
- //Sensor de Temperatura
- #define ONE_WIRE_BUS 2
- OneWire oneWire(ONE_WIRE_BUS);
- DallasTemperature sensor(&oneWire);
- //Função de setup
- void setup() {
- Serial.begin(115200);
- Serial.println();
- setupWifi();
- }
- //__ Função principal
- void loop() {
- float readingc;
- float readingf;
- sensor.requestTemperatures();
- readingc = sensor.getTempCByIndex(0);
- readingf = sensor.getTempFByIndex(0);
- //__ Verifica se está conectada a cloud para envio dos dados
- if (!!!client.connected()) {
- //__ Caso não esteja conectada, tenta a conexão
- Serial.print("Reconectando-se em ");
- Serial.println(server);
- while (!!!client.connect(clientId, authMeth, token)) {
- Serial.print(".");
- delay(500);
- }
- Serial.println();
- }
- //__ Envia um dado para a cloud
- enviaDado(String("Celsius"), readingc, String("Farenheit"), readingf);
- delay(10000);
- }
- //Função para enviar dados para o BLUEMIX
- void enviaDado(String nome_campo, int dado, String nome_campo2, int dado2){
- //__ Formata a string que será envia para a cloud (JSON)
- String payload = "{\"d\":{\"" + nome_campo + "\":";
- payload += dado;
- payload += ",\""+ nome_campo2 +"\":";
- payload += dado2;
- payload += "}}";
- Serial.print("Sending payload: ");
- Serial.println(payload);
- //__ Envia o dado
- if (client.publish(topic, (char*) payload.c_str())) {
- Serial.println("Publish ok");
- } else {
- Serial.println("Publish failed");
- }
- }
- void setupWifi(){
- // attempt to connect to Wifi network:
- WiFi.begin(ssid,password);
- Serial.print("Conectando ao Wifi: ");
- Serial.println(ssid);
- while (WiFi.status() != WL_CONNECTED) {
- // Serial.print(".");
- delay(500);
- }
- Serial.println("");
- Serial.println("WiFi conectado");
- Serial.print("IP: ");
- Serial.println(WiFi.localIP());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement