Rolando Pelayo / Mbed 2 deprecated sine_wave_generator

Dependencies:   mbed

AD9850.cpp

Committer:
roland_tmm
Date:
2017-11-21
Revision:
0:6069c0f2a245
Child:
1:9dcccb399f0b

File content as of revision 0:6069c0f2a245:

/******************************************************************************************************************
 * STM32F103 library for AD9850
 * Created 11/21/2017
 * Roland Pelayo 
 *
 * Use this library freely
 *
 * Hardware connections : 
 * W_CLK   -> any pin
 * FQ_UD   -> any pin
 * DATA/D7 -> any pin
 * RESET   -> any pin
 *
 * Functions :
 * dds.begin(W_CLK pin, FQ_UD pin, DATA pin, RESET pin); Initialize the output pins and master reset the AD9850 
 * dds.calibrate(frequency); Compensation of crystal oscillator frequency
 * dds.setfreq(frequency,phase); frequency in Hz, phase coded on 5 bits
 * dds.down(); power down mode reducing the dissipated power from 380mW to 30mW @5V
 * dds.up(); wake-up the AD9850
 *
 * AD9850 datasheet at http://www.analog.com/static/imported-files/data_sheets/AD9850.pdf
 *
 *****************************************************************************************************************/

#include "AD9850.h"
#include "mbed.h"

#define W_CLK PB_10
#define FQ_UD PB_11
#define DATA PB_1
#define RESET PB_0

#define REVERSE_BITS(byte) (((reverse_lookup[(byte & 0x0F)]) << 4) + reverse_lookup[((byte & 0xF0) >> 4)])
    
static const uint8_t reverse_lookup[] = { 0, 8,  4, 12, 2, 10, 6, 14,1, 9, 5, 13,3, 11, 7, 15 };

SPI SPI_dev2(DATA, PB_8, W_CLK);

DigitalOut wclk(W_CLK);
DigitalOut fq_ud(FQ_UD);
DigitalOut dat(DATA);
DigitalOut res(RESET);

AD9850::AD9850() {

}

void AD9850::Begin() {
    SPI_dev2.format(8,0); 
    deltaphase = 0;
    phase = 0;
    calibFreq = 125000000;
    begin_priv();
}

void AD9850::begin_priv() {
   
    res = 1;
    wait(0.001);
    res = 0;
    
    wclk = 1;
    wait(0.001);
    wclk = 0;   
   
    fq_ud = 1;
    wait(0.001);
    fq_ud = 0;
    
}

void AD9850::update() {
    uint32_t d,p;
    for (int i=0; i<4; i++, deltaphase>>=8) {
     d = REVERSE_BITS(deltaphase);
     SPI_dev2.write(d & 0xFF);
    // shiftOut(DATA, W_CLK, LSBFIRST, deltaphase & 0xFF);
    }
    p = REVERSE_BITS(phase);
    SPI_dev2.write(p & 0xFF);
    //shiftOut(DATA, W_CLK, LSBFIRST, phase & 0xFF);
    fq_ud = 1;
    wait(0.001);
    fq_ud = 0;
}


void AD9850::SetDDSFrequency(double f, uint8_t p) {
    deltaphase = f * 4294967296.0 / calibFreq;
    phase = p << 3;
    update();
}


void AD9850::down() {
    fq_ud = 1;
    wait(0.001);
    fq_ud = 0;
    SPI_dev2.write(REVERSE_BITS(0x04));
    //shiftOut(DATA, W_CLK, LSBFIRST, 0x04);
    fq_ud = 1;
    wait(0.001);
    fq_ud = 0;
}
    

void AD9850::up() {
    update();
}


void AD9850::CalibrateDDS(double TrimFreq)
{
    calibFreq = TrimFreq;
}

/*
void AD9850::pulse(int pin) {
    digitalWrite(pin, HIGH);
    digitalWrite(pin, LOW);
}*/