Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5001

Interfacing (DSI, CSI, I2C, etc.) • Serial data parse and save in file interrupt after seconds.

$
0
0
Hey,

my program stops after writing 200-300 lines in the file and i can not find the problem. Has somebody an idea?

Code:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/time.h>#include <time.h>#include <fcntl.h>#include <unistd.h>#include <termios.h>#define SERIAL_PORT_GPS "/dev/serial0"#define BAUD_RATE_GPS B921600#define MAX_SENTENCE_LENGTH 256#define FILENAME_LENGTH 24 // 20 Zeichen für Datum und Uhrzeit + 4 Zeichen für ".vbo"#define START_WRITING_THRESHOLD 0 // Anzahl der Zeilen, nach denen das Schreiben beginnen sollFILE *fileWriter;char filename[FILENAME_LENGTH];double totalDistance = 0.0;struct timeval prevTime;char lastTimestamp[15] = ""; // Speichert den zuletzt verarbeiteten Zeitstempelvoid generateFilenameAndHeader() {    time_t t = time(NULL);    struct tm *tm_info = localtime(&t);    strftime(filename, FILENAME_LENGTH - 4, "data/%y%m%d_%H%M%S", tm_info);    strcat(filename, ".vbo");    fileWriter = fopen(filename, "w");    if (fileWriter == NULL) {        fprintf(stderr, "Fehler beim Öffnen der Datei zum Schreiben.\n");        return;    }    char timestamp[20];    strftime(timestamp, sizeof(timestamp), "%Y/%m/%d at %H:%M:%S", tm_info);    fprintf(fileWriter, "File created on %s\n", timestamp);    // Daten aus header.txt lesen und anhängen    FILE *headerFile = fopen("header.txt", "r");    if (headerFile != NULL) {        char line[256];        while (fgets(line, sizeof(line), headerFile) != NULL) {            fprintf(fileWriter, "%s", line);        }        fclose(headerFile);    } else {        fprintf(stderr, "Fehler beim Lesen der Header-Datei.\n");    }}void parseNMEA(char *data) {    char *token = strtok(data, ",");    int count = 1;    char timestamp[15], latitude[15], longitude[15], latitudeDirection, longitudeDirection, speedKnots[15];    while (token != NULL) {        if (count == 1 && strcmp(token, "$GNRMC") != 0) {            return; // Nur "$GNRMC"-Zeilen verarbeiten        } else if (count == 2) {            strcpy(timestamp, token);        } else if (count == 4) {            strcpy(latitude, token);        } else if (count == 5) {            latitudeDirection = token[0];        } else if (count == 6) {            strcpy(longitude, token);        } else if (count == 7) {            longitudeDirection = token[0];        } else if (count == 8) {            strcpy(speedKnots, token);        }        token = strtok(NULL, ",");        count++;    }    // Weitere Verarbeitung nur, wenn die Zeile mit "$GNRMC" beginnt    strcpy(lastTimestamp, timestamp); // Aktualisiere den zuletzt verarbeiteten Zeitstempel    double currentLatitude = atof(latitude);    double currentLongitude = atof(longitude);    double latitudeValue = currentLatitude * 0.6;    double longitudeValue = currentLongitude * 0.6;    if (latitudeDirection == 'S') {        latitudeValue = -latitudeValue;    }    if (longitudeDirection == 'E') {        longitudeValue = -longitudeValue;    }    double speedKph = atof(speedKnots) * 1.852;    double courseValue = 120.0;    // Berechnung der Distanz basierend auf Geschwindigkeit und Zeit    if (prevTime.tv_sec == 0 && prevTime.tv_usec == 0) {        gettimeofday(&prevTime, NULL);    } else {        struct timeval currentTime;        gettimeofday(&currentTime, NULL);        double deltaTime = (double)(currentTime.tv_sec - prevTime.tv_sec) +                           (double)(currentTime.tv_usec - prevTime.tv_usec) / 1.0e6;        double distance = speedKph * deltaTime / 3600.0;  // in Kilometern        totalDistance += distance;        prevTime = currentTime;        double updateRate = 1.0 / deltaTime;  // Update-Rate in Hertz        // Beginne mit dem Schreiben in die Datei, nachdem die Startschwelle erreicht ist        static int sentenceCount = 0;        sentenceCount++;        if (sentenceCount > START_WRITING_THRESHOLD) {            fprintf(fileWriter, "007 %s %.6f %.6f %.2f 120 +00042.30 %.4f %.4f\n", timestamp, latitudeValue, longitudeValue, speedKph, totalDistance, updateRate);            printf("Z: %s, Lat: %.6f, Lon: %.6f, Geschw: %.2f km/h, Kurs: %.2f Grad, Distanz: %.4f km, UpdateRate: %.4f Hz\n",                   timestamp, latitudeValue, longitudeValue, speedKph, courseValue, totalDistance, updateRate);        }    }}int main() {    int serial_port_gps = open(SERIAL_PORT_GPS, O_RDWR | O_NOCTTY);    if (serial_port_gps < 0) {        fprintf(stderr, "Fehler beim Öffnen des seriellen Ports %s. Fehlercode: %d\n", SERIAL_PORT_GPS, serial_port_gps);        return 1;    }    struct termios options;    tcgetattr(serial_port_gps, &options);    cfsetispeed(&options, BAUD_RATE_GPS);    cfsetospeed(&options, BAUD_RATE_GPS);    options.c_cflag |= (CLOCAL | CREAD);    options.c_cflag &= ~PARENB;    options.c_cflag &= ~CSTOPB;    options.c_cflag &= ~CSIZE;    options.c_cflag |= CS8;    tcsetattr(serial_port_gps, TCSANOW, &options);    generateFilenameAndHeader();    char sentence[MAX_SENTENCE_LENGTH];    int index = 0;    int bytesRead;    while (1) {        char data;                // Überprüfe, ob Daten verfügbar sind        bytesRead = read(serial_port_gps, &data, 1);                if (bytesRead > 0) {            if (data == '\n') {                sentence[index] = '\0';                                // Prüfe, ob die Zeile mit "$GNRMC" beginnt                if (strstr(sentence, "$GNRMC") != NULL) {                    parseNMEA(sentence);                }                                index = 0;            } else {                sentence[index] = data;                index++;                if (index >= sizeof(sentence) - 1) {                    fprintf(stderr, "Pufferüberlauf bei der NMEA-Datenverarbeitung.\n");                    index = 0;                }            }            fflush(stdout);        } else if (bytesRead < 0) {            // Fehler beim Lesen            fprintf(stderr, "Fehler beim Lesen vom seriellen Port.\n");            break;        }    }    if (fileWriter != NULL) {        fclose(fileWriter);    }    close(serial_port_gps);    printf("Programm beendet.\n");    return 0;}

Statistics: Posted by neekamp — Tue Apr 30, 2024 11:10 pm



Viewing all articles
Browse latest Browse all 5001

Trending Articles