Analog sample rate question

Hi, I am new to Arduino. I have completed some tutorials and I am now trying to write my first program based on a tutorial I completed. I am using a piezo knock sensor and I would like to sample at a rate of 50Hz. Since 50Hz has a period of 0.01s I’ve assumed that I need a delay of 10 milliseconds after each analogRead.

for(int i=0; i<64; i++){
piezoOutput = analogRead(analogPin);

  • delay(10);*
  • }*
    Is my reasoning correct?
    I’ve also noticed that where code contains a Serial.print there is a delay at the end of the loop section to avoid overloading the serial port, is that necessary to do?
    Many Thanks in advance

You should not use delay() in anything but a rough demo program because the Arduino can do nothing during the delay interval. The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking.

There is another problem with your use of delay() in your posted code - it does not take account of the time required by the other lines of the program so the interval will always be greater than 10 millisecs. If you use millis() it is easy to avoid that problem.

You are right to think that the Arduino can print to the Serial port too fast. Again, decide on a suitable interval - perhaps once or twice per second - and use millis() to make that happen.

You may also want to consider whether the use of a FOR loop is appropriate. If it was my project I would just make one analog reading in each iteration of loop().

...R
Planning and Implementing a Program

Thank you! That was really helpful :slight_smile: