Skip to content

Instantly share code, notes, and snippets.

@ugeugeHigh
Created August 10, 2021 10:17
Show Gist options
  • Save ugeugeHigh/3de58082232bb034c8897aa49fb718ad to your computer and use it in GitHub Desktop.
Save ugeugeHigh/3de58082232bb034c8897aa49fb718ad to your computer and use it in GitHub Desktop.
#include <SPI.h>
const int SINE = 0x2000;
const int SQUARE = 0x2028;
const int TRAIANGLE = 0x2002;
const float refFreq = 25000000.0;
const int FSYNC = 10;
const int SWpin = 4;
int waveType = TRAIANGLE;
unsigned long freq = 1000000;
int SW = 0;
int freqPin = A3;
int val = 0;
float val2 = 0;
float tmp = 0;
void setup() {
Serial.begin(9600);
Serial.println("AD9833 Test");
pinMode(SWpin, INPUT);
SPI.begin();
delay(50);
AD9833reset();
delay(50);
AD9833setFrequency(freq, SINE);
}
void loop() {
val = digitalRead(SWpin);
val2 = analogRead(freqPin);
//Serial.println(val);
Serial.println(int(val2/10)*10);
tmp = 100*float(int(val2/10)*10);
Serial.println(tmp);
if ((val != SW)|(freq != tmp)){
SW = val;
freq = tmp;
if(SW == 0){
AD9833reset();
delay(50);
AD9833setFrequency(freq, TRAIANGLE);
Serial.println("TRAIANGLE");
} else {
AD9833reset();
delay(50);
AD9833setFrequency(freq, SINE);
Serial.println("SINE");
}
}
delay(100);
}
void AD9833reset() {
WriteRegister(0x100);
delay(10);
}
void AD9833setFrequency(long frequency, int Waveform) {
long FreqWord = (frequency * pow(2, 28)) / refFreq;
int MSB = (int)((FreqWord & 0xFFFC000) >> 14);
int LSB = (int)(FreqWord & 0x3FFF);
LSB |= 0x4000;
MSB |= 0x4000;
WriteRegister(0x2100);
WriteRegister(LSB);
WriteRegister(MSB);
WriteRegister(0xC000);
WriteRegister(Waveform);
}
void WriteRegister(int dat) {
SPI.setDataMode(SPI_MODE2);
digitalWrite(FSYNC, LOW);
delayMicroseconds(10);
SPI.transfer(highByte(dat));
SPI.transfer(lowByte(dat));
digitalWrite(FSYNC, HIGH);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment