Hello everyone,
I am new in this world called Arduino and I am doing a tachometer that reads and storage the RPM from a motor (12V DC) everything is working well, but, I would like to calculate the average of every minute and storage it instead of all measurements.
BTW this is my code.
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
File dataFile;
int encoder_pin = 2; // The pin the encoder is connected
unsigned int rpm; // rpm reading
volatile byte pulses; // number of pulses
unsigned long timeold; // The number of pulses per revolution
unsigned int pulsesperturn = 1; //Number of blades
void counter()
{
//Update count
pulses++;
}
//-----------------------------------
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(SS, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
// Open up the file we're going to log to!
dataFile = SD.open("datalog.txt", FILE_WRITE);
if (! dataFile) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
while (1) ;
}
//-----------code for RPM---------------
//Use statusPin to flash along with interrupts
pinMode(encoder_pin, INPUT);
//Interrupt 0 is digital pin 2, so that is where the IR detector is connected
//Triggers on FALLING (change from HIGH to LOW)
attachInterrupt(0, counter, FALLING);
// Initialize
pulses = 0;
rpm = 0;
timeold = 0;
}
void loop()
{
if (millis() - timeold >= 1000){
/Uptade every one second, this will be equal to reading frecuency (Hz)./
//Don't process interrupts during calculations
detachInterrupt(0);
rpm = (60 * 1000L / pulsesperturn )/ (millis() - timeold)* pulses;
timeold = millis();
pulses = 0;
//Write it out to serial port
Serial.print("RPM = ");
Serial.println(rpm,DEC);
//Restart the interrupt processing
attachInterrupt(0, counter, FALLING);
}
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}
dataFile.print("RPM = ");
dataFile.println(rpm);
dataFile.flush();
delay(1000);
}