/*********************************************
This program was produced by the
CodeWizardAVR V1.24.0 Standard
Automatic Program Generator
© Copyright 1998-2003 HP InfoTech s.r.l.
http://www.hpinfotech.ro
e-mail:office@hpinfotech.ro

Project : 
Version : 
 Date    : 29.01.2009
Author  : ij                              
Company :                                 
Comments: 


Chip type           : ATmega8
Program type        : Application
Clock frequency     : 16,000000 MHz
Memory model        : Small
External SRAM size  : 0
Data Stack size     : 256
*********************************************/

#include <mega8.h>
#include <io.h>
#include "ausgabe.h"
#include "rw.h" 
#include <stdint.h>
#include <delay.h>  
#include <stdio.h>


// I2C Bus functions
#asm
   .equ __i2c_port=0x15
   .equ __sda_bit=4
   .equ __scl_bit=5
#endasm
#include <i2c.h>

#define EEPROMADD_write 0xA0 // EEPROM adresse schreiben 


#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];
unsigned char rx_wr_index,rx_rd_index,rx_counter;
// This flag is set on USART Receiver buffer overflow
bit rx_buffer_overflow;

//------------------------------------------------------------------------------------------- USART Receiver interrupt service routine
#pragma savereg-
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
#asm
    push r26
    push r27
    push r30
    push r31
    in   r26,sreg
    push r26
#endasm
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
   {
   rx_buffer[rx_wr_index]=data;
   if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
   if (++rx_counter == RX_BUFFER_SIZE)
      {
      rx_counter=0;
      rx_buffer_overflow=1;
      };
   };
#asm
    pop  r26
    out  sreg,r26
    pop  r31
    pop  r30
    pop  r27
    pop  r26
#endasm
}
#pragma savereg+

#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer
#define _ALTERNATE_GETCHAR_
#pragma used+
char getchar(void)
{
char data;
while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
#asm("cli")
--rx_counter;
#asm("sei")
return data;
}
#pragma used-
#endif

// USART Transmitter buffer
#define TX_BUFFER_SIZE 8
char tx_buffer[TX_BUFFER_SIZE];
unsigned char tx_wr_index,tx_rd_index,tx_counter;

// USART Transmitter interrupt service routine
#pragma savereg-
interrupt [USART_TXC] void usart_tx_isr(void)
{
#asm
    push r26
    push r27
    push r30
    push r31
    in   r26,sreg
    push r26
#endasm
if (tx_counter)
   {
   --tx_counter;
   UDR=tx_buffer[tx_rd_index];
   if (++tx_rd_index == TX_BUFFER_SIZE) tx_rd_index=0;
   };
#asm
    pop  r26
    out  sreg,r26
    pop  r31
    pop  r30
    pop  r27
    pop  r26
#endasm
}
#pragma savereg+

#ifndef _DEBUG_TERMINAL_IO_
// Write a character to the USART Transmitter buffer
#define _ALTERNATE_PUTCHAR_
#pragma used+
void putchar(char c)
{
while (tx_counter == TX_BUFFER_SIZE);
#asm("cli")
if (tx_counter || ((UCSRA & DATA_REGISTER_EMPTY)==0))
   {
   tx_buffer[tx_wr_index]=c;
   if (++tx_wr_index == TX_BUFFER_SIZE) tx_wr_index=0;
   ++tx_counter;
   }
else
   UDR=c;
#asm("sei")
}
#pragma used-
#endif

// Standard Input/Output functions
#include <stdio.h>

