Josh Jennings / Mbed 2 deprecated Instrumentation

Dependencies:   mbed

main.cpp

Committer:
joshthepirate
Date:
2020-01-31
Revision:
0:bb9aeaaccee4
Child:
1:a22687a74345

File content as of revision 0:bb9aeaaccee4:

#include "mbed.h"

#define SPI_MOSI PB_15
#define SPI_MISO PB_14
#define SPI_SCK PB_13

#define FSYNC PB_12

const int SINE = 0x2000;    // AD9833 Waveform register values
const int SQUARE = 0x2028;
const int TRIANGLE = 0x2002;

const float refFreq = 25000000.0;           // On-board crystal reference frequency

SPI spi(SPI_MOSI, SPI_MISO, SPI_SCK);
Serial pc(USBTX, USBRX);
DigitalOut fsyncpin(FSYNC);

unsigned long freq = 1000; // initial freqency

void setup() {
    spi.format(16, 2); // set to 16 bit data and mode 2
    spi.frequency(freq); // set initial fequency
}

void WriteRegister(short dat) {
    fsyncpin = 0;                   // Set FSYNC low before writing to AD9833 registers
    
    wait_us(10);                    // Give AD9833 time to get ready to receive data.
                                    
    spi.write(dat >> 8);         // Each AD9833 register is 32 bits wide and each 16
    spi.write(dat & 0xFF);      // bits has to be transferred as 2 x 8-bit bytes.
    fsyncpin = 1;                   // Write done. Set FSYNC high
}

void AD9833setFrequency(long frequency, int Waveform) {

  long FreqWord = (frequency * pow(2, 28.0)) / refFreq;
  
  int MSB = (int)((FreqWord & 0xFFFC000) >> 14);    //Only lower 14 bits are used for data
  int LSB = (int)(FreqWord & 0x3FFF);

  //Set control bits 15 ande 14 to 0 and 1, respectively, for frequency register 0
  LSB |= 0x4000;
  MSB |= 0x4000;
  
  WriteRegister(0x2100);  
  WriteRegister(LSB);                  // Write lower 16 bits to AD9833 registers
  WriteRegister(MSB);                  // Write upper 16 bits to AD9833 registers.
  WriteRegister(0xC000);               // Phase register
  WriteRegister(Waveform);             // Exit & Reset to SINE, SQUARE or TRIANGLE
}

int main() {
    
    setup();
    
    while(1) {
        // put your main code here, to run repeatedly:
        
        if(pc.readable() > 0){
        
            char incomingData[20];
            pc.scanf("%s", incomingData);
            pc.printf("Setting Frequency to : %s\n", incomingData);
            
            freq = (long)atoi(incomingData);
            
            AD9833setFrequency(freq, SINE);
        }
    }
}