#include "stm32f4_discovery.h"
#include "stm32f4xx_conf.h" // again, added because ST didn't put it here ?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "delay.h"
#include "usart.h"


#define CLOCK_IN 100000000ULL
//P125 = PB6=i2c1-scl
//P127 = PB7=i2c1-sda

//combine with ddsprog.v


int main(void)
{
usart2_init(115200);

//hardware init
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_7|GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);


print(USART2, "ddstest\n"); 

while(1)
        {
        //read frequency in khz
	printf("Enter freq. in khz: "); fflush(stdout);
        unsigned int khz;
	scanf("%d",&khz);
	if(khz > CLOCK_IN/4000) {printf("frequency overflow\n"); continue;}
	uint64_t inc = khz;
        inc *= 1000;
        inc <<= 16+1;
        inc /= CLOCK_IN;
        if(inc > 65535) {printf("increment overflow\n"); continue;}
        uint16_t inc2 = inc;
	printf("Increment = %d\n",(int)inc2);
	
	//shift it to fpga
        uint8_t i;
        for(i=0; i<16; ++i)
                {
                if(inc2 & 1) GPIO_SetBits(GPIOB, GPIO_Pin_7); else GPIO_ResetBits(GPIOB, GPIO_Pin_7);
                delay_ms(1);
		GPIO_SetBits(GPIOB, GPIO_Pin_6);
                delay_ms(1);
		GPIO_ResetBits(GPIOB, GPIO_Pin_6);
                delay_ms(1);
                inc2 >>= 1;
                }
        }



}


