83 lines
2.3 KiB
C
83 lines
2.3 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"
|
|
#include "funs.h"
|
|
|
|
int crosses_zero(double prev, double curr) {
|
|
// let's just ignore 0 for now
|
|
return (prev > 0 && curr < 0) || (prev < 0 && curr > 0);
|
|
}
|
|
|
|
_Noreturn void k_f0(int fd, int sampling_frequency, int refreshing_frequency) {
|
|
printf("A k_f0 has been called\n");
|
|
|
|
//----- Initialize the buffer -----
|
|
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 tic, toc;
|
|
// delay.tv_sec = 0;
|
|
// delay.tv_nsec = (1./refreshing_frequency * 1000000000L); // 1/f in nanoseconds
|
|
unsigned long long delay = NSEC_PER_SEC*1./refreshing_frequency;
|
|
clock_gettime(CLOCK_REALTIME, &tic);
|
|
|
|
int transitions = 0;
|
|
int samples = 0;
|
|
int read_idx;
|
|
|
|
read_idx = buffer->info.free_idx - 1;
|
|
|
|
while (1) {
|
|
clock_gettime(CLOCK_REALTIME, &toc);
|
|
if (timespec_diff_nano(&toc, &tic) > delay) {
|
|
double t_samp = 1./sampling_frequency;
|
|
// printf("t_samp = %fs\n", t_samp);
|
|
// printf("n_samp = %d\n", samples);
|
|
double t_anal = t_samp*samples;
|
|
// printf("t_anal = %fs\n", t_anal);
|
|
// printf("n_tran = %d\n", transitions);
|
|
printf("f = %fHz\n", transitions/(2*t_anal));
|
|
transitions = 0;
|
|
samples = 0;
|
|
clock_gettime(CLOCK_REALTIME, &tic);
|
|
}
|
|
|
|
if (crosses_zero(buffer->data[read_idx-1], buffer->data[read_idx])) {
|
|
++transitions;
|
|
}
|
|
while (read_idx == ((buffer->info.free_idx - 1) % buffer->info.size)) {};
|
|
read_idx = ++read_idx % buffer->info.size;
|
|
++samples;
|
|
}
|
|
}
|
|
|
|
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_f0(fd, 2000, 1);
|
|
|
|
return 0;
|
|
} |