//---------------------------------------------------------------------------------------------------Timer 1 overflow interrupt service routine
interrupt [TIM1_OVF] void timer1_ovf_isr(void)
{
 
static unsigned int zeit;
char kontakt; 
//static unsigned int regadd_w_1 = 0x00;    
static unsigned char regadd_w_0 = 0x00;
static unsigned char regadd_w_1 = 0x00;
static unsigned int  regadd_w_1_z = 0x00;
// Reinitialize Timer 1 value
TCNT1H=0x9E;
TCNT1L=0x57;
// Place your code here 

    if ( regadd_w_1_z <= 16)
        {       
         if(regadd_w_0 != 252)
                {
                 kontakt = PINB & 0x07; // Kontakt erhält die wertigkeiten der der ersten 3 Pins von PORTB
                 i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0, ((zeit >> 8) & 0xFF));  //zeit geschrieben die ersten (höchsten) 8 Bit schreiben                  Register anorden!!!!!!!
                 i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0+1, (zeit & 0xFF));       //zeit geschrieben  die niedrigsten 8 Bit schreiben                        Register anorden!!!!!!!
                 i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0+2, kontakt);             //Kontakt geschrieben
                 zeit++;
                 regadd_w_0+=3; 
                }
         else
                {
                 regadd_w_0 = 0x00;
                 regadd_w_1++;  
                 regadd_w_1_z++; 
                 if ( regadd_w_1_z <= 16)
                 {       
                        kontakt = PINB & 0x07; // Kontakt erhält die wertigkeiten der der ersten 3 Pins von PORTB
                        i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0, ((zeit >> 8) & 0xFF));  //zeit geschrieben die ersten (höchsten) 8 Bit schreiben                  Register anorden!!!!!!!
                        i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0+1, (zeit & 0xFF));       //zeit geschrieben  die niedrigsten 8 Bit schreiben                        Register anorden!!!!!!!
                        i2c_transmit(EEPROMADD_write, regadd_w_1, regadd_w_0+2, kontakt);             //Kontakt geschrieben
                        zeit++; 
                 }
                }
           //printf("Zähler: %i registerHi: %x ; registerLo: %x \r\n",regadd_w_1_z, regadd_w_1,regadd_w_0);
         }
}





#define ADC_VREF_TYPE 0x40
// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input|ADC_VREF_TYPE;
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}

// Declare your global variables here 
unsigned char karo[720]; 


