//FSK_DDS v1.3 2016.02.23
//ARDUINO UNO + AD9850
 
#define  CLK   8  //UNO:PORT_B0
#define  FQ    9  //UNO:PORT_B1
#define  DATA  10 //UNO:PORT_B2
#define  RST   11 //UNO:PORT_B3

long  mark  = 7035000;  // ***** Set operating frequency here in Hz. *****

void shortPulse (char PIN)
{
        digitalWrite(PIN, 1);
        digitalWrite(PIN, 0);
}

void setFreq(double freq)
{
        //--calculate
        int32_t d_Phase = freq * pow(2, 32) / 125000000;
        //--send first 32bit
        for (int i=0; i<32; i++, d_Phase>>=1)
        {
                if(d_Phase & 1 == 1)
                {
                        PORTB |=  _BV(2); //--data
                }
                else
                {
                        PORTB &= ~_BV(2); //--data
                }
                //--short pulse clk
                PORTB |=  _BV(0);
                PORTB &= ~_BV(0);
        }
        //--send rest 8bit
        PORTB &= ~_BV(2); //--data
        for (int i=0; i<8; i++)
        {
                //--short pulse clk
                PORTB |=  _BV(0);
                PORTB &= ~_BV(0);
        }
        //--finish, short pulse fq
        PORTB |=  _BV(1);
        delayMicroseconds(30);
        PORTB &= ~_BV(1);
}

void setup()
{
        pinMode(CLK, OUTPUT);
        pinMode(FQ, OUTPUT);
        pinMode(DATA, OUTPUT);
        pinMode(RST, OUTPUT);
        //--reset
        shortPulse(RST);
        shortPulse(CLK);
        //--change mode
        shortPulse(FQ);
        //--start,mark=idle
        delay(100);
        setFreq(mark);
        delay(500);
}

void loop()
{
        static boolean state1 = 1;
        static boolean state2 = 0;
        static long    space  = mark - 170;
        
        if(digitalRead(6) == 0) //--trx control
        {
                setFreq(2);
                state1 = 0;
                delay(44);
        }
        else
        {
                state2 = digitalRead(7); //--fsk keying input
                if(state2 != state1)
                {
                        if(state2 == 1)
                        {
                                setFreq(mark);
                        }
                        else
                        {
                                setFreq(space);
                        }
                        state1 = state2;
                }
        }
}