//This routine calls a PCF8574 with adress "chip1" and send "signal1" for output
//Compiler: MPLAB C18 v3.10

//set configuration bits 
#pragma    config WDT =OFF      //Watchdog timer disabled 
#pragma    config MCLRE =ON     //Master Clear Reset enabled 

//includes
#include <p18cxxx.h>
#include <delays.h>
#include <stdlib.h>
#include <i2c.h>
           
//constants
const char signal1 = 0b00000001;

/* 
  PCF8574 used for OUT / PCF8574A used for IN
  PCF8574 slave adress: 0 1 0 0 A2 A1 A0 x -> 64 to 78
  PCF8574A slave adress 0 1 1 1 A2 A1 A0 x -> 112 to 126
  X = 0 -> write data; X = 1 -> read data
*/
const char chip1 = 64;  // =0x40, A0 = 0, A1 = 0, A2 = 0, X = 0

unsigned char send_i2c(unsigned char addr, unsigned char data)
{
  IdleI2C();
  StartI2C();
  IdleI2C();
  putcI2C(addr);
  IdleI2C();
  if ( SSPCON2bits.ACKSTAT )  // test received ack bit state
  {
	StopI2C();
   	return 0;            // bus device responded with  NOT ACK
  }                        
  putcI2C(data);
  IdleI2C();
  if ( SSPCON2bits.ACKSTAT )  // test received ack bit state
  {
    StopI2C();
    return 0;            // bus device responded with  NOT ACK
  }                        
  StopI2C();
  return 1;

}// of send_i2c

void main (void)
{ 
  /*
    Set SDA and SCL
  */
  TRISCbits.TRISC3 = 1;
  TRISCbits.TRISC4 = 1;

  /*
    MASTER I2C Master mode
    SLEW_OFF Slew rate disabled for 100 kHz mode
  */
  OpenI2C(MASTER, SLEW_OFF);

  /* 
    When the SSP is configured in Master mode, 
    the lower seven bits of SSPADD act as the Baud Rate Generator reload value.
    e.g.:
    PIC-Takt (MHz)  4, 8, 10, 12, 16, 20
    SSPADD für 100 kHz 9, 19, 24, 29, 39, 49
    SSPADD für 400 kHz 2, 4, 6, 7, 9, 12
    SSPADD = (FREQ/(4 * SCL))-1
  */ 
  SSPADD = 19;  // 100KHz and 8MHz

  
  while(1)
  {
    if (send_i2c(chip1, signal1)) 
    {
      //transmission was ok
    }// of if
    else
    {
      // problem while transmitting (no ACK received)
    }// of else
  }// of while(1)
}// of main

