Skip to content

Instantly share code, notes, and snippets.

@MDevolution
Created April 16, 2022 13:06
Show Gist options
  • Save MDevolution/2883077d9ed99b1fc59c82df6398b79c to your computer and use it in GitHub Desktop.
Save MDevolution/2883077d9ed99b1fc59c82df6398b79c to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include "ThingSpeak.h"
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
const char* ssid = "REPLACE_WITH_YOUR_SSID"; // your network SSID (name)
const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // your network password
WiFiClient client;
unsigned long myChannelNumber = X;
const char * myWriteAPIKey = "XXXXXXXXXXXXXXXX";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;
// Variable to hold temperature readings
float temperatureC;
// Create a sensor object
Adafruit_BME280 bme; //BME280 connect to ESP8266 I2C (GPIO 4 = SDA, GPIO 5 = SCL)
void initBME(){
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
}
void setup() {
Serial.begin(115200); //Initialize serial
initBME();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
// Get a new temperature reading
temperatureC = bme.readTemperature();
Serial.print("Temperature (ºC): ");
Serial.println(temperatureC);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeField(myChannelNumber, 1, temperatureC, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment