/*
 *Do what ever you want with this code...
 */
#include <avr/io.h>
#include <avr/iom32.h>
#include <util/delay.h>
#include "wtv020.h"


/*
 * Initialize the pins
 */
void wtv020_init(void){
	WTV_DDR |= (1 << WTV_RES) | (1 << WTV_CL) | (1 << WTV_DO);	//RES, CL, DO output
	WTV_DDR &= ~(1 << WTV_BUSY);		//BUSY input
	WTV_PORT &= ~(1 << WTV_BUSY);		//Pull-Up off
	wtv020_reset();						//Initial Reset
}


/*
 * Reset the chip
 */
void wtv020_reset(){
	WTV_PORT |= (1 << WTV_CL);		//CL high, DO low
	WTV_PORT &= ~(1 << WTV_DO);
	_delay_ms(5);

	WTV_PORT |= (1 << WTV_RES);		//RES pulse
	_delay_ms(100);
	WTV_PORT &= ~(1 << WTV_RES);
	_delay_ms(10);
	WTV_PORT |= (1 << WTV_RES);

	_delay_ms(500);					//wait until module is ready
}


/*
 * Play file until its end.
 * BLOCKING FUNCTION!
 * waits for BUSY-FLAG
 */
void wtv020_playVoice(uint16_t voiceNumber){
	wtv020_sendCommand(voiceNumber);	//Send song number
	while(WTV_PIN & (1 << WTV_BUSY));	//Wait while busy (playing)
}


/*
 * Send command to WTV020
 * 0x0000 to 0x01FF (0 to 511 decimal) will play the files 0000.ad4 to 0511.ad4
 * All other commands are defined in wtv020.h
 */
void wtv020_sendCommand(uint16_t command) {

	WTV_PORT &= ~(1 << WTV_CL);				//Pull CL low for 2ms for start
	_delay_ms(2);

	for (int i=15; i>=0; i--){ 				//for each bit of 16bit data
		_delay_us(CLK/4);

		if(((command>>i)&0x0001 )>0)		//when bit=1 DO high else low
			WTV_PORT |= (1 << WTV_DO);
		else
			WTV_PORT &= ~(1 << WTV_DO);

		_delay_us(CLK/4);						//CL high pulse
		WTV_PORT |= (1 << WTV_CL);
		_delay_us(CLK/2);

		if(i==0){							//if last bit, stop transmission
			WTV_PORT |= (1 << WTV_CL);
			WTV_PORT &= ~(1 << WTV_DO);
		}
		else								//else begin new clock cycle
		WTV_PORT &= ~(1 << WTV_CL);

	}

	_delay_ms(70);							//wait for BUSY-Flag available
}
