// Rapsberry Pi: I2C in C - Versione 0.61 - Luglio 2013 // Copyright (c) 2013, Vincenzo Villa (https://www.vincenzov.net) // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/RaspberryPi/i2c_c.htm // Compile: gcc LM92.c -std=c99 -o LM92 // Run as user with R&W right on /dev/i2c-* (NOT ROOT!) // vv@vvrpi ~ $ ./LM92 // Using LM92 - I2C #include #include #include #include #include #include #include #include #include #include #define I2C_ADDR 0x4B // Device adress #define LM92_RES 0.0625 // Resolution (see data sheet) static const char *device = "/dev/i2c-1"; // I2C bus static void exit_on_error (const char *s) // Exit and print error code { perror(s); abort(); } int main(int argc, char *argv[]) { int fd; uint8_t buffer[2]; int16_t data; double temperature; printf("Rapsberry Pi: I2C in C - Versione 0.61 - Luglio 2013\n"); printf("Copyright (c) 2013, Vincenzo Villa (https://www.vincenzov.net)\n"); printf("Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported.\n"); printf("Creative Commons | Attribution-Share Alike 3.0 Unported\n"); printf("https://www.vincenzov.net/tutorial/elettronica-di-base/RaspberryPi/i2c-c.htm\n\n"); // Open I2C device if ((fd = open(device, O_RDWR)) < 0) exit_on_error ("Can't open I2C device"); // Set I2C slave address if (ioctl(fd, I2C_SLAVE,I2C_ADDR) < 0) exit_on_error ("Can't talk to slave"); // Read from LM92 (from Power-up default register) printf("Reading from LM92 at address 0x%.2X on %s\n\n", I2C_ADDR, device); if (read(fd,buffer,2) != 2 ) exit_on_error ("Failed to read from the i2c bus"); printf("Data read from Power-up default register: 0x%.2X%.2X\n\n", buffer[0], buffer[1]); data = buffer[0]; data = data << 8; data = data | buffer[1]; data = data >> 3; temperature = LM92_RES * data; printf("Temperature: %2.1f °C\n\n", temperature); close(fd); return (0); }