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)