I am using an Arduino Due with the SineWaveDue library to generate a sine wave from the DAC0 and DAC1 pins to an amplifier. While doing this I am also using a VL53L0X to obtain distance measurements using this Adafruit library based on their example of multiple sensors.
According to the datasheet, the vl53l0x has a max clock speed of 400kHz. For redundancy because I have a few of them on the same bus, and simply because I just don't need that many samples, I've knocked it down to ~1kHz in the setup. On every loop, the recorded values get written to a csv file on the SD card.
The issue that appears to be occurring is that, whether it be through error accumulation or some unintended delay, the phase of the sine wave seems to switch in an undesirable way. I have two Due's running independently and generating sine waves. Based on parameters I set before runtime, these waves should either be in phase for the duration of the loop, or 180deg out of phase. I do know that these oscillators will never be exactly in or out of phase, but for my purposes they just need to be close.
I've connected these Arduinos to an oscilloscope to at least qualitatively confirm what's going on. It appears that at some point while writing to the SD, there is a sudden drop in the amplitude and the phase then shifts 180deg. This shouldn't happen because the amplitude is constant and never gets updated. I've read a lot of issues about varying latency in SD cards up to ~250ms. To try and counteract this I've been experimenting with the SdFat library as opposed to the included SD library, also trying writing to binary files during the loop and then converting to csv at the end.
// Current version I'm experiencing issues with
void loop() {
while(millis() - startTime < maxTime) {
if(myFile) {
sw.playtone(10); // 10Hz sine wave
S.rangingTest(&sensor, false);
dist = sensor.RangeMilliMeter;
myFile.println(dist, 8); // print data to csv file
}
}
myFile.close();
exit(0);
}
I'm currently pointing the finger at the SD writing being the issue because when I comment that line out, the issue seems to be reduced, as well as the latency issues I've read about the SD cards. I've read the suggestions on this post, but haven't yet had time to implement any of them.
I'm taking roughly a couple thousand samples each time, so I don't want to store the data in an array so I can save the RAM of the Due. I ran the example "LowLatencyLogger" in the SdFat lib to save the data in a bin file but saw little improvement in the number of samples recorded. The SineWaveDue page states a 50us sample time, should I try and match my VL53L0X sampling frequency to this as close as possible for optimal performance? I'm not sure what kind of affect that may have on the phase shifting issue. Any insight is appreciated.