80 lines
2.0 KiB
C
80 lines
2.0 KiB
C
|
//
|
||
|
// Written for Computer Networks and Systems lab classes
|
||
|
// AUTHOR : Sergiusz Warga
|
||
|
|
||
|
#include <fcntl.h>
|
||
|
#include <math.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <sys/mman.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <unistd.h>
|
||
|
#include <time.h>
|
||
|
|
||
|
#include "CircBuffer.h"
|
||
|
|
||
|
#define PI 3.14
|
||
|
#define SIG_FREQ 100
|
||
|
#define SAM_FREQ 2000
|
||
|
|
||
|
_Noreturn void k_avg(int fd) {
|
||
|
// Exponential Moving Average should be updated with f = 10Hz (i.e. every 200 samples).
|
||
|
int samples = 200;
|
||
|
printf("A k_avg has been called\n");
|
||
|
|
||
|
struct CircBuffer *buffer;
|
||
|
buffer = mmap(NULL, sizeof(struct CircBuffer*), PROT_READ, MAP_SHARED, fd, 0);
|
||
|
if (buffer == MAP_FAILED) {
|
||
|
fprintf(stderr, "mmap: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
struct timespec delay;
|
||
|
delay.tv_sec = 0;
|
||
|
delay.tv_nsec = 100000000ULL*1; // 100ms == 100 000 000ns -> 10Hz
|
||
|
|
||
|
|
||
|
double alpha = 0.1;
|
||
|
double ema;
|
||
|
int start_idx = 0;
|
||
|
|
||
|
|
||
|
while (1) {
|
||
|
start_idx = buffer->info.free_idx;
|
||
|
ema = buffer->data[start_idx];
|
||
|
printf("start_idx = %d\n", start_idx);
|
||
|
printf("EMA = %lf\n", ema);
|
||
|
nanosleep(&delay, NULL);
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
// while (1) {
|
||
|
// start_idx = (buffer->info.free_idx - samples) % buffer->info.size;
|
||
|
// printf("start_idx = %d\n", start_idx);
|
||
|
// ema = buffer->data[start_idx];
|
||
|
// for (int read_idx = start_idx + 1; read_idx < samples; read_idx = ++read_idx % buffer->info.size) {
|
||
|
// ema = alpha*buffer->data[read_idx] + (1 - alpha) * ema;
|
||
|
// printf("EMA[%d] = %lf\n", read_idx, ema);
|
||
|
// }
|
||
|
// printf("EMA = %lf\n", ema);
|
||
|
// nanosleep(&delay, NULL);
|
||
|
// }
|
||
|
|
||
|
}
|
||
|
|
||
|
int main(int argc, char *argv[]) {
|
||
|
|
||
|
//----- Open a shared memory -----
|
||
|
const char *memory_name = "/dsp";
|
||
|
int fd = shm_open(memory_name, O_RDONLY, 0777);
|
||
|
if (fd < 0) {
|
||
|
fprintf(stderr, "shm_open: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
printf("Shared memory file descriptor: %d\n", fd);
|
||
|
|
||
|
k_avg(fd);
|
||
|
|
||
|
return 0;
|
||
|
}
|