/*******************************************************
 Author:					Manfred Langemann
 mailto:					Manfred.Langemann ät t-online.de
 Begin of project:			04.01.2008
 Latest version generated:	04.01.2008
 Filename:					Main.c
 Description:    			Main routine for testing
 							TWI-Slave-main.c
 ********************************************************/
#define F_CPU 8000000

#include <stdio.h>
#include <avr/interrupt.h>
//#include <Internet/General.h>
#include <Internet/RS232.h>
#include <avr/delay.h>
#include <Internet/TWI_Slave.h>
#include <Internet/TWI_Slave.c>

void wait_ms(int miliSec)
{
	_delay_loop_2( 1*(F_CPU/(1000/4)) * miliSec);   // 4 Zyklen warteschleife
}

#include <ch/ch_LCD_2x16.c> //Bib. für LCD

/*
** This main programm demonstrates how to use the
** implemented TWI slave functions. These are:
**	TWIS_Init
**	TWIS_ReadAck
**	TWIS_ReadNack
**	TWIS_Write
**	TWIS_Stop
**	TWIS_ResonseRequired
**
** For testing this program, use the program
** TWI_Master_main.c in the slave uC and connect the
** two TWI lines properly (don't forget to also
** connect GND between Master and Slave!)
**
** Used uC for Slave is ATMega8
*/
int main (void)
	{
	uint8_t		i=0;
	uint8_t		j=0;
	uint8_t		byte[8];
	uint8_t		TWIS_ResonseType;

	lcd_init();

// Clear any interrupt
	cli ();

// Wait 1 second for POR
	_delay_ms(500);

// Initiate RS232
	print ("Hello world..",1,1);

// Start TWI Slave with address 15 and bitrate of 100000 Hz
	TWIS_Init (15, 100000);                                         // BIS Hier schreibt er alles
	print ("Init OK",1,1);
	while (1)
		{
/*
** Check wether something is to do for the TWI slave interface
*/
	if (TWIS_ResonseRequired (&TWIS_ResonseType))                   // Schleife wird nicht bearbeitet!!!
			{
			print ("ok 02",1,1);
			switch (TWIS_ResonseType)
				{
/*
** Slave is requests to read bytes from the master.
** It is expliciltely assumed, that the master sends 8 bytes
*/
				case TWIS_ReadBytes:
					print ("Super",1,1);
					for (i=0;i<7;i++)
						{
							byte[i] = TWIS_ReadAck ();
							print("Byte read:",1,1);
							print_dec(byte[i],1,2,1);
						}
					byte[7] = TWIS_ReadNack ();
					print ("Byte read:",1,1);
					print_dec(byte[7],1,2,1);
					TWIS_Stop ();
					break;

// Slave is requested to send bytes to the master.
// It is expliciltely assumed, that the master expects 8 bytes

				case TWIS_WriteBytes:
					print ("Ok 03",1,1);
					for (i=0;i<8;i++)
						{
						TWIS_Write (j++);
						print ("Byte sent:",1,1);
						}
				    TWIS_Stop ();
					break;

				}

			}
/*
** Do something else, e.g.
*/                                                                  // Hier springt er wieder rein
		i++;

		}
	return 0;
	}
