Interrupt on nano and detach

Hello, I try to count the number of beeps on another device with the nano. I use a comparator since voltage on that device piezo is negative. My comparator output is a pulse train of 30msec of square waves 4V at 3000Hz.
This is fed to D2. This code tries to count each beep (of 30msec) as one count. But each beep produces 2 counts. I know I can divide the counts by two, but I try to understand why this happens. Any ideas why?

const byte radexPin = 2;

volatile unsigned long counts; // When accessing this in setup or loop (or anything called by either) interrupts must be disabled
volatile boolean picked=false;
long prevCounts=0;

void setup() {
  pinMode(radexPin, INPUT);
  attachInterrupt(digitalPinToInterrupt(radexPin), pik, RISING);
  Serial.println("setup ok; waiting for beeps...");

void loop() {
if (picked) {picked=false;prevCounts=counts;counts++;delay(50);
             attachInterrupt(digitalPinToInterrupt(radexPin), pik, RISING);

void pik(){
void show(){
      Serial.print("teller="); Serial.print(teller);
      Serial.print("/ prevCounts="); Serial.print(prevCounts);
      Serial.print("/ time="); Serial.print(millis());
      Serial.print("/ counts="); Serial.println(counts); }


The easier you make it to read and copy the code the more likely it is that you will get help

Please follow the advice given in the link below when posting code

The problem was at the comparator. Topic can be closed.

Apart from the fact that disabling and reenabling interrupts is a known cause of
problems - you shouldn't be doing it this way, reattaching a RISING interrupt may
trigger a spurious new interrupt if the signal happens to be HIGH and the hardware
happens to work this way (chip dependent).

Besides detach and re-attach costs CPU cycles that are completely unnecessary here.

Basically unless you have an overriding reason to do it, and a full understanding of
the interrupt hardware for the chip in question, never use things like detachInterrupt()!

This is possibly overkill, but when you come to directly enabling and disabling interrupts
at the hardware level this sort of thing will bite you.

Thanks for info! I will divide the counts by the number of pulses in the beep-pulse-train, without detaching.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.