How to use a power sensor to create your own dashboard of power consumntion

Created on March 13, 2023 at 12:42 pm

The SCT-013-000 sensor is a device that is used to measure power consumption in an electrical circuit. This sensor is designed to detect current flowing through a conductor, and it is capable of measuring both AC and DC current. There are several benefits to using the SCT-013-000 sensor to measure power consumption, including accuracy, convenience, and ease of use.

One of the primary benefits of using the SCT-013-000 sensor to measure power consumption is accuracy. This sensor is designed to provide precise measurements of current flow, which can be used to calculate the power consumption of an electrical circuit. The accuracy of the SCT-013-000 sensor is important for a number of reasons, including energy efficiency and cost savings. By accurately measuring power consumption, individuals and organizations can identify areas where energy is being wasted and make changes to reduce their overall energy usage.

Another benefit of using the SCT-013-000 sensor to measure power consumption is convenience. This sensor is relatively easy to install and use, and it can be integrated into a variety of electrical systems. The SCT-013-000 sensor is also compatible with a wide range of microcontrollers, which makes it easy to collect and analyze data about power consumption. This convenience makes the SCT-013-000 sensor an attractive option for individuals and organizations looking to monitor and manage their energy usage.

Ease of use is also a key benefit of using the SCT-013-000 sensor to measure power consumption. This sensor is designed to be simple and straightforward to use, with minimal setup required. The sensor can be connected to a microcontroller or other data collection device, and it can be configured to provide real-time data about current flow and power consumption. This ease of use makes the SCT-013-000 sensor an ideal tool for anyone looking to monitor and manage their energy usage, regardless of their technical expertise.

In addition to these benefits, the SCT-013-000 sensor is also relatively affordable, making it accessible to a wide range of users. The sensor is widely available from a variety of suppliers, and it can be purchased for a reasonable price. This affordability makes the SCT-013-000 sensor an attractive option for individuals and organizations looking to monitor their energy usage without breaking the bank.

Integrating the SCT-013-000 sensor with a LoRaWAN module can further enhance its capabilities by enabling the transmission of power consumption data over long distances. LoRaWAN is a low-power, long-range wireless communication protocol that can transmit data up to several kilometers without the need for a wired connection. By combining the SCT-013-000 sensor with a LoRaWAN module, users can remotely monitor power consumption data and analyze it to optimize energy usage.

To integrate the SCT-013-000 sensor with a LoRaWAN module, users will need to connect the sensor output to an analog-to-digital converter (ADC) to convert the analog signal to a digital signal. The digital signal can then be transmitted to a microcontroller or gateway, which is connected to the LoRaWAN module. The data can be transmitted over the LoRaWAN network to a cloud-based platform for analysis and visualization.

The use of LoRaWAN technology to transmit power consumption data can be particularly beneficial for companies looking to optimize their energy usage. By monitoring power consumption data in real-time, companies can identify trends and patterns in energy usage and make adjustments to reduce energy waste. This can help companies reduce their energy bills, improve their sustainability, and meet regulatory requirements related to energy efficiency.

Moreover, using the SCT-013-000 sensor with a LoRaWAN module can provide valuable insights into when and how energy is being consumed. By analyzing the data, companies can identify peak energy usage periods and determine which devices or systems are consuming the most energy. This information can be used to optimize energy usage and reduce energy costs.

In addition, the remote monitoring capabilities of the SCT-013-000 sensor and LoRaWAN module can help companies identify potential issues with their electrical systems before they become major problems. For example, abnormal power consumption patterns can indicate a malfunctioning device or system, allowing companies to take corrective action before the problem escalates.

A rough implementation of this project will look somethin like this :


#include 
#include 
#include 
#include 
#include 

// LoRaWAN parameters
const u1_t PROGMEM DEVEUI[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
const u1_t PROGMEM APPEUI[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
const u1_t PROGMEM APPKEY[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static osjob_t sendjob;
const unsigned TX_INTERVAL = 60; // send data every 60 seconds
unsigned long lastSendTime = 0;

// ADS1015 parameters
Adafruit_ADS1115 ads;
const int ADC_PIN = 0; // connect the SCT-013-000 sensor to A0
const float VCC = 5.0; // supply voltage
const float ADC_RANGE = 32767.0; // ADC range
const float VREF = 1.024; // ADS1015 reference voltage
const float VOLTAGE_DIVIDER_RATIO = 0.002; // voltage divider ratio
const float CURRENT_RATIO = 0.045; // SCT-013-000 output ratio
const float POWER_FACTOR = 0.9; // power factor

void do_send(osjob_t* j) {
  // Read ADC value
  int16_t adcValue = ads.readADC_SingleEnded(ADC_PIN);

  // Calculate RMS current
  float current = (adcValue * VREF / ADC_RANGE) / VOLTAGE_DIVIDER_RATIO / CURRENT_RATIO;
  float rmsCurrent = current / sqrt(2);

  // Calculate power consumption
  float power = rmsCurrent * VCC * POWER_FACTOR;
  
  // Prepare data
  byte data[4];
  memcpy(data, &power, 4);

  // Prepare LoRaWAN message
  LMIC_setTxData2(1, data, sizeof(data), 0);

  // Schedule next transmission
  os_setTimedCallback(&sendjob, os_getTime() + sec2osticks(TX_INTERVAL), do_send);

  // Save last send time
  lastSendTime = millis() / 1000;
}

void onEvent (ev_t ev) {
  switch(ev) {
    case EV_JOINED:
      Serial.println("Network joined");
      break;
    case EV_TXCOMPLETE:
      Serial.println("Transmission complete");
      break;
    default:
      break;
  }
}
void setup() {
  Serial.begin(9600);

  // Initialize ADS1115
  ads.begin();

  // Initialize LoRaWAN
  os_init();
  LMIC_reset();
  LMIC_setSession (0x1, DEVADDR, (u1_t*)DEVEUI, (u1_t*)APPKEY);
  LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI); // configure LoRaWAN channel
  LMIC_setLinkCheckMode(0);
  LMIC_setDrTxpow(DR_SF7, 14);
  LMIC_setAdrMode(0);

  // Schedule transmission
  do_send(&sendjob);
}

Certainly! Adding an LTE module to the system can provide several benefits, such as faster data transmission and wider coverage area. Here's an example of how to send the data from the Sensor to a fast API endpoint using an LTE module:


void send_data() {
  // Read current from SCT-013-000 sensor
  float current = ads.readADC_SingleEnded(0);

  // Construct payload
  String payload = "{\"current\":" + String(current, 2) + "}";

  // Send payload to API endpoint
  String url = "https://example.com/api/data";
  HTTPClient http;
  http.begin(url);
  http.addHeader("Content-Type", "application/json");
  int httpResponseCode = http.POST(payload);
  if (httpResponseCode > 0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
  } else {
    Serial.println("Error sending data to API endpoint");
  }
  http.end();
}

In this code, we first read the current value from the SCT-013-000 sensor using the ADS1115 module. We then construct a JSON payload containing the current value, and send it to the API endpoint using an HTTP POST request with the HTTPClient library. We also add a header to specify the content type as JSON.

To use this code, you will need to replace the url variable with the endpoint URL for your own API, and modify the payload as needed for your particular use case. Additionally, you will need to install the HTTPClient library using the Arduino IDE's library manager.

Overall, using an LTE module to send the data to a fast API endpoint can provide several benefits, such as faster and more reliable data transmission, as well as the ability to easily integrate the data with other systems or applications.

You can create a Flash App that will consume the data and use Pandas to provide you with more insigts.

Here's an example of a Python Flask endpoint that accepts power consumption data and stores it in a Pandas DataFrame:

from flask import Flask, request, jsonify
import pandas as pd
import matplotlib.pyplot as plt

app = Flask(__name__)

# Create empty DataFrame to store power consumption data
power_data = pd.DataFrame(columns=["timestamp", "power_consumption"])

# Endpoint to add power consumption data
@app.route("/add_data", methods=["POST"])
def add_data():
    data = request.json
    
    # Convert timestamp to datetime object
    timestamp = pd.to_datetime(data["timestamp"])
    
    # Add data to DataFrame
    power_data.loc[len(power_data)] = [timestamp, data["power_consumption"]]
    
    # Return success message
    return jsonify({"message": "Data added successfully"})

# Endpoint to get power consumption data
@app.route("/get_data", methods=["GET"])
def get_data():
    # Group data by hour and calculate mean power consumption
    hourly_data = power_data.groupby(pd.Grouper(key="timestamp", freq="1H"))["power_consumption"].mean()

    # Calculate rolling 24-hour average
    rolling_average = hourly_data.rolling(window=24).mean()

    # Plot power consumption and rolling average
    plt.plot(hourly_data.index, hourly_data.values, label="Hourly")
    plt.plot(rolling_average.index, rolling_average.values, label="24-hour Rolling Average")
    plt.title("Power Consumption Over Time")
    plt.xlabel("Time")
    plt.ylabel("Power Consumption (Watts)")
    plt.legend()
    plt.savefig("power_consumption.png")

    # Return power consumption data as JSON
    data = {
        "hourly": hourly_data.to_dict(),
        "rolling_average": rolling_average.to_dict(),
        "peak_hour": hourly_data.groupby(hourly_data.index.hour)["power_consumption"].mean().idxmax(),
    }
    return jsonify(data)

if __name__ == "__main__":
    app.run(debug=True)

In this code, we create a Flask app and an empty Pandas DataFrame to store the power consumption data. We define two endpoints: /add_data, which accepts POST requests with power consumption data and adds it to the DataFrame, and /get_data, which returns the power consumption data as JSON and creates a line chart of the data using Matplotlib.

When a POST request is received at /add_data, we convert the timestamp to a datetime object and add the data to the DataFrame. We then return a success message as JSON.

When a GET request is received at /get_data, we group the data by hour and calculate the mean power consumption for each hour. We also calculate a rolling 24-hour average to smooth out any fluctuations. We then create a line chart of the power consumption data and save it as an image. Finally, we return the power consumption data as JSON, including the hourly data, rolling average data, and the hour with the highest mean power consumption.

Overall, this endpoint provides a flexible and scalable way to collect, store, and visualize power consumption data, and can be easily integrated into a larger system for monitoring and optimizing energy usage.

Integrating something very similar to this in my last gig I think is a great achievement that required knowledge and skills in multiple domains.

By building this system, I think have demonstrated proficiency in hardware programming, wireless communication, data analysis, and web development. Moreover, this system has the potential to help companies understand their power consumption patterns, optimize their energy usage, and reduce their environmental impact.

I hope my accomplishment is something that can serve as an inspiration for others who are looking to develop solutions that solve real-world problems.

Connecting to lzomedia.com... Connected... Page load complete