MATLAB Answers

Write on DAC with desired Frequency of a Sine Wave

13 views (last 30 days)
pallab choudhury
pallab choudhury on 12 Jun 2018
Commented: Walter Roberson on 16 Jun 2018
I am trying to write a sine wave for a DAC by using the MATLAB support package of Arduino. The code that I used is as below:
clear all
a = arduino('COM3', 'Uno');
dev = spidev(a,'D10','Mode',2,'BitOrder','msbfirst','Bitrate',1000000);
fs = 1024; % Sampling frequency
dt = 1/fs; % seconds per sample
StopTime = 1; % Total time
F1 = 100; % Sine wave frequency (hertz)
for t=0:dt:StopTime-dt
data1 = 32767+24576*sin(2*pi*F1*t); % 32767 and 24576 are the bias and amplitude setting of Sine wave for 16 bit DAC
writeRead(dev,[24,flip(typecast(uint16(data1),'uint8'))],'uint8'); % Command/Address bits and 16 bit Data
The DAC output shows a sine wave with frequency reduced to 10 Hz instead of 100 Hz....I checked with other sample rate and different frequency setting but the output frequency is always lower than the desired frequency. Could you please suggest how to avoid such delay or match the output frequency with the desired one. Thanks.

Answers (1)

Walter Roberson
Walter Roberson on 12 Jun 2018
You need a sampling frequency that is at least twice the frequency of the sine wave you want to create.
By the way, for efficiency you should probably create the entire output matrix first.
data1 = swapbytes(uint16(32767+24576*sin(2*pi*F1*t)));
for K = 1 : length(data1)
writeRead(dev, [uint8(24), typecast(data1(K),'uint8')], 'uint8');
Walter Roberson
Walter Roberson on 16 Jun 2018
The part of the Arduino code where you output 1024 samples to each of four channels has no built-in delays: it will output as quickly as the hardware permits the cycles to be run.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!