// Rapsberry Pi: I2C in C - Versione 0.6 - 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 MCP23017.c -std=c99 -o MCP23017 // Run as user with R&W right on /dev/i2c-* (NOT ROOT!) // vv@vvrpi ~ $ ./MCP23017 X // 0 <= X <= 255 // Using MCP23017 - I2C #include #include #include #include #include #include #include #include #include #include #define I2C_ADDR 0x20 // Device adress #define MCP23017_IODIRA 0 // IODIRA (see data sheet) #define MCP23017_IODIRB 1 // IODIRB (see data sheet) #define MCP23017_GPPUA 0x0C // GPPUA (see data sheet) #define MCP23017_GPIOA 0x012 // GPIOA (see data sheet) #define MCP23017_GPIOB 0x013 // GPIOB (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]; printf("Rapsberry Pi: I2C in C - Versione 0.6 - 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"); if (argc != 2) { printf ( "Usage: \n rpi ~ $ ./MCP23017 X\n X is an integer number from 0 to 255\n\n"); exit(-1); } // 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"); // Configure PortB as output buffer[0] = MCP23017_IODIRB; buffer[1] = 0x00; if (write(fd,buffer,2) != 2 ) exit_on_error ("Failed to write to the i2c bus [1]"); // Put data to PortB buffer[0] = MCP23017_GPIOB; buffer[1] = atoi(argv[1]); printf("Write 0x%X to PortB\n\n", buffer[1] ); if (write(fd,buffer,2) != 2) exit_on_error ("Failed to write to the i2c bus [2]"); // Configure PortA as input buffer[0] = MCP23017_IODIRA; buffer[1] = 0xFF; if (write(fd,buffer,2) != 2 ) exit_on_error ("Failed to write to the i2c bus [3]"); // Enable pull-up on PortA buffer[0] = MCP23017_GPPUA; buffer[1] = 0xFF; if (write(fd,buffer,2) != 2) exit_on_error ("Failed to write to the i2c bus [4]"); // Read from PortA buffer[0] = MCP23017_GPIOA; if (write(fd,buffer,1) != 1) exit_on_error ("Failed to write to the i2c bus [5]"); if (read(fd,buffer,1) != 1 ) exit_on_error ("Failed to read from the i2c bus"); printf("Data read from PortA: 0x%X\n\n", buffer[0]); close(fd); return (0); }