Created
August 4, 2017 18:42
-
-
Save FrankBuss/6ce2ad168057ea669b3e237bf6a4528d to your computer and use it in GitHub Desktop.
3 Hz sawtooth example with a DAC8718
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 3 Hz sawtooth example with a DAC8718 | |
* Arduino Nano pins: | |
* CS: 10 | |
* MOSI: 11 | |
* MISO: 12 | |
* SCK: 13 | |
*/ | |
#include "SPI.h" | |
// pin numbers | |
const int csPin = 10; | |
const int ldacPin = 9; | |
const int rstPin = 8; | |
// signal generator | |
const float samplerate = 20000.0f; | |
const float frequency = 3.0f; | |
uint32_t increment = 1.0f / samplerate * frequency * 4294967296.0f; // 2^32 = multiplicator for 32 bit full scale | |
uint32_t accu = 0; | |
uint16_t nextValue = 0; | |
// send a word to the DAC | |
void sendDacWord(uint8_t reg, uint16_t word) | |
{ | |
digitalWrite(csPin, LOW); | |
SPI.transfer(reg); | |
SPI.transfer(word >> 8); | |
SPI.transfer(word & 0xff); | |
digitalWrite(csPin, HIGH); | |
} | |
void setup() | |
{ | |
// init pins | |
pinMode(csPin, OUTPUT); | |
pinMode(ldacPin, OUTPUT); | |
pinMode(rstPin, OUTPUT); | |
digitalWrite(csPin, HIGH); | |
digitalWrite(ldacPin, HIGH); | |
digitalWrite(rstPin, HIGH); | |
// reset DAC | |
delay(1); | |
digitalWrite(rstPin, LOW); | |
delay(1); | |
digitalWrite(rstPin, HIGH); | |
delay(1); | |
// init SPI | |
SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE1)); | |
SPI.begin(); // additional begin is required, otherwise the second call to SPI.transfer hangs | |
// configuration register: gain 4 | |
sendDacWord(0, 0x180); | |
// offset DAC A | |
sendDacWord(3, 0x2400); | |
// offset DAC B | |
sendDacWord(4, 0x2400); | |
// initialize timer1 | |
noInterrupts(); // disable all interrupts | |
TCCR1A = 0; | |
TCCR1B = 0; | |
TCNT1 = 0; | |
OCR1A = 16000000.0f / samplerate; // compare match register for IRQ with selected samplerate | |
TCCR1B |= (1 << WGM12); // CTC mode | |
TCCR1B |= (1 << CS10); // no prescaler | |
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt | |
interrupts(); // enable all interrupts | |
} | |
// timer 1 interrupt | |
ISR(TIMER1_COMPA_vect) | |
{ | |
digitalWrite(ldacPin, LOW); | |
digitalWrite(ldacPin, HIGH); | |
sendDacWord(7, nextValue); | |
nextValue = accu >> 16; | |
accu += increment; | |
} | |
void loop() | |
{ | |
// everything is in the interrupt, nothing to do here | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment