// ATmega8: Szukseges labak: VCC=5V,GND=GND,TX=MIDI-In, PC4=Reset (midi mellett) 
#define F_CPU 16000000UL		 //kulso!!
#define USART_BAUDRATE 31250  
#define UBRR_ERTEK ((F_CPU / (USART_BAUDRATE * 16UL)) - 1)
#include <avr/io.h>  
#include <util/delay.h>

char note = 0;			//MIDI hang amit el fog jatszani
char instrument = 0;

void KonfigUART()
{
    UBRRL = UBRR_ERTEK;   
    UBRRH = (UBRR_ERTEK>>8);  
    UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); 
    UCSRB |= (1 << RXEN) | (1 << TXEN);	
}

void UARTAdatKuld(char data)
{
    while(!(UCSRA & (1<<UDRE))){}
    UDR=data;
}

void reset() 
{
  DDRC = (1<<PC4);	  //midi Resethez
  PORTC &= ~(1<<PC4);
  _delay_ms(100);
  PORTC |=  (1<<PC4);
  _delay_ms(100);
}

void talkMIDI(char cmd, char data1, char data2) 
{
  UARTAdatKuld(cmd);
  UARTAdatKuld(data1);
  if( (cmd & 0xF0) <= 0xB0) UARTAdatKuld(data2);
}

void noteOn(char channel, char note, char attack_velocity) 
{
  talkMIDI( (0x90 | channel), note, attack_velocity); //0x90=note on
}

void noteOff(char channel, char note, char release_velocity) 
{
  talkMIDI( (0x80 | channel), note, release_velocity); //0x80=note off
}

int main() 
{
  KonfigUART();
  while(1)
  {
	reset();
	talkMIDI(0xB0, 0x07, 120); //0xB0 parametert allitom, a hangerot, 120-ra (127-max)
	talkMIDI(0xB0, 0, 0x79);   //0xB0 parametert allitom, a bankot, melodiara (0x78-dob)
	for(instrument = 0 ; instrument < 127 ; instrument++) //vegigmegyek az osszes hangszeren
	{
		talkMIDI(0xC0, instrument, 0); //hangzas
	    for (note = 27 ; note < 87 ; note++) //skala
		{
			noteOn(0, note, 60); //hang
			_delay_ms(50);
			noteOff(0, note, 60); //csend
			_delay_ms(50);
		}
		_delay_ms(100); //hangszervaltas kozti szunet
	}
  }
}