# Counting the number of zero crossing using arduino uno

will this code work to display the frequency of input signal of zero crossing detector?

#define SECONDS 2.0

int count = 0;

void setup()
{
Serial.begin(9600);
Serial.println("Zero Cross Test");
attachInterrupt(0, cross, RISING);
}

void loop()
{
delay(SECONDS * 1000);
noInterrupts();
float hz = count / SECONDS / 2;
count = 0;
interrupts();
Serial.print(hz);
Serial.println("Hz");
}

void cross() {
count++;
}

• Where are you stuck? Do we assume that you are measuring mains frequency? You can either (1) measure the time between two zero-crosses or (2) count the number of zero-crosses in a given time. Without a schematic we can't answer the second part. There's a schematic button on the editor toolbar. Update the post rather than put the missing info in the comments. – Transistor Mar 23 '18 at 7:19
• Yes, i want to measure mains frequency and display it in serial monitor. i have updated my post. I hope for your help. thank you. – Ryadiff Mar 23 '18 at 8:58
• Actually, what is tour requirement? You didn't post anything regarding schematics and merely asking that whether that code will work or not? What if you have a correct working code and wrong circuit connections in your requirement? – Dhans Mar 23 '18 at 10:49
• @Ryadiff: The code is a mess. Use the code formatting button on the editor to tidy it up. Remove blank lines (unless to separate sections) and add comments, if required. – Transistor Mar 23 '18 at 11:48

You can use H11AA1 optocoupler to execute a concept of Zero Crossing Detection. It will turn on the phototransistor for every half cycle of the main AC signal. By detecting this signal using an MCU such as Arduino, we can find the frequency of the signal. Here is a simple workout of Arduino code for zero cross detection.

#define ZCD 2
#define LED_PIN 13

volatile byte counter=0;

void setup()
{
pinMode(ZCD,INPUT_PULLUP);
pinMode(LED_PIN,OUTPUT);
digitalWrite(LED_PIN,LOW);
attachInterrupt(digitalPinToInterrupt(ZCD),zerocrossing,RISING);
}

void loop()
{
}

void zerocrossing()
{
++counter;
Serial.println(counter);
if( counter == 60)
{
counter=0;