0% found this document useful (0 votes)
40 views8 pages

AC Current Sensor Code for Arduino

This document provides notes on using an AC current sensor with an LCD display. It includes: 1) Safety notes and descriptions of the current measurement module and calculations. 2) Variables and pins used for current measurement, offset calibration, and LCD display. 3) Code snippets for setup, loop, measuring current samples, calculating RMS current values, displaying to serial monitor and LCD, and automatic offset calibration when a button is pressed.

Uploaded by

khalid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views8 pages

AC Current Sensor Code for Arduino

This document provides notes on using an AC current sensor with an LCD display. It includes: 1) Safety notes and descriptions of the current measurement module and calculations. 2) Variables and pins used for current measurement, offset calibration, and LCD display. 3) Code snippets for setup, loop, measuring current samples, calculating RMS current values, displaying to serial monitor and LCD, and automatic offset calibration when a button is pressed.

Uploaded by

khalid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// AC Current Sensor with LCD By Solarduino

// Note Summary
// Note : Safety is very important when dealing with electricity. We take no
responsibilities while you do it at your own risk.
// Note : This AC Current Sensor Code is for ACS712 current module and Hall effect
split core current transformer use.
// Note : The value shown in Serial Monitor / LCD Display is refreshed every
second and is the average value of 1000 sample readings.
// Note : The current measured is the Root Mean Square (RMS) value.
// Note : The analog value per sample is squared and accumulated for every 1000
samples before being averaged. The averaged value is then getting square-rooted.
// Note : The auto calibration (currentOffset1) is using averaged analogRead value
of 1000 samples.
// Note : The auto calibration (currentOffset2) is using calculated RMS current
value including currentOffset1 value for calibration.
// Note : The unit provides reasonable accuracy and may not be comparable with
other expensive branded and commercial product.
// Note : All credit shall be given to Solarduino.

/
*//////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
////////////////*/////////////*/

/* 0- General */

int decimalPrecision = 2; // decimal places for all


values shown in LED Display & Serial Monitor

/* 1- AC Current Measurement */

int CurrentAnalogInputPin = A1; // Which pin to measure Current


Value (A0 is reserved for LCD Display Shield Button function)
float mVperAmpValue = 185; // If using ACS712 current
module : for 5A module key in 185, for 20A module key in 100, for 30A module key in
66
// If using "Hall-Effect"
Current Transformer, key in value using this formula: mVperAmp = maximum voltage
range (in milli volt) / current rating of CT
// For example, a 20A Hall-
Effect Current Transformer rated at 20A, 2.5V +/- 0.625V, mVperAmp will be 625 mV /
20A = 31.25mV/A
float offsetSampleRead = 0; /* to read the value of a
sample for offset purpose later */
float currentSampleRead = 0; /* to read the value of a
sample including currentOffset1 value*/
float currentLastSample = 0; /* to count time for each
sample. Technically 1 milli second 1 sample is taken */
float currentSampleSum = 0; /* accumulation of sample
readings */
float currentSampleCount = 0; /* to count number of sample.
*/
float currentMean ; /* to calculate the average
value from all samples, in analog values*/
float RMSCurrentMean ; /* square roof of currentMean,
in analog values */
float adjustRMSCurrentMean ; /* RMScurrentMean including
currenOffset2, in analog values */
float FinalRMSCurrent ; /* the final RMS current
reading*/

/*1.1 Offset AC Current */

int OffsetRead = 0; /* to change the mode for


offset */
float currentOffset1 = 0; // to Offset deviation and
accuracy. Offset any fake current when no current operates.
// Offset will
automatically callibrate when SELECT Button on the LCD Display Shield is pressed.
// If you do not have LCD
Display Shield, look into serial monitor to add or minus the value manually and key
in here.
// 26 means add 26 to all
analog value measured
float currentOffset2 = 0; // to offset value due to
calculation error from squared and square root.
float offsetSampleSum =0; /* accumulation of sample
readings for offset */
float offsetCurrentMean = 0; /* to calculate the average
value from all samples for offset, in analog values*/
float offsetLastSample = 0; /* to count time for each
sample for offset purpose. */
float offsetSampleCount = 0; /* to count number of
sample for offset. */

