Function generator code modified to work on the Freescale KL25Z
Fork of AD9850 function generator SPI driver by
This is an update to the original AD9850 SPI driver produced by Liam Goudge.
The main changes are to assign the appropriate pins and to send the 40-bit AD9850 programming word as five 8-bit packets. This is necessary because the KL25Z only supports 8-bit SPI transfers.
main.cpp
- Committer:
- ptamike
- Date:
- 2013-10-24
- Revision:
- 3:a643b6a454aa
- Parent:
- 2:e9d2346ea1bb
File content as of revision 3:a643b6a454aa:
// MBED driver for AD9850 digital synthesizer using hacked SPI interface // Original code by Liam Goudge Sept 2013 // Modified for KL25Z by Mike Richards Oct 2013 #include "mbed.h" SPI device (PTD2, PTD3, PTD1); // Set the KL25Z SPI pins DigitalOut CS(PTD0); // Use pin PTD0 as a fake Chip select DigitalOut ADReset(PTA13); // Use Pin PTA13 as the reset line for AD9850 Serial pc(USBTX, USBRX); // tx, rx for debug terminal int reverseBits (int source) { // Unfortunately need to invert bit order of the desired frequency setting since MBED only allows for MSB first from SPI. We need LSB first for AD9850 int mask=0;; int i=0; int target=0; int bitTarget=0x80000000; // Hard-wired for 32-bit inversion for (i=0;i<32;i++) { // ditto mask=1<<i; bitTarget=1<<(31-i); // ditto if (source & mask) target=target | bitTarget; } return target; } void writeSPI(int frq, int phase) { // Send the 40-bit packet. NB: KL25Z only supports 8-bit SPI so send five 8-bit packets device.format(8,0); // 8-bits per packet, mode 0 (CPOL=0 CPHA=0) device.frequency(1000000); //SPI clock set to 1MHz wait_ms(1); // First do chip select. Need to use a GPIO to fake the chip select since MBED doesn't allow to set positive logic CS signal CS=1; // assert chip select (a.k.a FQ_UD frequency update input to AD9850) wait_ms(1); CS=0; device.write(frq>>24); // Write upper 8-bits device.write(frq>>16); device.write(frq>>8); device.write(frq); // Now the last 8 bits device.write(phase); // This is phase and factory settings byte // Now pulse FQ_UD again to load the word into the DDS CS=0; wait_ms(1); CS=1; wait_ms(1); CS=0; } int main() { // This routine produces a continuous frequency sweep int targetFrq=0x147AE148; // Frequency word = ([Desired freq in MHz] * 34.3597384) int increment=0xD6B; //100Hz step // Reset the AD9850. Active high logic. Minimum reset period 5 clock cycles (5/125MHz) ADReset=0; wait_ms(5); ADReset=1; wait_ms(5); ADReset=0; while(1) { while (targetFrq<0x148bFFFF) // up to 10.001MHz { writeSPI(reverseBits(targetFrq),0); // Don't use phase so set to zero. targetFrq=targetFrq+increment; //wait_ms(200); } while (targetFrq>0x147AE148) // down to 10MHz { writeSPI(reverseBits(targetFrq),0); targetFrq=targetFrq-increment; //wait_ms(200); } } }