/*
**     $Author: Bipsen $
**     $Filename: test_lib.c $
**     $Release: 1.00 $
**     $Revision: 37.3 $
**     $Date: 1994/01/07 20:24:10 $
** 
**     Small testprogram for i2c.library
**
*/

#include <exec/libraries.h>
#include <libraries/dos.h>
#include <stdio.h>
#include <proto/exec.h>
#include <proto/dos.h>

#include "i2c_library.h"

#define MaxNumI2C 200

#ifndef __SASC_60
struct Library *I2C_Base=NULL;
#endif

int main (void)
{
	UBYTE           i2cdata[MaxNumI2C];
	int             count;
	int             ErrorBack = RETURN_FAIL;

	char            kar;
	int             i;

#ifndef __SASC_60
	if(!(I2C_Base=OpenLibrary("i2c.library",37L)))
		{
		Printf("You need i2c.library v37+ in your LIBS: drawer!\n");
		return(RETURN_ERROR);
		}
#endif

	if ((i=AllocI2C(DELAY_TIMER,"I2C_Test-program")))
		{
		switch(i)
			{
			case	I2C_BITS_BUSY:
						Printf ("Some bits in use, cannot allocate!\n");
						break;
			case	I2C_NO_MISC_RESOURCE:
						Printf ("Cannot find misc.resource ???\n");
						break;
			case	I2C_ERROR_PORT:
						Printf ("Cannot allocate port!\n");
						break;
			case	I2C_ACTIVE:
						Printf ("I2C-bus already active!\n");
						break;
			case	I2C_NO_TIMER:
						Printf ("Cannot open timer!\n");
						break;
			}
			fflush (0l);
			ErrorBack = RETURN_ERROR;
		}
	else
		{
		/* I2C-bus is allocated, we can now do whatever we want */
		/* with it                                              */
		Printf("I2C-bus is succesfully allocated !\n");
		fflush (0l);
		ErrorBack = RETURN_OK;

		/* initialise port and set I2C-bus to default */
		InitI2C ();

		SetDelay(1000);

		/* sending data  to I/O device at 0x40 (write-adres)   */
		/* The I/O device is a PCF8574P                        */

		i2cdata[0] = 0xAA;

		for (i = 0; i < 5; ++i)
			{
			if (!SendI2C (0x40, 1, i2cdata))
				Printf ("Error sending data to device 0x40 ... \n");
			i2cdata[0] = ~i2cdata[0];
			}


		/* receiving 10 bytes from the I/O device at 0x41 (read-adres) */

		if (!ReceiveI2C (0x41, 10, i2cdata))
			Printf ("Error receiving data from device 0x41 ... \n");
		else
			for (count = 0; count < 10; count++)
				Printf ("Byte %2ld was %lx hex. \n", count + 1, i2cdata[count]);


		Printf ("Press return to free port and deallocate I2C-bus\n");
		fflush (0l);

		scanf ("%c", &kar);

		FreeI2C ();
		}
#ifndef __SASC_60
	CloseLibrary(I2C_Base);
#endif

	return (ErrorBack);
}
