/*
   A simple test for my PCF 8574A device on 0x70 on Raspberry bus 0
   We need to open, write, read, and close.
   Here is my test code. I used this to write and then read
   0xAA in PCF8574A (device address 0x70).
   As there is a switch at bit 7; depending on the state
   it will read back as 0xAA (switch open) or 0x2A (closed)

   Compile with gcc -o i2c_pcf8574a i2c_pcf8574a.c
   Run with ./i2c_pcf8574a
   
   Kees Moerman, June 2010
*/

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>

int main(){

    int file;
    int addr = 0x70 >> 1;
    unsigned short reg = 0x10;
    char buf[10];
    int n;

    if ((file = open("/dev/i2c-0", O_RDWR)) < 0) {
        printf("open error!\n");
        exit(1);
    }

    if (ioctl(file,I2C_SLAVE_FORCE,addr) < 0) {
        printf("address error!\n");
        exit(1);
    }

    buf[0] = 0xAA;
    buf[1] = 0;


    printf("write: 0x%X\n", buf[0]);
    n=write(file,buf,1);
    if (n != 1) {
        printf("write error! %d\n",n);
        exit(1);
    }

    n=read(file,buf,1);
    if (n != 1) {
        printf("read error! %d\n",n);
        exit(1);
    } else {
        printf("read: 0x%X\n", buf[0]);
    }

    close(file);
}
