main.c

 

#include <avr/io.h>     
#include <util/delay.h>
#include <stdlib.h>
#include <avr/interrupt.h>

#define USART_BAUDRATE 9600 
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

void setup_analog();				// Function prototype
void transmit();
void readLight();

	unsigned int buttonStatus = 0;
	unsigned int switchStatus = 0;		
	unsigned int level = 1024;
	unsigned int lowLevel = 0;
	unsigned int highLevel = 0;
	unsigned int redLevel = 0;
	unsigned char hits = 0;
	unsigned char* sending;
	unsigned char start;

int main(void){
  	UBRRL = 12;                       	// Set baudrate to 9600.
    UCSRA = _BV(U2X);                   	// Double the USART transmission speed.
    UCSRB = _BV(RXEN)                   	// Reciever enable.
          | _BV(TXEN);                  	// Transmitter enable.
    UCSRC = _BV(URSEL)                  	// Register select.
          | _BV(UCSZ0) 		          	// 8-bit character size.
		  | _BV(UCSZ1);

											
	DDRD = 0b111111111;
   	ADMUX |= (1 << REFS0); 			// Set ADC reference to AVCC. 
	
	GICR = 0b11000000 |(1 << ADC);
	MCUCR = 0b00000111;

	ADCSRA |= (1<<ADIE); 			// Enable ADC conversion complete interrupt.
	ADCSRA |= (1<<ADEN); 			// Enable the ADC.

	sei();
	setup_analog();
	for(;1==1;){
		
	}
	return 1;
}
ISR(SIG_INTERRUPT0) { 				// The interrupts on the switch.
	if ((PIND & 0b00000100) != 0){		// Check switch status.
	transmit();
	}
}
ISR(SIG_INTERRUPT1) {				// The interrupts on the button
	if((PIND & 0b00001000) != 0){
		PORTD  = 0b01000000;
		level = redLevel+200;
	}
		while((PIND & 0b00001000) != 0){}
		PORTD  = 0b00000000;
		_delay_ms(10);
}
ISR(SIG_ADC){					// The interrupt on the A/D converter.
	readLight();
	setup_analog();
}

void transmit (){				// Function which operates the transferance 
						//of data, computer-AVR Mega16.
	SREG = 0b00000000;
	PORTD &= ~(1<< 3);
	PORTD &= ~(1<< 4);
	while( !(UCSRA & ( 1<<RXC)) );
	start = UDR;
 	while (! (UCSRA & (1<<UDRE))){}
	UDR = hits;
	while (switchStatus != 0){
		switchStatus = (PIND & 0b00000100);
	}
	sei();
}

void readLight(){				// Function which reads the phototransistor.
	lowLevel = ADCL;						
	highLevel = ADCH;
	highLevel <<=8;
	redLevel = lowLevel | highLevel;
	if(redLevel > level){
			hits ++; 
			PORTD = 0b10000000;
			_delay_ms(500);
			PORTD = 0b00000000;
		} else {
			PORTD = 0b00000000;
			_delay_ms(10);
		}

}
void setup_analog(){
	ADCSRA |= (1 << ADEN) | (1 << ADSC);    // Set upp the analog converter and makes it 
						//ready to start convert.
	
}