Right, I have rethought the input function into a slightly more logical structure and it seems to work now. I would still value peoples input as to whether I am missing something.
Am I right in that the previous code was messing with the arrays and accessing them out of their range?
Code:
/* Program to compute the RMS value or 1024 Samples 16-bit 2's comp data.
This program has been designed to run a rolling block of samples so
that once the initial block of 1024 samples has been aquired the program
rms is then calculated each time a new sample is added and the oldest sample
is removed from the block*/
#include <stdio.h>
#include <math.h> // Library required for using sqrt function
#define MAX 10 // sample block, in this case 1024
#define DATA 50 // size of test data
//function to calculate rms and print output to screen
float rms(long total)
{
printf("rms = %f\n", sqrt(total / MAX));
return 0;
}
/* Function to accept input into the program. The input is stored as a
squared number to simplify the process of swapping the oldest sample
with the newest sample. */
void input(long samples[])
{
int i;
int j;
int value;
long total;
int test[DATA];
/* This for loop is here to represent input data to the program from a circuit.
a sine wave with an amplitude of 340 has been used with the expected result of
around 240, the same as UK mains voltage. */
for (j = 0; j < DATA; ++j) {
test[j] = 340 * sin(j);
printf("%d\n", test[j]);
}
j = 0;
while (j < DATA) {
for (i = 0; i < MAX; ++i) {
total -= samples[i]; // Removes oldest sample from array
value = test[i]; // Gets new data, in this case from the array "test".
samples[i] = value * value;
total += samples[i];
rms(total);
}
++j;
}
}
// Function to initialize array for 1024 samples
void init()
{
int i;
long samples[MAX];
for (i = 0; i < MAX; ++i) {
samples[i] = 0;
}
input(samples);
}
// Program start
int main(void)
{
init();
return 0;
}
Kind regards
P166