Setting a timer to count analogRead input for 3 seconds

Thread Starter

Rickpercy87

Joined Nov 20, 2015
18
I should mention this is for Arduino.

Hello, I would like the analogRead function to count the input from a sensor over three seconds.
Basically my analogue read it reading about ten values per second.
I would like it to add the total number counted from the analogue input over three seconds and output and ALARM if a threshold is exceeded.

Thank you:
Here is the code I have so far:
C:
const int analogPin = 0; // input from sensor
const int threshold = 3; //threshold sensor warning alarm
int ledPin = 13;
int buzzerPin = 8;  //alarm
void setup()

{
  Serial.begin(9600);
  pinMode (ledPin, OUTPUT);
  pinMode (buzzerPin, OUTPUT); 

}

void loop() {
  int mn = 1023;     // mn only decreases
  int mx = 0;        // mx only increases

  // Perform 750 reads. Update mn and mx for each one.
  for (int i = 0; i < 750  ; ++i) {
    int val = analogRead(analogPin);
    mn = min(mn, val);
    mx = max(mx, val);

  }
{

if (threshold > mn){


digitalWrite (ledPin, HIGH); // lights the LED
delay (100); // time LED stays lit once a rigger is met
tone (8, 1500, 100); // warning alarm once the threshold is met
delay (100);
tone (8, 1000, 100);
delay(100);
tone (8, 1500, 100);
delay (100);
tone (8, 1000, 100);
delay(100);
tone (8, 1500, 100);
delay (100);
tone (8, 1000, 100);
delay(100);
tone (8, 1500, 100);
delay (100);
tone (8, 1000, 100);
delay(100);
}

else {
digitalWrite (ledPin, LOW); //LED is turned off if there is no movement
analogWrite (buzzerPin, LOW);
}

  // Send min, max and delta over Serial
  Serial.print("m=");
  Serial.print(mn);
  Serial.print(" M=");
  Serial.print(mx);
  Serial.print(" D=");
  Serial.print(mx-mn);
  Serial.println();
}}
Mod edit: Please use code tags to post code.
 
Last edited by a moderator:

mcgyvr

Joined Oct 15, 2009
5,394
So you want to get 30 readings (10 per second) over 3 seconds?
How accurate on the time and number of readings do you need it to be?
Exactly how fast can you get 1 reading now?
 

dannyf

Joined Sep 13, 2015
2,197
Hello, I would like the analogRead function to count the input from a sensor over three seconds.
Basically my analogue read it reading about ten values per second.
I would like it to add the total number counted from the analogue input over three seconds and output and ALARM if a threshold is exceeded.
Wouldn't just be adding up readings over 3 seconds, or adding up 3x10 readings?

So approach 1

Code:
  time_start=time(); //start time now
  sum=0;
  while (time() - time_start < 30 seconds) sum+=adc_reading();
or approach 2
Code:
  count=0;
  sum=0;
  while (count++ < 30) sum+=adc_reading();
Pick whatever you want.
 
Top