I want to count peak of photocell data with serial communication in Arduino.
Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.
If somebody can help me with the coding part I would appreciate it.
Here is the code that I used:
int count=0;
int val;
int data;
void setup() {
Serial.begin(115200);
}
void loop() {
data=analogRead(A0);
val=map(data,0,1023,1000,0);
if(val>700) {
count++;
}
Serial.println(count);
delay(100);
}
This picture shows what I am trying to achieve:
Counting the peaks
Example Michelson Morley fringes:
Example Michelson Morley fringes
1 Answer 1
keep in mind that since you used
delay(100)
your 'loop' code runs in 10HZ (10 times a second) So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition
(val>700)
is satisfied.
If you know that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:
int count=0;
int val;
int data;
bool inPeak = false;
void setup() {
Serial.begin(115200);
}
void loop() {
data=analogRead(A0);
val=map(data,0,1023,1000,0);
if(val>700) {
if (!inPeak)
{
count ++;
inPeak = true;
}
}
else
{
inPeak = false;
}
Serial.println(count);
delay(100);
}
Explore related questions
See similar questions with these tags.