Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h> /* exit, EXIT_FAILURE */
- #include <fcntl.h>
- #include <linux/i2c-dev.h>
- #include <errno.h>
- #include <sys/ioctl.h>
- #include <unistd.h>
- #define I2C_ADDR 0x20
- #define DEV_I2C "/dev/i2c-0"
- /*--------------------------------------------------------------------*/
- int I2COpen(){//Return fd
- int fd;
- fd = open(DEV_I2C, O_RDWR);
- if (fd < 0) {
- printf("Error opening file: \n");
- return -1;
- }
- if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0) {
- printf("ioctl error: \n");
- return -1;
- }
- return fd;
- };
- /*--------------------------------------------------------------------*/
- void I2CSetup (int fd) {//Setup mcp23017
- char buffer[2];
- buffer[1]=0x00;//Valeur register
- //Clear ports mcp23017 GPIOB OUTPUT
- for( size_t reg=0x01 ;reg<0x10;reg++){
- buffer[0]=reg;//load register
- write(fd,buffer,2);
- usleep(1000);
- }
- //GPIOA INPUT
- buffer[0]=0x00;//Register IODIRA
- buffer[1]=0xFF;// Value INPUT
- write(fd,buffer,2);
- };
- /*--------------------------------------------------------------------*/
- int iI2CRead (int fd) {//Read GPIOA
- char buffer[2];
- buffer[0]=0x12;//GPIOA
- write(fd,buffer,1);
- read(fd, &buffer[1], 1);
- return buffer[1];
- };
- /*--------------------------------------------------------------------*/
- void iI2CWrite (int fd, unsigned char data){//write GPB
- char buffer[2];
- buffer[0]=0x13;//GPIOB
- buffer[1]=data;
- write(fd,buffer,2);
- };
- /*--------------------------------------------------------------------*/
- /*--------------------------------------------------------------------*/
- int main (void) {
- char buffer[2];
- int fd(-1);
- if ( (fd=I2COpen()) <0){exit (0);}
- I2CSetup (fd);//SetUp mcp23017
- //Read GPIOA
- printf("0x%02X\n",iI2CRead (fd));
- usleep(100000);
- //Write GPIOB
- buffer[1]=0xAA;//Write data
- iI2CWrite (fd, buffer[1]);//write GPB
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement