I'm using an SSD1306 128x64 oled display to display sensor data from a BME280 and CCS811 using I2C. I've also added a button to cycle through all the outputs, but I found that the sendBuffer command is causing the sensor output to not work (temp = -144, alt = -800 etc.). I noticed that the sensor values do display correctly for the first loop, then stop working for the rest. I've been trying all sorts of different libraries for both the sensors and the display, and I haven't made much progress.
I'm very new to Arduino and coding so there's bound to be a lot of mistakes and unnecessary things. I'd appreciate some advice as well to help me out.
#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "SparkFunCCS811.h"
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define CCS811_ADDR 0x5B
#define SEALEVELPRESSURE_HPA (1013.25)
unsigned long delayTime;
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);
Adafruit_BME280 bme;
CCS811 ccs(CCS811_ADDR);
const int buttonPin = 2;
byte oldButtonState = HIGH;
int screenNumber = 0;
byte buttonState = 0;
void setup(void) {
u8g2.begin();
u8g2.setPowerSave(0);
pinMode(buttonPin, INPUT_PULLUP);
unsigned status;
status = bme.begin();
}
void loop()
{
buttonState = digitalRead(buttonPin);
// Test if the button is being pressed
if (buttonState == HIGH) {
u8g2.clear();
u8g2.updateDisplay();
oldButtonState = buttonState;
if (screenNumber <=5) {
++screenNumber;
}
else if (screenNumber > 5) {
screenNumber = 1;
}
//delay a little to avoid bouncing
delay(50);
}
if (screenNumber == 1)
{
u8g2.clearBuffer();
int t;
t = round(bme.readTemperature() * 100.0) / 100.0;
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(t);
u8g2.sendBuffer();
}
else if (screenNumber == 2)
{
u8g2.clearBuffer();
int h;
h = round((bme.readHumidity()) * 100.0) / 100.0;
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(h);
u8g2.sendBuffer();
}
else if (screenNumber == 3)
{
u8g2.clearBuffer();
int p;
p = round((bme.readPressure() / 100.0F) * 100.0) / 100.0;
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(p);
u8g2.sendBuffer();
}
else if (screenNumber == 4)
{
u8g2.clearBuffer();
int a;
a = round(bme.readAltitude(SEALEVELPRESSURE_HPA) * 100.0) / 100.0 + 100;
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(a);
u8g2.sendBuffer();
}
else if (screenNumber == 5)
{
u8g2.clearBuffer();
ccs.readAlgorithmResults();
int c = (ccs.getCO2());
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(ccs.getCO2());
u8g2.sendBuffer();
}
else if (screenNumber == 6)
{
u8g2.clearBuffer();
ccs.readAlgorithmResults();
int v = (ccs.getTVOC());
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setCursor(3,15);
u8g2.print(ccs.getTVOC());
u8g2.sendBuffer();
}
}