1

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

sa_leinad
3,2182 gold badges23 silver badges51 bronze badges
asked Jan 13, 2017 at 12:54

1 Answer 1

2

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);
}
answered Jan 13, 2017 at 18:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.