/*
 * "Hello World" example.
 *
 * This example prints 'Hello from Nios II' to the STDOUT stream. It runs on
 * the Nios II 'standard', 'full_featured', 'fast', and 'low_cost' example
 * designs. It runs with or without the MicroC/OS-II RTOS and requires a STDOUT
 * device in your system's hardware.
 * The memory footprint of this hosted application is ~69 kbytes by default
 * using the standard reference design.
 *
 * For a reduced footprint version of this template, and an explanation of how
 * to reduce the memory footprint for a given application, see the
 * "small_hello_world" template.
 *
 */

#ifndef  DDS_H
#define  DDS_H

#include <stdio.h>
#include "system.h"
#include "altera_avalon_pio_regs.h"
#include "io.h"
#include "SinWavePoint.h"

#include "my_common.h"
#include "sys/alt_alarm.h"

#define CHA_FREQ			Out1_Freq
#define CHB_FREQ			Out2_Freq
#define CHAB_PHASE			(Calculate_Pword(Out2_Phas) << 16) | (Calculate_Pword(Out1_Phas))
#define CHAB_PLUSE_WIDTH	((Out2_Width * 16384 / 100) << 16) | (Out1_Width * 16384 / 100)


extern u32 Out1_Freq;
extern u32 Out2_Freq;
extern u16 Out1_Phas;
extern u16 Out2_Phas;
extern u8 Out1_Width;
extern u8 Out2_Width;
extern enum OUT_ChANNEL Out_Channel;

void Init_DDS_ROM_tra(int base)
{
	int i;
	for(i=0;i<4096;i++)
	{
		IOWR_16DIRECT(base, i*2, i*4);
	}
}

void Init_DDS_ROM_sine(int base)
{
	int i;
	for(i=0;i<4096;i++)
	{
		IOWR_16DIRECT(base, i*2, SinWavePoint[i]);
	}
}

void Init_DDS_ROM_squr(int base)
{
	int i;
	for(i=0;i<2047;i++)
	{
		IOWR_16DIRECT(base, i*2, 0);
	}
	for(i=2047;i<4096;i++)
	{
		IOWR_16DIRECT(base, i*2, 16383);
	}
}


uint_fast64_t Calculate_Fword(uint_fast64_t Fout)
{
	uint_fast64_t fword;

	fword = Fout * 65536*65536;
	fword = fword/125000000;
	return fword;
}

uint_fast64_t Calculate_Pword(uint_fast64_t Phase)
{
	uint_fast64_t pword;
	pword = Phase * 4096;
	pword = pword / 360;
	pword = pword & 0x0000ffff;

	return pword;
}



int dds_init()
{
  Init_DDS_ROM_sine(RAM_A_BASE);
  Init_DDS_ROM_sine(RAM_B_BASE);

  IOWR_ALTERA_AVALON_PIO_DATA(CHA_FWORD_BASE,Calculate_Fword(CHA_FREQ));
  IOWR_ALTERA_AVALON_PIO_DATA(CHB_FWORD_BASE,Calculate_Fword(CHB_FREQ));
  IOWR_ALTERA_AVALON_PIO_DATA(CHAB_PWORD_BASE,CHAB_PHASE);
  IOWR_ALTERA_AVALON_PIO_DATA(CHAB_PLUSE_WIDTH_BASE, CHAB_PLUSE_WIDTH);
  IOWR_ALTERA_AVALON_PIO_DATA(CHAB_EN_BASE, 0);
  IOWR_ALTERA_AVALON_PIO_DATA(CHAB_EN_BASE, (u8)Out_Channel);

  return 0;
}


#endif   /* ifdef DDS_H */

