// Student Name: Muhammad Afeeq Zhikri Bin Zamzuri
// Student ID: 52224122134
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "EmonLib.h"
#include "ThingSpeak.h"
#define SCREEN_WIDTH 128 // OLED width, in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
// OLED display object connected to I2C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak API information
const char* server = "https://api.thingspeak.com";
const char* apiKey = "CDJEFTTGRAFUMV67"; // Replace with your ThingSpeak Write API Key
const char* myChannelNumber = "2810704"; // Replace with your ThingSpeak Channel Number
const int voltagePin = 35; // Analog input pin for voltage measurement
const int currentPin = 34; // Analog input pin for current measurement
const int redLedPin = 4; // Digital output pin for red LED
const int greenLedPin = 5; // Digital output pin for green LED
// Temperature sensor pins and objects
#define ONE_WIRE_BUS 15 // Pin connected to the temperature sensor
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature tempSensor(&oneWire);
EnergyMonitor currentSensor;
float voltage, current, power, powerConsumption, temperature, costOfElectricity;
unsigned long previousMillis = 0; // Variable to store the time of the last update
unsigned long totalMillis = 0; // Variable to store the total elapsed time
// Electricity rate per kWh in Ringgit Malaysia
float electricityRate = 0.57; // Example rate of RM 0.57 per kWh
void setup() {
Serial.begin(115200);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
delay(500);
display.clearDisplay();
display.setTextColor(WHITE);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
pinMode(voltagePin, INPUT);
pinMode(currentPin, INPUT);
pinMode(redLedPin, OUTPUT); // Set red LED pin as output
pinMode(greenLedPin, OUTPUT); // Set green LED pin as output
// Initialize temperature sensor
tempSensor.begin();
}
void sendDataToThingSpeak() {
// Read raw analog values
int rawVoltage = analogRead(voltagePin);
int rawCurrent = analogRead(currentPin);
// Convert raw values to physical quantities
voltage = (rawVoltage / 4095.0) * 230; // Assuming 230V reference
float currentVoltage = (rawCurrent / 4095.0) * 5; // Assuming 5V reference
const float sensorSensitivity = 0.1; // Sensor sensitivity in V/A (adjust according to datasheet)
current = currentVoltage / sensorSensitivity; // Calculate current in Amperes
power = voltage * current; // Calculate power in Watts
// Calculate elapsed time since last update
unsigned long currentMillis = millis();
unsigned long elapsedTime = currentMillis - previousMillis;
previousMillis = currentMillis;
totalMillis += elapsedTime;
// Calculate power consumption
float elapsedTimeHours = totalMillis / 3600000.0; // Convert milliseconds to hours
powerConsumption = (power / 1000.0) * elapsedTimeHours; // Convert power to kWh and multiply by elapsed time
costOfElectricity = powerConsumption * electricityRate; // Multiply by electricity rate
// Read temperature from sensor
tempSensor.requestTemperatures();
temperature = tempSensor.getTempCByIndex(0); // Assuming only one sensor connected
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "/update?api_key=" + apiKey +
"&field1=" + String(voltage, 2) +
"&field2=" + String(current, 2) +
"&field3=" + String(powerConsumption, 2) +
"&field4=" + String(temperature, 2) +
"&field5=" + String(costOfElectricity, 2);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Data sent to ThingSpeak successfully!");
} else {
Serial.print("Error sending data: ");
Serial.println(http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.println("WiFi not connected! Unable to send data.");
}
}
void loop() {
// Send data to ThingSpeak every 10 seconds
static unsigned long lastSendTime = 0;
if (millis() - lastSendTime >= 10000) {
sendDataToThingSpeak();
lastSendTime = millis();
}
// Display values on the OLED
display.clearDisplay(); // Clear display before drawing new values
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("Voltage (V): ");
display.println(voltage, 2);
display.setCursor(0, 16);
display.print("Current (A): ");
display.println(current, 2);
display.setCursor(0, 32);
display.print("Power/H: ");
display.println(powerConsumption, 2);
display.setCursor(0, 48);
display.print("Temperature: ");
display.println(temperature, 2);
display.println("°C");
display.setCursor(0, 64);
display.print("Cost: RM ");
display.println(costOfElectricity, 2);
display.display();
}