I'm developping a bytebeat module with ArduinoUno and MCP4821 DAC.
User writes a formula, the formula is evaluated by the TinyExpr library and the result is sent through pwm to the DAC in order to have analogue values.
The reference formula in bytebeat is simply "t" which result to a sawtooth wave at 8kHz frequency.
T is a variable that never stop to increment between 0 and 255.
But now I'm a little confused, because when I send
for (int i = 0; i < 255; i++)
{
MCP.fastWriteA(i);
}
To the DAC in the loop, the result frequency is ~260Hz and that's not enough to be eared.
I don't know where I have to search now in order to output the desired frequency.
The DAC expects a number as input, if I'm correct. Is the above code doing just this? Or is it a PWM value?
If PWM is what you're using on an analog pin, a PWM output of 255 means 5V almost constant (or 99% duty cycle), 128 means 50% duty cycle and so on. Arduino Uno has a PWM freq of about 590 Hz...
Nope. MCP4821 is 12 bits DAC and its needed 16 bits data for work - read the datasheet.
Probably setting the DAC value is slow. To be sure, change the cycle by giving a larger increment.
Instead for (int i = 0; i <255; i ++)
try it for (int i = 0; i <255; i += 5)
and if the DAC frequency is about 5 times higher then the assumption is correct. If the project allows you, you can increase the step enough to achieve the required frequency. Or you can replace the microcontroller with a faster one as suggested by @SteveMann. The measured time of 16 microseconds corresponds to the result - 256 values each for 16 microseconds gives a frequency of about 244 Hz.
You need to look at the MCP_DAC library to see what sort of data transfer it is doing. On the Uno, it may be using the default SPI connection at 100 kHz clock rate, or bit banged I/O. Those are slow, and very, very slow, respectively.
To send data faster, either modify the library or write your own SPI routines to make use of faster SPI data transfers.
Try 'i + = 486' instead of 512. But it may not help, because the steps are very small - only 8. Try to change the upper value of 4096. 8 steps are only 12.5% resolution and you will hardly be able to adjust the frequency 8 kHz exactly.