Go Down

Topic: Timer Question (Read 141 times) previous topic - next topic

nick321

If I want get the analogread data every 10ms, but also I want get the peak to peak voltage every 1000ms

but in 1000ms I can get the analogread data, after 1000ms I just can't go back to the analogread .

Don't know how to fix my code.......  THX


#include <Timer.h>


Timer tcb;
Timer tcb2;

void analogread() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
 
}

void vpp() {
const int sampleWindow = 1000; // Sample window width in mS
unsigned int sample;

   unsigned long startMillis= millis();  // Start of sample window
   unsigned int peakToPeak = 0;   // peak-to-peak level
 
   unsigned int signalMax = 0;
   unsigned int signalMin = 1024;
 
   // collect data for 1S
   while (millis() - startMillis < sampleWindow)
   {
      sample = analogRead(A0);
      if (sample < 1024)  // toss out spurious readings
      {
         if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
      }
   }
   peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
   double volts = (peakToPeak * 5) / 1024;  // convert to volts
 
   Serial.println(volts);
}
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
    tcb.every(1000, vpp);
    tcb2.every(10, analogread);
}

// the loop routine runs over and over again forever:
void loop() {
   tcb.update();
   tcb2.update();
 
}

Robin2

I don't know anything about the Timer library.

What you want to do would be easy using millis() as illustrated in Several Things at a Time

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

Go Up