I'm an absolute beginner, and lately I had some problem with this program I was trying to do. Basically I wanted with the Arduino to count 3 pulses from an oscillator and store the time of these 3 pulses, but as I said I am a beginner so I have no Idea on how to do it, I would appreciate your help.
2 Answers
While this is likely to need tweaks for your needs, it should get you looking at the right things - millis, interrupts, etc. Official references at: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/ https://www.arduino.cc/reference/en/language/functions/time/millis/
#define pulsesToStore 3
#define interruptPin 2
volatile unsigned char index;
unsigned long storedTimes[pulsesToStore];
void restartStorage() {
index = 0;
attachInterrupt(digitalPinToInterrupt(interruptPin), storeTime, RISING);
}
void storeTime() {
storedTimes[index] = millis();
index = index + 1;
if(index >= pulsesToStore) { //stop storage
detachInterrupt(digitalPinToInterrupt(interruptPin));
}
}
void setup() {
pinMode(interruptPin, INPUT_PULLUP);
restartStorage();
}
void loop() {
// does nothing for now. this is where you would do something with the stored pulses, print to serial, etc.
}
Simple code
int pin = 7;
unsigned long duration;
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
void loop() {
long duration = pulseIn(pin, HIGH);
Serial.println(duration);
//delay(100);
}
Assuming that you are mentioning a squrewave this code mesures the time that squrewave pulse stays in HIGH
and prints out in computer serial monitor.
You should send the signal to digital pin 7 (or put any pin you won't modify code int pin = 7;
) 5 V HIGH and 0 V LOW.
The time unit measuring in here is in microseconds.
If you won't to measure low then pulseIn(pin, LOW);
I took the example from Arduino official site you can refer more here
https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/
Remember this is the basic example there are other good methods than this...
Analog wave is bit too complex.
-
That could help, but is there any other way than using a blocking function? Commented Aug 24, 2020 at 19:11
millis()
ormicros()
(tons of tutorials on the web about them). Though that does not work for high frequency. Please define your exact requirements. What frequency are we talking about? How are the pulses shaped? Do you need to do other things besides that?pseudo code
that can be translated to real code