#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
float waterFull=40;//number of litres in the barrel
float barrelHeight=60;//pixels high on the display
float waterRatio=barrelHeight/waterFull;//to calc the water height in the image
float waterLeft;
int flowPin = 2; //This is the input pin on the Arduino
volatile int flowCount = 0; //This is the var to save the flow count from the sensor
float flowCountPerLitre=480;//this is how many pulses from the sensor per litre of water
int shouldUpdate=1;//initial display draw
int thisUsageCount=0;
void setup() {
waterLeft=waterFull;
Serial.begin(9600); //Start Serial
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
pinMode(flowPin, INPUT); //Sets the pin as an input
attachInterrupt(0, Flow, RISING); //Configures interrupt 0 (pin 2 on the Arduino Uno) to run the function "Flow"
}
void loop() {
if(waterLeft>0 && shouldUpdate==1){//only update if the water has been used andf there is water left
updateDisplay();
}
delay(10000);
}
void Flow()
{
flowCount++; //Every time this function is called, increment "count" by 1
thisUsageCount++;//and this one
Serial.println(flowCount); //Print the variable flowRate to Serial
if(thisUsageCount>=flowCountPerLitre/10){//update every 100 mls to save on display redraws
shouldUpdate=1;
thisUsageCount=0;
}
}
void updateDisplay(){
shouldUpdate=0; //turn this flag off
//calc the amount of water remaining
waterLeft=waterFull-(flowCount/flowCountPerLitre);
if(waterLeft<0){//if less than zero make it zero
waterLeft=0;
}
display.clearDisplay(); //Clear the display
display.setTextSize(2);
display.setTextColor(WHITE); // Draw white text
display.setCursor(3, 3); // x,y
display.cp437(true); // Use full 256 char 'Code Page 437' font
display.println("WATER");
display.setTextSize(3);
display.setCursor(3, 34); //move the cursor down (x,y)
display.print(waterLeft,1);
display.setTextSize(3);
display.print("L");
display.drawRect(100, 4, 20, barrelHeight, WHITE);// Draw the rectangle frame
int waterHeight=waterLeft*waterRatio;
//Serial.println(waterHeight);
display.fillRect(100, 4+barrelHeight-waterHeight, 20, waterHeight, INVERSE);//x,y,width/height (x,y is top left corner)
display.display(); //Redraw the display
}