thx M. Gibert :)

This commit is contained in:
Loic Delattre 2023-04-28 17:01:27 +02:00
parent 7837fb9c94
commit 85313b8104
1 changed files with 89 additions and 6 deletions

View File

@ -1,11 +1,94 @@
const int _portBaud = 9600; // baud rate of the serial port
unsigned long samplingTimestamp = 0;
const unsigned int nbSamples = 10; // number of samples to compute mean and std
unsigned long sampleTimestamps[nbSamples]; // array containing the timestamps
unsigned int sampleIndex = 0; // current sample index
// predivisor: possible values 1, 8, 64, 256, 1024
// Register TCCR#B
// CS#0 -> 1
// CS#1 -> 8
// CS#0 CS#1 -> 64
//CS#2 -> 256
// CS#0 CS#2 -> 1024
// register 0 and 2 are 8 bits -> max value 256
// register 1 is 16 bits -> max value 65535
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void setup()
{
// initializes the serial port
Serial.begin(_portBaud);
void loop() {
// put your main code here, to run repeatedly:
// stops interrupts
cli();
// sets timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;// initialize counter value to 0
// sets compare match register for 1hz increments
OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be < 65536)
// turns on CTC mode
TCCR1B |= (1 << WGM12);
// set CS10 and CS12 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
//allow interrupts
sei();
}
ISR(TIMER1_COMPA_vect)
{
//change the 0 to 1 for timer1 and 2 for timer2
//interrupt commands here
// initializes the timer
unsigned long startTime = micros();
// estimates sampling duration
unsigned long samplingDuration = startTime - samplingTimestamp;
samplingTimestamp = startTime;
//Serial.println(samplingDuration);
if (sampleIndex < nbSamples)
{
sampleTimestamps[sampleIndex] = samplingDuration;
sampleIndex++;
}
//reads data once on pin A0
analogRead(0);
}
void loop()
{
if (sampleIndex == nbSamples)
{
// average
double timestampAverage = 0;
for (int l_sample=0; l_sample < nbSamples; l_sample++)
{
timestampAverage += (double)sampleTimestamps[l_sample]/nbSamples;
}
Serial.print("average= ");
Serial.println(timestampAverage); // print the timestamp average
// variance
double timestampVariance = 0;
for (int l_sample=0; l_sample < nbSamples; l_sample++)
{
timestampVariance += pow((double)(sampleTimestamps[l_sample]-timestampAverage), 2.0)/nbSamples;
}
Serial.print("variance= ");
Serial.println(timestampVariance); // print the timestamp average
sampleIndex = 0;
}
}