Created
February 5, 2019 08:49
-
-
Save ni5ni6/fd7d21b87bd5405d2097efa64bbd9333 to your computer and use it in GitHub Desktop.
Weather station sketch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Wire.h> | |
| #include <SPI.h> | |
| #include <Adafruit_Sensor.h> | |
| #include <Adafruit_BME280.h> | |
| #include <ESP8266WiFi.h> | |
| #include <PubSubClient.h> | |
| #include <ATT_IOT.h> | |
| #include <SPI.h> // required to have support for signed/unsigned long type. | |
| #include <CborBuilder.h> | |
| #define BME_SCK 13 | |
| #define BME_MISO 12 | |
| #define BME_MOSI 11 | |
| #define BME_CS 10 | |
| #define SEALEVELPRESSURE_HPA (1013.25) | |
| #define CBOR | |
| #define backend "api.allthingstalk.io" // API endpoint | |
| Adafruit_BME280 bme; // I2C | |
| WiFiClient wifi; | |
| void callback(char* topic, byte* payload, unsigned int length); | |
| PubSubClient pubSub(backend, 1883, callback, wifi); | |
| ATTDevice device("", ""); | |
| CborBuilder payload(device); | |
| void setup() { | |
| Serial.begin(9600); | |
| if (!bme.begin()) { | |
| Serial.println("Could not find a valid BME280 sensor, check wiring!"); | |
| while (1); | |
| } | |
| setupWiFi("Hello World", "helloworld"); | |
| while(!device.connect(&wifi, backend)) // Connect to AllThingsTalk | |
| Serial.println("retrying"); | |
| while(!device.subscribe(pubSub)) // Subscribe to mqtt | |
| Serial.println("retrying"); | |
| } | |
| unsigned long prevTime; | |
| unsigned int prevVal = 0; | |
| unsigned int interval = 10000; | |
| void loop() { | |
| unsigned long curTime = millis(); | |
| if (curTime > (prevTime + interval)) | |
| { | |
| #ifdef CBOR | |
| payload.reset(); | |
| payload.map(4); | |
| payload.addNumber(bme.readTemperature(), "t"); | |
| payload.addNumber(bme.readPressure() / 100.0, "p"); | |
| payload.addNumber(bme.readHumidity(), "h"); | |
| payload.addNumber(bme.readAltitude(SEALEVELPRESSURE_HPA), "a"); | |
| payload.send(); | |
| #endif | |
| prevTime = curTime; | |
| } | |
| device.process(); // Check for incoming messages | |
| } | |
| void setupWiFi(const char* ssid, const char* password) | |
| { | |
| delay(10); | |
| Serial.print("Connecting to "); | |
| Serial.print(ssid); | |
| WiFi.begin(ssid, password); | |
| while (WiFi.status() != WL_CONNECTED) | |
| { | |
| delay(500); | |
| Serial.print("."); | |
| } | |
| Serial.print("Connected"); | |
| } | |
| /**** | |
| * Callback function | |
| * Handle messages that were sent from the AllThingsTalk cloud to this device | |
| */ | |
| void callback(char* topic, byte* payload, unsigned int length) | |
| { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment