// 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-2.c -std=c99 -o LM92-2 // Run as user with R&W right on /dev/i2c-* (NOT ROOT!) // vv@vvrpi ~ $ ./LM92-2 // Using LM92 - I2C #include #include #include #include #include #include #include #include #include #include #define I2C_ADDR 0x4B // Device adress #define LM92_TEMP 0 // Temperature register (see data sheet) #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; int16_t data; int32_t SMBUS_word; double temperature; printf("Rapsberry Pi: I2C in C - Versione 0.64 - 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 printf("Reading from LM92 (bus: %s Address: 0x%.2X Register: %d)\n\n", device, I2C_ADDR,LM92_TEMP); if ( (SMBUS_word = i2c_smbus_read_word_data (fd , LM92_TEMP)) < 0) exit_on_error ("Error reading from SMBus"); printf("Data read (as integer): 0x%X\n\n", SMBUS_word); // Convert to °C (see data sheet) data = ((SMBUS_word >> 8) | (SMBUS_word << 8)) & 0xFFFF; data = data >> 3; temperature = LM92_RES * data; printf("Temperature: %2.1f °C\n\n", temperature); close(fd); return (0); }