0

I am trying to implement a circular buffer to acquire data from an accelerometer and exporting the information to a csv. The readings from the accelerometer must have a constant period. I used the p_thread to run both reading and exporting functions at the same time, but it is giving me a segmentation fault error. Also, I am not sure if using p_thread I can export multiple values. Can you help me with my problem please?

#include <stdio.h>
#include "MPU-9150.h"
#include <stdint.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#define nBuff   32

struct thread_data{
   double ax_buff[nBuff];
   double ay_buff[nBuff];
   double gz_buff[nBuff];
   int n_int;
   int n_save;
};

void *reader( void *threadarg) {
    int ret;
    struct thread_data *my_data;
    my_data = (struct thread_data *) threadarg;
    time_t usecs = 0.005; // 0.005 seconds
    while(1) {
        time_t ustartTime = time(NULL);
        while (time(NULL) - ustartTime == usecs) {
            if (my_data->n_int + 1 != my_data->n_save) {
                ret = imupi_read( my_data->ax_buff[my_data->n_int], my_data->ay_buff[my_data->n_int], my_data->gz_buff[my_data->n_int] );
                if ( ret )  {
                    mpu_read_error(ret);
                }
            my_data->n_int = (my_data->n_int+1) % nBuff;
            }
        }
    }
}

void main( void ) {
    int ret;
    // Set acquisition timer
    struct thread_data data;
    pthread_t my_thread;

    // Initialization of the MPU-9150
    if ( ret = imupi_init( ) )  {
        mpu_init_error(ret);
    }

    //Open Data File
    /*FILE *fid = fopen("mpu_cal.csv", "w");
    if (fid == NULL) {
        perror("Error opening file\n");
        exit(1);
    }*/

    if (pthread_create(&my_thread, NULL, reader, (void *) &data)) {
        fprintf(stderr, "Error creating thread\n");
        exit(1);
    }

    // Set full timer
    time_t secs = 30; // 30 seconds
    time_t startTime = time(NULL);
    while (time(NULL) - startTime < secs) {     

        if (data.n_save != data.n_int) {
            printf( "%f,%f,%f\n", data.ax_buff[data.n_save], data.ay_buff[data.n_save], data.gz_buff[data.n_save]);
            //fflush(stdout);
            data.n_save = (data.n_save+1) % nBuff;
        }
    }
    //fclose(fid);
    exit(1);
}

1 Answers1

0

You aren't initialising data.n_int and data.n_save. The simplest fix is adding an initialiser to the declaration:

struct thread_data data = { .n_int = 0, .n_save = 0 };

Also, you are passing double values to imupi_read() when it appears it should take pointers instead:

ret = imupi_read(&my_data->ax_buff[my_data->n_int],
    &my_data->ay_buff[my_data->n_int], &my_data->gz_buff[my_data->n_int]);

Another problem you will face is that on common platforms time_t is an integral type, so assigning 0.005 to usecs will just set it to zero.

caf
  • 233,326
  • 40
  • 323
  • 462