Unpredictable behavior with Serial

Hi, I am working on a project that reads a square wave and measures its period. I use an Arduino UNO and the web editor, plugin agent is v1.1.76-e873eeb. An led and a resistor is connected to pin 11.
I don't carry a signal generator with me, so I am using a SigGen class to simulate the output of a square wave. I have tested the SigGen class in a different sketch. I generates the correct signal which alternates
between 2 and 20Hz, and successfully flashes pin 11 led in sync with it.

The problem is that sometimes the code works and measures the period, outputs it on the serial monitor, but other times, the Serial just blanks out with nothing in it and the pin 13 built-in led keeps flashing three times as if it is constantly reseting. However, the sketch upload is successful. I expect at least the print statement to be outputted to the Serial but it doesn't happen.

my main code

#include "SigGen.h"
#include "PeriodDetector.h"

PeriodDetector periodDetector;
SigGen sigGen((unsigned int)(2)); // generating a squarewave with frequency 2 Hz
bool trigger = false; // varable to monitor the signal
bool oldTrigger = false; // variable to monitor change in signal
const byte ledPin = 11; // led that flashes with the signal

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
    Serial.println("setup() successful"); //see if setup() gets run
}

void loop() {
  // I want the frequency to alternate between 20 and 2
  //to check my periodDetector works between changes
  if(millis()%10000L > 5000L){
    sigGen.setFrequency((unsigned int)(20));
  }
  else{
    sigGen.setFrequency((unsigned int)(2));
  }
  
  // monitor signal and update trigger
  if(sigGen.getOutput()>500){
    trigger = true;
  }
  else{
    trigger = false;
  }
  
  // when signal is rising
  if(trigger && (!oldTrigger)){
    digitalWrite(ledPin, HIGH);
    periodDetector.record();
    Serial.println(periodDetector.getPeriod());
  }

  // when signal is falling
  if(oldTrigger && (!trigger)){
    digitalWrite(ledPin, LOW);
  }
  
  oldTrigger = trigger; // update oldTrigger
}

A good run looks like this.

setup() successful
284
499832
500032
500044
499992
499920
499996
500000
500076
499916
499996
50040
50068
49948
50028
49992
...

The period in microseconds it outputted every period.

I tried to comment out code but the unpredictable nature of this problem makes it very difficult.
One thing I've noticed is that usually the serial communication gets setup after the program it successfully uploaded and starts running. This has been the case for my other projects. The arduino starts running the program, then Serial is setup and arduino resets and Serial starts getting output from Arduino. However, when a bad run happens, the program runs just fine before Serial is established, but after it is established the pin 13 built-in led just blinks thrice indefinitely.
I don't know what is happening. Thanks in advance for any help.

period_detector.zip (3.59 KB)

I was a little confused by all the division and modulo operations in SigGen. I re-wrote it in the style of BlinkWithoutDelay and it has been running for a while witohut problems on my Arduino UNO.

#include "SigGen.h"


// frequency in Hz, minimum 1, maximum = unsigned int max ~65k.
SigGen::SigGen(unsigned int frequency)
{
  setFrequency(frequency);
}


// checks clock and decide whether to return 0 or 1000.


int SigGen::getOutput()
{
  unsigned long currentTime = micros();
  static boolean level = true;
  int returnValue = level ? 1000 : 0;


  if (currentTime - startTime_m >= period_m)
  {
    startTime_m += period_m;
    level = !level;
  }


  return returnValue;
}


// frequency in Hz, minimum 1, maximum = unsigned int max ~65k.
void SigGen::setFrequency(unsigned int frequency)
{
  if (frequency == 0)
  {
    period_m = 500000L; // assume min frequency 1Hz
    return;
  }


  period_m = 500000UL / frequency;  // period of half a cycle in microseconds
}

Hello,

Thank you for your help. I substituted yuor code into SigGen.cpp. The first two runs are good, but on the third upload, the problem appears again. The pin 13 led starts to blink thrice as soon as the Serial monitor on the web editor is available. From repeated uploads, it seems there is a one in three chance that this happens and I get no output on the serial whatsoever. :confused:

the Serial monitor on the web editor

Can you do a local IDE install and try that?

The problem seems to appear less often on a local IDE, but it happens every now and then.