#include #include #include #include #include #include #include #include #define I2C_DEVICE "/dev/i2c-1" #define SLAVE_ADDR 0x50 #define DATA_ADDR 0x54 // Function to write a sequence to the I2C device int i2c_write_sequence(int file, uint8_t *sequence, uint8_t length) { return write(file, sequence, length); } // Function to read data from the I2C device int i2c_read(int file, uint8_t *data, uint8_t length) { return read(file, data, length); } int main() { int file; // Open the I2C device if ((file = open(I2C_DEVICE, O_RDWR)) < 0) { perror("Failed to open the I2C bus"); return 1; } // Set the slave address for the length command if (ioctl(file, I2C_SLAVE, SLAVE_ADDR) < 0) { perror("Failed to set slave address"); close(file); return 1; } // Step 1: Send command to read NMEA data length uint8_t length_command[] = {0x08, 0x00, 0x51, 0xAA, 0x04, 0x00, 0x00, 0x00}; usleep(10000); if (i2c_write_sequence(file, length_command, sizeof(length_command)) < 0) { perror("Failed to send length command 1"); close(file); return 1; } usleep(10000); // Switch to data address if (ioctl(file, I2C_SLAVE, DATA_ADDR) < 0) { perror("Failed to set slave address for data"); close(file); return 1; } uint8_t length_data[4]; if (i2c_read(file, length_data, 4) < 0) { perror("Failed to read NMEA length"); close(file); return 1; } usleep(10000); // Calculate the NMEA data length uint8_t nmea_length = (length_data[3] << 24) | (length_data[2] << 16) | (length_data[1] << 8) | length_data[0]; printf("NMEA Data Length: %d bytes\n", nmea_length); if (nmea_length <= 0 || nmea_length > 1024) { fprintf(stderr, "Invalid NMEA data length.\n"); close(file); return 1; } // Step 2: Send command to read NMEA data uint8_t data_command[] = {0x00, 0x20, 0x51, 0xAA, nmea_length, 0x00, 0x00, 0x00}; if (ioctl(file, I2C_SLAVE, SLAVE_ADDR) < 0) { perror("Failed to set slave address"); close(file); return 1; } usleep(10000); if (i2c_write_sequence(file, data_command, sizeof(data_command)) < 0) { perror("Failed to send data command"); close(file); return 1; } usleep(10000); // Allocate buffer for NMEA data uint8_t *nmea_data = malloc(nmea_length); if (!nmea_data) { perror("Memory allocation failed"); close(file); return 1; } if (ioctl(file, I2C_SLAVE, DATA_ADDR) < 0) { perror("Failed to set slave address for data"); close(file); return 1; } if (i2c_read(file, nmea_data, nmea_length) < 0) { perror("Failed to read NMEA data"); free(nmea_data); close(file); return 1; } usleep(10000); printf("Raw NMEA Data:\n"); for (int i = 0; i < nmea_length; i++) { printf("%c", nmea_data[i]); } printf("\n"); free(nmea_data); close(file); return 0; }