I'm running several Low Frequency Oscillators for a synthesizer using a Due. I'd like to add more instances of these LFOs but the code is starting to run too slowly to give smooth waveforms. Can anyone help me make this code run faster please? I'm driving four MPC4921 DACs and would addd more if able to get the performance up.
Excerpt posted:
//
Set_DAC_4921_4(round(D));
subroutine to set DAC No 4 on MCP4921
void Set_DAC_4921_4(int DC_Value) {
lower_byte = DC_Value & 0xff;
upper_byte = (DC_Value >> 8) & 0x0f;
bitSet(upper_byte, 4);
bitSet(upper_byte, 5);// bitSet(upper_byte, 7); set bit 7 as 1 for DAC_B in twin DAC chip MCP4922; 0 for DAC_A
digitalWrite(DAC4_CS, LOW);
tfr_byte(upper_byte);
tfr_byte(lower_byte);
digitalWrite(DAC_SDI, LOW);
digitalWrite(DAC4_CS, HIGH);
digitalWrite(DAC_LDAC, LOW);
digitalWrite(DAC_LDAC, HIGH);
}
// transfers a byte, a bit at a time, LSB first to the DAC
void tfr_byte(byte data)
{
for (int i = 0; i < 8; i++, data <<= 1) {
digitalWrite(DAC_SDI, data & 0x80);
pulseHigh(DAC_SCK); //after each bit sent, CLK is pulsed high
}
}
stevehunt100:
Of course it doesn't compile - I said it was an excerpt. How can I post complete code when it exceeds the character limit that this site allows?
By using SPI, you mean using a different DAC chip that supports that protocol?
How I have posted code that exceeds the character limit, I use several postings.
If the DUE is being bogged down it may be time to use an ESP32.
Hi,
Maybe pre-define those bit patterns, or most of the bits at least. Put the patterns in an array and select them as needed.
I have built automated machines where entire often-used functions had their data values in arrays and at run time there were mostly just some move instructions.
stevehunt100:
Of course it doesn't compile - I said it was an excerpt. How can I post complete code when it exceeds the character limit that this site allows?
You can attach the full code or (even better) post a small MCVE.
Thanks all. OK next time I'll cut my sketch up into chunks or create an MCVE. I leaned something!
I'll have a look at a faster processor and thanks for the pointer with the ESP32, but I think it's the I/O that's slowing me down. A faster processor would step through the various output pulses faster so that should help but AWOL's SPI hint might also be a useful path to explore.
Pre-defining the bit patterns should help a bit too. Cheers.
Try PIO_SODR / PIO_CODR instead of a slow digitalWrite(). If you want to drive a DAC thru the SPI peripheral, search DUE DAC SPI, you will find a .pdf tutorial from chianorobotics. For an even faster SPI, have a look atTurboSpi library for Sam3x to leverage the SPI DMA feature.