/* 2 - LCD Display */

#include<LiquidCrystal.h> /* Load the liquid Crystal


Library (by default already built-it with arduino solftware)*/
LiquidCrystal LCD(8,9,4,5,6,7); /* Creating the LiquidCrystal
object named LCD. The pin may be varies based on LCD module that you use*/
unsigned long startMillisLCD; /* start counting time for LCD
Display */
unsigned long currentMillisLCD; /* current counting time for
LCD Display */
const unsigned long periodLCD = 1000; // refresh every X seconds (in
seconds) in LED Display. Default 1000 = 1 second

void setup() /*codes to run once */

/* 0- General */

[Link](9600); /* to display readings in


Serial Monitor at 9600 baud rates */

/* 2 - LCD Display */

[Link](16,2); /* Tell Arduino that our


LCD has 16 columns and 2 rows*/
[Link](0,0); /* Set LCD to start with
upper left corner of display*/
startMillisLCD = millis(); /* Start counting time
for LCD display*/

void loop() /*codes to run again and


again */
{

/* 0- General */

/* 0.1- Button Function */

int buttonRead;
buttonRead = analogRead
(0); // Read analog pin A0. Pin A0
automatically assigned for LCD Display Button function (cannot be changed)

/*Right button is pressed */


if (buttonRead < 60)
{ [Link](0,0); [Link] ("PRESS <SELECT> "); }

/* Up button is pressed */
else if (buttonRead < 200)
{ [Link](0,0); [Link] ("PRESS <SELECT> "); }

/* Down button is pressed */


else if (buttonRead < 400)
{ [Link](0,0); [Link] ("PRESS <SELECT> "); }

/* Left button is pressed */


else if (buttonRead < 600)
{ [Link](0,0); [Link] ("PRESS <SELECT> "); }

/* Select button is pressed */


else if (buttonRead < 800)
{
OffsetRead =
1; // to activate offset
[Link](0,0);
[Link] ("INITIALIZING..... ");
[Link](0,1);
[Link] ("WAIT 5 SEC ..... ");
}

/* 1- AC Current Measurement */

if(millis() >= currentLastSample + 1)


/* every 1 milli second taking 1 reading */
{
offsetSampleRead = analogRead(CurrentAnalogInputPin)-512;
/* Read analog value. This is for offset purpose */
offsetSampleSum = offsetSampleSum + offsetSampleRead;
/* Accumulate analog values from each sampel for offset purpose*/
currentSampleRead = analogRead(CurrentAnalogInputPin)-512 +
currentOffset1; /* read the sample value including offset
value*/
currentSampleSum = currentSampleSum + sq(currentSampleRead) ;
/* accumulate total analog values for each sample readings*/

currentSampleCount = currentSampleCount + 1;
/* to count and move on to the next following count */
currentLastSample = millis();
/* to reset the time again so that next cycle can start again*/
}

if(currentSampleCount == 1000)
/* after 1000 count or 1000 milli seconds (1 second), do this following codes*/
{
offsetCurrentMean = offsetSampleSum /currentSampleCount;
/* average accumulated analog values for offset purpose */

currentMean = currentSampleSum/currentSampleCount;
/* average accumulated analog values*/
RMSCurrentMean = sqrt(currentMean);
/* square root of the average value*/
adjustRMSCurrentMean = RMSCurrentMean + currentOffset2;
/* square root of the average value including offset value */
FinalRMSCurrent = (((adjustRMSCurrentMean /1024) *5000)
/mVperAmpValue); /* calculate the final RMS current*/
[Link](" The Current RMS value is: ");
[Link](FinalRMSCurrent,decimalPrecision);
[Link](" A ");
offsetSampleSum = 0;
/* to reset accumulate offset sample values for the next cycle */
currentSampleSum =0;
/* to reset accumulate sample values for the next cycle */
currentSampleCount=0;
/* to reset number of sample for the next cycle */
}

/* 1.1 - Offset AC Current */

if(OffsetRead == 1)
/* Run this code when button SELECT is pressed */
{
currentOffset1 = 0;
/* set back currentOffset as default*/
if(millis()>= offsetLastSample + 1)
/* keep countng time for offset1*/
{

offsetSampleCount = offsetSampleCount + 1;

offsetLastSample = millis();

if(offsetSampleCount == 1500)
/* after 1.5 seconds, run this codes. */
{
currentOffset1 = - offsetCurrentMean;
/* set the offset values */
OffsetRead = 2;
/* go for second offset Settings */
offsetSampleCount = 0;
/* to reset the time again so that next cycle can start again */
}

if(OffsetRead == 2)
/* Run this code after first offset done */
{
currentOffset2 = 0;
/* set back currentOffset2 as default*/
if(millis()>= offsetLastSample + 1)
/* keep countng time for offset2*/
{

offsetSampleCount = offsetSampleCount + 1;

offsetLastSample = millis();

if(offsetSampleCount == 2500)
/* after 2.5 seconds, run this codes. */
{

currentOffset2 = - RMSCurrentMean;
/* set the offset values */
OffsetRead = 0;
/* change the offset mode to original, wait until the button is pressed again */

offsetSampleCount = 0;
/* to reset the time again so that next cycle can start again */
}

/* 2 - LCD Display */

currentMillisLCD = millis();
/* Set counting time for LCD Display*/
if (currentMillisLCD - startMillisLCD >= periodLCD)
/* for every x seconds, run the codes below*/
{
[Link](0,0);
/* Set cursor to first colum 0 and second row 1 */
[Link]("I=");
[Link](FinalRMSCurrent,decimalPrecision);
/* display current value in LCD in first row */
[Link]("A ");
[Link](0,1);
[Link](" ");
/* display nothing in LCD in second row */
startMillisLCD = currentMillisLCD ;
/* Set the starting point again for next counting time */
}

-----------------------------------------------------------------------------------
-----

// AC Current Sensor without LCD By Solarduino

// Note Summary
// Note : Safety is very important when dealing with electricity. We take no
responsibilities while you do it at your own risk.
// Note : This AC Current Sensor Code is for ACS712 current module and Hall effect
split core current transformer use.
// Note : The value shown in Serial Monitor is refreshed every second and is the
average value of 1000 sample readings.
// Note : The current measured is the Root Mean Square (RMS) value.
// Note : The analog value per sample is squared and accumulated for every 1000
samples before being averaged. The averaged value is then getting square-rooted.
// Note : The auto calibration (currentOffset1) is using averaged analogRead value
of 1000 samples.
// Note : The auto calibration (currentOffset2) is using calculated RMS current
value including currentOffset1 value for calibration.
// Note : The unit provides reasonable accuracy and may not be comparable with
other expensive branded and commercial product.
// Note : All credit shall be given to Solarduino.

/
*//////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
////////////////*/////////////*/

/* 0- General */

int decimalPrecision = 2; // decimal places for all


values shown in LED Display & Serial Monitor

/* 1- AC Current Measurement */

int CurrentAnalogInputPin = A1; // Which pin to measure Current


Value (A0 is reserved for LCD Display Shield Button function)
float mVperAmpValue = 185; // If using ACS712 current
module : for 5A module key in 185, for 20A module key in 100, for 30A module key in
66
// If using "Hall-Effect"
Current Transformer, key in value using this formula: mVperAmp = maximum voltage
range (in milli volt) / current rating of CT
// For example, a 20A Hall-
Effect Current Transformer rated at 20A, 2.5V +/- 0.625V, mVperAmp will be 625 mV /
20A = 31.25mV/A
float offsetSampleRead = 0; /* to read the value of a
sample for offset purpose later */
float currentSampleRead = 0; /* to read the value of a
sample including currentOffset1 value*/
float currentLastSample = 0; /* to count time for each
sample. Technically 1 milli second 1 sample is taken */
float currentSampleSum = 0; /* accumulation of sample
readings */
float currentSampleCount = 0; /* to count number of sample.
*/
float currentMean ; /* to calculate the average
value from all samples, in analog values*/
float RMSCurrentMean ; /* square roof of currentMean,
in analog values */
float adjustRMSCurrentMean ; /* RMScurrentMean including
currenOffset2, in analog values */
float FinalRMSCurrent ; /* the final RMS current
reading*/

/*1.1 Offset AC Current */

float currentOffset1 = 0; // to Offset deviation and


accuracy. Offset any fake current when no current operates.
// Offset will
automatically callibrate when SELECT Button on the LCD Display Shield is pressed.
// If you do not have LCD
Display Shield, look into serial monitor to add or minus the value manually and key
in here.
// 26 means add 26 to all
analog value measured
float currentOffset2 = 0; // to offset value due to
calculation error from squared and square root.

void setup() /*codes to run once */

/* 0- General */

[Link](9600); /* to display readings in


Serial Monitor at 9600 baud rates */

void loop() /*codes to run again and


again */
{

/* 1- AC Current Measurement */

if(millis() >= currentLastSample + 1)


/* every 1 milli second taking 1 reading */
{
offsetSampleRead = analogRead(CurrentAnalogInputPin)-512;
/* Read analog value. This is for offset purpose */
currentSampleRead = analogRead(CurrentAnalogInputPin)-512 +
currentOffset1; /* read the sample value including offset
value*/
currentSampleSum = currentSampleSum + sq(currentSampleRead) ;
/* accumulate total analog values for each sample readings*/

currentSampleCount = currentSampleCount + 1;
/* to count and move on to the next following count */
currentLastSample = millis();
/* to reset the time again so that next cycle can start again*/
}

if(currentSampleCount == 1000)
/* after 1000 count or 1000 milli seconds (1 second), do this following codes*/
{
currentMean = currentSampleSum/currentSampleCount;
/* average accumulated analog values*/
RMSCurrentMean = sqrt(currentMean);
/* square root of the average value*/
adjustRMSCurrentMean = RMSCurrentMean + currentOffset2;
/* square root of the average value including offset value */
FinalRMSCurrent = (((adjustRMSCurrentMean /1024) *5000)
/mVperAmpValue); /* calculate the final RMS current*/
[Link](" The Current RMS value is: ");
[Link](FinalRMSCurrent,decimalPrecision);
[Link](" A ");
currentSampleSum =0;
/* to reset accumulate sample values for the next cycle */
currentSampleCount=0;
/* to reset number of sample for the next cycle */
}

Common questions

Powered by AI

The calculation of the final RMS current value involves several mathematical operations. Initially, each sample's analog value is squared and accumulated over 1000 samples . After averaging these values, the square root of the average is taken to yield the RMSCurrentMean . This value is then adjusted by adding another calibration offset (currentOffset2) to produce the adjustRMSCurrentMean . The final RMS current is calculated using the formula: ((adjustRMSCurrentMean / 1024) * 5000) / mVperAmpValue. Each step ensures that the measured current reflects an accurate and consistent RMS value.

The AC current sensor mitigates sample reading variations through an auto-calibration process. This involves taking 1000 samples to calculate an average analogRead value (currentOffset1), which offsets any measurements deemed erroneous when no current should be present . Additionally, a similar offset (currentOffset2) is applied to account for calculation errors from squared and square-rooted values . This two-step calibration helps ensure the accuracy of the RMS current measurement.

The Arduino setup differentiates button presses on the LCD Display Shield by reading analog values at pin A0, which are associated with specific button actions. If the analogRead returns values below certain thresholds (e.g., <60, <200, <400, <600, <800), the program recognizes them as Right, Up, Down, Left, or Select button presses, respectively . For example, pressing the Select button activates the offset calibration mode, as indicated by the display message "INITIALIZING..." and requires a 5-second wait for completion . This capability allows users to interact with the sensor system for operations like calibration.

The system updates RMS current values in real-time by recalculating every second. It achieves this by counting each sample per millisecond, taking 1000 samples within a second, averaging these samples, and then recalculating the RMS value . The RMS value is printed to the LCD display and the Serial Monitor, both refreshing every second to reflect current changes . This frequent updating is crucial for real-time monitoring, allowing users to observe changes quickly and adapt as needed, significantly enhancing the practical applicability in dynamic environments or real-time applications.

The Liquid Crystal Display (LCD) in the AC Current Sensor setup provides a real-time visual display of the RMS current values to the user. The setup involves initializing the LCD with specific pins and setting a timer to refresh the display every second . The code positions the cursor on the display to show the current RMS value in the first row with precision to two decimal places . This integration between the LCD and Arduino code facilitates user interaction by providing immediate feedback on current measurements and system calibration prompts.

Setting up the AC current sensor circuit involves connecting the appropriate components to the Arduino, namely the ACS712 current module or Hall effect transformer and the LCD display. Initialization in the Arduino setup phase includes defining the analog input pin for current measurement, specifying the mVperAmp value according to the current module, and configuring the LCD pins to handle display functions . The setup() function initializes Serial communication and LCD parameters, setting the stage for accurate current measurement and display functionality . This foundation is crucial for subsequent operations, ensuring that readings are accurately captured and communicated to the user.

Time synchronization in the AC current sensor code is handled through the millis() function, which tracks the milliseconds since the Arduino board began running the current program. Each reading is synchronized to occur every millisecond by checking if the current time (millis()) exceeds the time of the last sample plus one millisecond . This ensures that exactly 1000 samples are taken every second, critical for accurate RMS calculations, as it maintains a consistent timeframe for averaging and subsequent analyses . Precise timing helps avoid discrepancies in readings that might occur if samples were taken at inconsistent intervals.

Offset calibration in the AC current sensor corrects for deviations in readings when no current flow is expected. It involves automatically adjusting the baseline reading using two offsets: currentOffset1 and currentOffset2. The first offset (currentOffset1) accounts for any false current indication when no load is applied by using the averaged reading of 1000 initial samples . The second offset (currentOffset2) addresses errors from mathematical processing, such as squaring and taking square roots of sample values . This dual approach to offsetting effectively nullifies fictitious readings and refines the accuracy of the RMS current calculation, ensuring that zero current is accurately reflected as zero on display.

The Arduino code supports two main types of current sensors: the ACS712 current module and a Hall effect split-core current transformer. For the ACS712 module, the code assigns different mVperAmp values depending on the module's current rating (e.g., 185 for 5A, 100 for 20A, and 66 for 30A). For a Hall effect current transformer, the mVperAmp value is calculated using the transformer's maximum voltage range and current rating . This adaptable approach in the code allows it to adjust the mVperAmp variable to align with the specific characteristics of the sensor being used, thereby handling both sensor types appropriately.

The AC current sensor described is designed to offer a reasonable degree of accuracy through its process of taking 1000 sample readings, averaging them, and applying calibration offsets . However, the document acknowledges that its accuracy may not compare with expensive branded commercial products . The necessity for manual calibration offsets and potential errors in mathematical operations like squaring and square-rooting may introduce inconsistencies. Thus, while suitable for hobbyist and educational purposes, its commercial viability may be limited due to these factors and its lack of durability and standardization against higher-priced solutions.

You might also like