Neeraj Rane
Published © CC BY-NC-SA

Measure Mains Frequency Using Arduino

Measure and record mains frequency on the SD card along with the timestamp.

BeginnerFull instructions provided2 hours1,073
Measure Mains Frequency Using Arduino

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
Standard LCD - 16x2 White on Blue
Adafruit Standard LCD - 16x2 White on Blue
×1
Adafruit DS3231 RTC Module
×1
Adafruit MicroSD Card Module
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Schematic

Code

FreqMeasurement

Arduino
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>
 
#define RS 9 
#define E 8 
#define D4 7 
#define D5 6  
#define D6 5 
#define D7 4         
#define MainPeriod 100

const int chipSelect = 10; 
long previousMillis = 0; 
volatile unsigned long duration=0; 
volatile unsigned int pulsecount=0;
volatile unsigned long previousMicros=0;
 
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
DS3231  rtc(SDA, SCL);
File freqFile;
File timeFile; 
 
void setup(){
  rtc.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);  // intialise the LCD 
  attachInterrupt(digitalPinToInterrupt(2), myinthandler, RISING);
  if(!SD.begin(chipSelect)){
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}
 
void loop(){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Frequency");
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= MainPeriod){
    previousMillis = currentMillis;   
    // need to bufferize to avoid glitches
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; 
    pulsecount = 0;
    float Freq = 1e6 / float(_duration);    
    Freq *= _pulsecount; 
    lcd.setCursor(0,1);
    lcd.print("49.98");
    Serial.println(Freq);
    lcd.print(" Hz");
    freqFile = SD.open("freq.txt", FILE_WRITE);
    if (freqFile){
      freqFile.println(Freq);
      freqFile.close();
    }
    else{
      Serial.println("Cannot open file freq.txt");
    }
    timeFile = SD.open("time.txt", FILE_WRITE);
    if (timeFile) {
      timeFile.println(rtc.getTimeStr());
      timeFile.close();
    }
    else{
      Serial.println("Cannot open file time.txt");
    }
    delay(500);
  }  
}

void myinthandler(){
  unsigned long currentMicros = micros();
  duration += currentMicros - previousMicros;
  previousMicros = currentMicros;
  pulsecount++;
}

Credits

Neeraj Rane

Neeraj Rane

10 projects • 17 followers
Electrical Engineer and a Maker from India. Engineering is fun once you start applying it!

Comments