//------------------------------------------------------------------------------------------------------------------------lokale/globale-Variablen
void main(void)
{ 

// Declare your local variables here
int u = 0x00;                           // Spannungsaufnahme über ADC PC3 
int i_0 = 0x00;                         // Word_Adress_Zähler erstes Byte 
int i_1 = 0x00;                         // Word_Adress_Zähler zweites Byte 
unsigned char instruction = 0x00;       // Anweisung vom Hyper Terminal
unsigned char regadd_r_1 = 0x00;         // Word_Adress erstes Byte 
unsigned char regadd_r_0 = 0x00;         // Word_Adress zweites Byte 
unsigned char ausgabe_z_0 = 0x00;
unsigned char ausgabe_z_1 = 0x00;
unsigned char ausgabe_k = 0x00;
unsigned int regadd_r_1_z = 0x00;
unsigned int ausgabe_zaehler = 0x00;
unsigned char loechen_0 = 0x00;
unsigned char loechen_1 = 0x00;
unsigned int loechen_1_z = 0x00;
unsigned int loechen_0_z = 0x00;


// Reset Source checking
if (MCUCSR & 1)
   {
   // Power-on Reset
   MCUCSR=0;
   // Place your code here

   }
else if (MCUCSR & 2)
   {
   // External Reset
   MCUCSR=0;
   // Place your code here

   }
else if (MCUCSR & 4)
   {
   // Brown-Out Reset
   MCUCSR=0;
   // Place your code here

   }
else
   {
   // Watchdog Reset
   MCUCSR=0;
   // Place your code here
  
   };

// Input/Output Ports initialization
// Port B initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In Func7=In 
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T State7=T 
PORTB=0x00;
DDRB=0x00;    
PORTB.0 = 1;           // Pull-up an PORTB PIN 0 aktivieren
PORTB.1 = 1;           // Pull-up an PORTB PIN 1 aktivieren
PORTB.2 = 1;           // Pull-up an PORTB PIN 2 aktivieren

// Port C initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In 
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T 
PORTC=0x00;
DDRC=0x00; 


// Port D initialization
// Func0=In Func1=In Func2=In Func3=In Func4=In Func5=In Func6=In Func7=In 
// State0=T State1=T State2=T State3=T State4=T State5=T State6=T State7=T 
PORTD=0x00;
DDRD=0x00;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
TCCR0=0x00;
TCNT0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: 62,500 kHz
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
TCCR1A=0x00;
TCCR1B=0x04;
TCNT1H=0x9E;
TCNT1L=0x57;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
MCUCR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;

// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x67;

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
// Analog Comparator Output: Off
ACSR=0x80;
SFIOR=0x00;

// ADC initialization
// ADC Clock frequency: 125,000 kHz
// ADC Voltage Reference: AVCC pin
// ADC High Speed Mode: Off
// ADC Auto Trigger Source: None
ADMUX=ADC_VREF_TYPE;
ADCSRA=0x87;
SFIOR&=0xEF;


// I2C Bus initialization
i2c_init(); 
i2c_stop(); 
//Takt inizalisieren
//TWSR = 0xf8;
//TWBR = 0x48;  


//--------------------------------------------------------------------------------------------------------------------------------------Programm 
// Watchdog Timer initialization
// Watchdog Timer Prescaler: OSC/512k
//WDTCR=0x1D;
//WDTCR=0x0D;
	
// Global enable interrupts
#asm("sei")

  

while (1)
      {
      
      u = read_adc(0x40);   
    
      if( u >= 897)
      	{            
      	  
      		TIMSK = 0x04;
        
      	} 
      else
      	{
      	  
      		TIMSK = 0x00;
      		PORTD.7 = 0;
      		
      		
      	}  

     
     if (rx_counter != 0)
        {
         instruction = getchar();            // holt sich ein Byte aus den Puffer 
                               
         if (instruction == 'a')
                { 
                
                 do
                   { 
                    ausgabe_zaehler++;
                    if ( regadd_r_1_z <= 16)
                        {       
                         if(regadd_r_0 != 252)
                        {
                        ausgabe_z_0 = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0);               
                        ausgabe_z_1 = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0+1);                             
                        ausgabe_k = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0+2);       
                        regadd_r_0+=3;
                        //printf("Zeit: %c Kontakt_1: %c Kontakt_2 %c Kontakt_3 %c \r\n", (256 * ausgabe_z_0 + ausgabe_z_1)*400, 
                        //      ((ausgabe_k & 0x01) ? 1 : 0),((ausgabe_k & 0x02) ? 1 : 0),((ausgabe_k & 0x04) ? 1 : 0));
                        }
                     else
                        {   
                        regadd_r_0 = 0x00;
                        regadd_r_1++;  
                        regadd_r_1_z++; 
                                if ( regadd_r_1_z <= 16)
                                        {
                                         ausgabe_z_0 = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0);               
                                         ausgabe_z_1 = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0+1);                             
                                         ausgabe_k = i2c_receive(EEPROMADD_write, regadd_r_1, regadd_r_0+2);        
                                         //printf("Zeit: %c Kontakt_1: %c Kontakt_2 %c Kontakt_3 %c \r\n", (256 * ausgabe_z_0 + ausgabe_z_1)*400, 
                                         //((ausgabe_k & 0x01) ? 1 : 0),((ausgabe_k & 0x02) ? 1 : 0),((ausgabe_k & 0x04) ? 1 : 0));
                                        }
                           }
                         }
                   }while((ausgabe_z_0 != 0xff && ausgabe_z_1 != 0xff && ausgabe_k != 0xff) || ausgabe_zaehler != 65536 );
                 printf("Auslesen beendet");
                } 
         
          if (instruction == 'l')
               {                 
                 while ( loechen_0_z != 4096)  // 256 * 16
                        {       
                         if(loechen_0 != 255)
                                {
                                 i2c_transmit(EEPROMADD_write, loechen_1, loechen_0, 0x00);  //zeit geschrieben die ersten (höchsten) 8 Bit schreiben                  Register anorden!!!!!!!
                                 loechen_0++; 
                                 loechen_0_z++;             
                                }
                         else
                                {
                                 loechen_0 = 0x00;
                                 loechen_1++;  
                                 loechen_1_z++; 
                                }
           
                        }
                
  	         
                }printf("Loeschen abgeschlossen Zähler1: %i Zähler0 %i",loechen_1_z,loechen_0_z);
                  
          
          if (instruction != 'l' && instruction != 'a' )
                {
                 printf ("löschen = l ausgabe = a");
                }
         
       
  }    
 }  
}
