MATLAB Error code when try to acquire data from NI cDAQ9184 - matlab

I would like to have some help on this error.
I using MATLAB with NI cDAQ9184.
Error code:
NI Error -201087:
Task contains physical channels on one or more devices that require you to specify the Sample Clock rate. Use the Sample Clock
Timing function/VI to specify a Sample Clock rate.
You cannot specify a Sample Clock rate if Mode is set to On Demand.
Device: cDAQ9184-182032A
Task Name: _unnamedTask
Status Code: -201087
Here is the code I use.
I use this code on the old computer before and it is run fine.
However, I have to change computer recently due to the computing power issue and the error appear.
% Set up the NI DAQ device
dq = daq("ni"); % Find avaliable NI Device
dq.Rate = 7142.8571; % Set Fequency of NI Devices
% Add an input channel for the analog input signal
ch1 = addinput(dq, "cDAQ9184-182032AMod2", "ai1", "Bridge"); % Add ai 0 input as Bridge modes
ch1.BridgeMode = "Full"; % Full mode
ch1.NominalBridgeResistance = 350; % Resisitance of the strain gauge
ch2 = addinput(dq, "cDAQ9184-182032AMod2", "ai2", "Bridge"); % Add ai 0 input as Bridge modes
ch2.BridgeMode = "Full"; % Full mode
ch2.NominalBridgeResistance = 350; % Resisitance of the strain gauge
ch3 = addinput(dq, "cDAQ9184-182032AMod2", "ai3", "Bridge"); % Add ai 0 input as Bridge modes
ch3.BridgeMode = "Full"; % Full mode
ch3.NominalBridgeResistance = 350; % Resisitance of the strain gauge
tic
while(toc<5)
Test = read(dq);
disp(Test)
pause(0.1);
end
Thank you.

Related

Matlab Convolutional Neural network not learning

I'm running an example that I got from a Webinar.
this is the code:
%% Fine Tuning A Deep Neural Network
clear; clc;close all;
imagenet_cnn = load('imagenet-cnn');
net = imagenet_cnn.convnet;
net.Layers
%% Perform net surgery
layers = net.Layers(1:end-3);
layers(end+1) = fullyConnectedLayer(12, 'Name', 'fc8_2')
layers(end+1) = softmaxLayer('Name','prob_2');
layers(end+1) = classificationLayer('Name','classificationLayer_2')
%% Setup learning rates for fine-tuning
% fc 8 - bump up learning rate for last layers
layers(end-2).WeightLearnRateFactor = 100;
layers(end-2).WeightL2Factor = 1;
layers(end-2).BiasLearnRateFactor = 20;
layers(end-2).BiasL2Factor = 0;
%% Load Image Data
rootFolder = fullfile('E:\Universidad\Tesis\Matlab', 'TesisDataBase');
categories = {'Avion','Banana','Carro','Gato', 'Mango','Perro','Sandia','Tijeras','Silla','Mouse','Calculadora','Arbol'};
imds = imageDatastore(fullfile(rootFolder, categories), 'LabelSource', 'foldernames');
tbl = countEachLabel(imds);
%% Equalize number of images of each class in training set
minSetCount = min(tbl{:,2}); % determine the smallest amount of images in a category
% Use splitEachLabel method to trim the set.
imds = splitEachLabel(imds, minSetCount);
% Notice that each set now has exactly the same number of images.
countEachLabel(imds)
[trainingDS, testDS] = splitEachLabel(imds, 0.7,'randomize');
% Convert labels to categoricals
trainingDS.Labels = categorical(trainingDS.Labels);
trainingDS.ReadFcn = #readFunctionTrain;
%% Setup test data for validation
testDS.Labels = categorical(testDS.Labels);
testDS.ReadFcn = #readFunctionValidation;
%% Fine-tune the Network
miniBatchSize = 32; % lower this if your GPU runs out of memory.
numImages = numel(trainingDS.Files);
numIterationsPerEpoch = 250;
maxEpochs = 62;
lr = 0.01;
opts = trainingOptions('sgdm', ...
'InitialLearnRate', lr,...
'LearnRateSchedule', 'none',...
'L2Regularization', 0.0005, ...
'MaxEpochs', maxEpochs, ...
'MiniBatchSize', miniBatchSize);
net = trainNetwork(trainingDS, layers, opts);
As you can see this code , uses the well known AlexNet as a first start, then the last 3 layers are deleted ,in order to put 3 new layers with the number of neurons necessary for the new task.
the read func for test and training are the same here you have one of them:
function Iout = readFunctionTrain(filename)
% Resize the flowers images to the size required by the network.
I = imread(filename);
% Some images may be grayscale. Replicate the image 3 times to
% create an RGB image.
if ismatrix(I)
I = cat(3,I,I,I);
end
% Resize the image as required for the CNN.
Iout = imresize(I, [227 227]);
this code runs well at the webinar, they use it to classify cars and subs that pass thru the matworks door.
The problem is that the new net is not learning when I try it with my own images,I have a data set of 12 categories each one with 1000 images more or less, all this images where downloaded from ImageNET.
the net does not increase its Mini batch accuracy, actually some times it does but very slow.
I also did the tutorial of this page
Matlab Deep Learning ToolBox
and it worked good with my images. So , I don't understand what is wrong with my fine-tuning. Thanks.
If you have R2016a and a GeForce GTX1080 or other Pascal GPU, then see this tech support answer and this bug report.
Your learning rate for the pre-trained section of the network (0.01) looks very high for a fine tuning workflow. Also, your LR of 1.0 is quite high for the randomly initialized classification head.
What happens if you set the learning rate of the pre-trained section to 0 and train only the randomly initialized head of the network? What happens if you just use a low learning rate and train end to end (say 1e-5)?
It would be useful to see the training-progress plot, but I think its possible you're not converging due to your learning rate settings.

Why is my BER become constant, is my code incorrect?

I am working to simulate the BER between 2 users in CDMA with convolutional codes and modulation scheme of QAM-16. From the graph i've attached, the BER of user 1 and user 2 are the same and constant. It seems that the SNR does not affect the transmission. Is there anyway i can improve the graph? Here is my code:
M = 16; % Modulation order
k = log2(M); % Bits per symbol
EbNoVec = (0:20)'; % Eb/No values (dB)
numSymPerFrame = 1; % Number of QAM symbols per frame
users=2; % Number of Users
trellis = poly2trellis(7,[171 133]);
tbl = 32;
rate = 1/2;
%------------------Generation of Walsh code--------------------------------
noOfSubCarrier =20; %Number of Data Sub-Carriers
walsh=hadamard(noOfSubCarrier);
code1=walsh(10,:);
code2=walsh(20,:);
berEst1 = zeros(size(EbNoVec));
berEst2 = zeros(size(EbNoVec));%Initialize the results vector
% The main processing loop executes the following steps:
% Generate binary data and convert to 64-ary symbols
% QAM modulate the data symbols
% Pass the modulated signal through an AWGN channel
% Demodulate the received signal
% Convert the demoduated symbols into binary data
% Calculate the number of bit errors
for n = 1:length(EbNoVec)
% Convert Eb/No to SNR
snrdB = EbNoVec(n) + 10*log10(k*rate);
% Reset the error and bit counters
numErrs1 = 0;
numErrs2 = 0;
numBits = 0;
% Generate binary data and convert to symbols
B=10;
dataIn1= rand(1,B);
dataIn2=rand(1,B);
symbols1= unique(dataIn1);
symbols2= unique(dataIn2);
probs1 = histc(dataIn1,symbols1)./numel(dataIn1);
probs2 = histc(dataIn2,symbols2)./numel(dataIn2);
[dict1, avglen1] = huffmandict(symbols1, probs1);
[dict2, avglen2] = huffmandict(symbols2, probs2);
comp1 = huffmanenco(dataIn1,dict1);
comp2 = huffmanenco(dataIn2,dict2);
% Convolutionally encode the data
dataEnc1 = convenc(comp1,trellis);
dataEnc2 = convenc(comp2,trellis);
% QAM modulate
txSig1 = qammod(dataEnc1,M,0);
txSig2 = qammod(dataEnc2,M,0);
%------------------Spreading & IFFT for User1------------------------------
Tx_data1=txSig1';
Spread_User1=Tx_data1*code1; % Spreading
Spread1=(Spread_User1)';
ifftdata_user1=ifft(Spread1); % Taking the IFFT
ifftdata1=ifftdata_user1';
%------------------Spreading & IFFT for User2------------------------------
Tx_data2=txSig2';
Spread_User2=Tx_data2*code2; % Spreading
Spread2=(Spread_User2)';
ifftdata_user2=ifft(Spread2); % Taking the IFFT
ifftdata2=ifftdata_user2';
%----------------------Addition of all signal------------------------------
TotSignal = Spread1+Spread2;
% Pass through AWGN channel
AwTotSignal = awgn(TotSignal,snrdB,'measured');
%-----------------------Removing the FFT & De-Spreading--------------------
fft_data_received =fft(AwTotSignal);
Rec_Data1=(AwTotSignal'*code1');
Rec_Data2=(AwTotSignal'*code2');
% Demodulate the noisy signal
rxSym1 = qamdemod(Rec_Data1,M,0);
rxSym2 = qamdemod(Rec_Data2,M,0);
data1=vitdec(rxSym1,trellis,5,'cont','unquant');
data2=vitdec(rxSym2,trellis,5,'cont','unquant');
% Convert received symbols to bits
%dataOut1 = de2bi(data1,k);
%dataOut2 = de2bi(data2,k);
% Calculate the number of bit errors
nErrors1 = biterr(comp1',data1);
nErrors2 = biterr(comp2',data2);
% Increment the error and bit counters
numErrs1 = numErrs1 + nErrors1;
numErrs2 = numErrs2 + nErrors2;
numBits= numBits + numSymPerFrame*k;
% Estimate the BER
berEst1(n) = numErrs1/numBits;
berEst2(n) = numErrs2/numBits;
end
graph of BER
[NOTE: This should actually be a comment, but I cannot write them with my current SO reputation and this is something the OP should know]
First of all, I confess I didn't have a particularly hard look at your code because the errors I see in the graphs come from bugs unrelated to CDMA or the modulation at hand.
I'd say the most remarkable error is not the graphs being constant, but the BER being over 1. That makes no sense at all and indicates that, at least, there's something wrong with your formulation of the BER itself.
Moreover, if the BER was actually 1 and not over it it would still make no sense. Take into account that a BER of 1 (let alone OVER 1) implies that you fail to recover the symbol correctly every single time. By simple statistics you should recover at least some of them correctly even if picking them at random. That's another common error scenario in this kind of applications.
That said, check your BER formulation and plot some intermediate values. Don't do everything in one step (e.g: Try the system without the correction codes).
I hope that gives you a bump in the right direction.

Lsqnonlin on Matlab and Hardware-In-The-Loop with Arduino

I'm having some trouble with the function "lsqnonlin" on Matlab. I'm trying to optimize a PID controller inside Arduino by using this function that has the coefficients (Kp,Ki,Kd) of the PID as decisional variables and the goal function is to minimize the least-square difference of the response minus the reference value.
This link explains better what I'm doing: http://it.mathworks.com/help/optim/ug/lsqnonlin-with-a-simulink-model.html.
The difference between that example and my problem is that I want to perform a sort of Hardware-In-The-Loop simulation, replacing the simulation performed by Simulink with the actual system that I designed, on which a sensor interfaced with Arduino provides the response "yout" to Matlab by Serial Communication.
The problem is that the algorithm on Matlab changes the variables (Kp,Ki,Kd) with a really small step (10^-8 or something like that) and so I can't see any change on the actual response. After a few iterations the algorithm stops saying: "lsqnonlin stopped because the size of the current step is less than
the selected value of the step size tolerance".
I can't understand why the steps are so little and why it stops like that. My code is the following.
pid0 = [10 0 0]; %inizialization of PID parameters
options = optimset('LargeScale','off','Display','iter',...
'TolX',0.001,'TolFun',0.001);
pid = lsqnonlin(#trackpid, pid0, [0 0 0], [], options)
Kp = pid(1); Ki = pid(2); Kd = pid(3);
The trackpid function is:
function F = trackpid(pid)
% Serial communication
s = serial('/dev/cu.usbmodemFD131');
set(s,'BaudRate', 9600);
set(s,'DataBits', 8);
set(s,'StopBits', 1);
% Global Variables
numberOfDatas = 700;
Kp = pid(1)
Ki = pid(2)
Kd = pid(3)
i = 1;
fopen(s);
pause(1.7); %i need to wait 1.7s in order to read the values
%Send to Arduino the PID coefficients
fprintf(s,num2str(Kp));
fprintf(s,num2str(Ki));
fprintf(s,num2str(Kd));
while (fscanf(s,'%c') ~= 't') %Wait for Arduino to start the simulation
end
%Scan
while(i <= numberOfDatas)
yout(i) = fscanf(s,'%f');
i = i + 1;
end
fclose(s);
yout
F = yout - 21; %evaluate the difference between the response and the reference
Thank you in advance.

How can I output a composite signal made of two signals with different time period at the same time on one audio channel in matlab code?

%-------------------------------------------------------------------
% Function to Generate ECG of 1 heart beat signal
function [Heartbeat,t1] = ECG_Gen (HR,pulse_width,Amp)
Fs = 48000;
delay = ((60/HR)/2)-(0.5*pulse_width);
t1 = -delay:(1/Fs):delay;
Heartbeat = Amp*tripuls (t1,pulse_width);
%-------------------------------------------------------------------
%Test Circuit configuration
function [FECG_MECG,Mixed_ECG,fastTime] = Test_Circuit (FHR,MHR)
Fs = 48000;
%FHR = 150;
%MHR = 60;
Fpulse_width = 30e-3;
Mpulse_width = 60e-3;
FAmp = 0.2;
MAmp = 0.5;
% Fetal ECG Gen
%------------------------------------------------
[FECG,FHR_Delay]= ECG_Gen (FHR,Fpulse_width,FAmp);
% Maternal ECG Gen
%------------------------------------------------
[MECG,MHR_Delay]= ECG_Gen (MHR,Mpulse_width,MAmp);
% Composite signal implementation
%------------------------------------------------
% Set parameters for Composite signal Algorithms
if length (MECG) > length (FECG) % Check for time sequences for both ECG signal
slowECG = FECG; % Set interpolation to slower rate
fastECG = MECG;
timeSeg = length(MECG);
fastTime = MHR_Delay; % Set sampling times
slowTime = FHR_Delay;
else
slowECG = MECG;
fastECG = FECG;
timeSeg = length(FECG);
fastTime = FHR_Delay;
slowTime = MHR_Delay;
end
FECG_MECG = zeros (timeSeg,2); % To hold stereo output
FECG_MECG(:,2) = fastECG(1,:); % Assign higher rate signal to one channel
% Interpolation on the slower rater sampled ECG
slowECGInterp = interp1 (slowTime,slowECG,fastTime);
slowECG = num2cell(slowECGInterp); % Conversion to cell Array in order to remove NaN
slowECG(cellfun(#(slowECG) any(isnan(slowECG)),slowECG)) = [];
slowECG = cell2mat(slowECG);
j = 1;
for i = 1:timeSeg
FECG_MECG(i,1) = slowECG(1,j);
if j == length(slowECG)
j = 0;
end
j = j+1;
end
Mixed_ECG = FECG_MECG(:,1) + FECG_MECG(:,2); % to hold mono output
%while (1)
%sound(Mixed_ECG ,Fs);
%end
%-------------------------------------------------------------------
% Test Wave script
clear all
%clc
clc
Fs = 48000;
%for i = 1:3
%toc
MHR = 60;
FHR = 200;
% Obtain ECG interpolated signal and composite
[FECG_MECG,Mixed_ECG,fastTime] = Test_Circuit (FHR,MHR);
% for test purposes
[MECG,MHR_Delay]= ECG_Gen (60,60e-3,0.5);
%t = timer ('TimerFcn','stat=false','Period',2.0);
wavwrite (FECG_MECG(:,2),Fs,'ECGwav.wav');
i = 0;
a = 1;
tic
while (1)
while (toc < 20*a)
sound (MECG,Fs);
end
toc
a = a+1;
[MECG,MHR_Delay]= ECG_Gen (60*a,60e-3,0.5);
if a > 4
break
end
end
%start(t)
%tic
%t = cputime;
%y = wavread('ECGwav.wav');
%while (1)
% sound(y,Fs);
%end
%toc
Hey Thank you very much for getting back to me, I have made use of your interpolation but still have minor problems from the reading obtained from the Monitor. Fist of all, say I have a constant signal with fixed time period say, 0.8s and I want to add composite signal of say 0.3s, I have managed to use your interpolation method to sample the 0.3s signal at the rate of my 0.8s signal. I think I have solved this issue. Second issue deals with how to combine the two signals which I have managed to do somehow but when I use a while loop in order to repeat the composite signal say over 20s, the signals obtained from the sound output isn't quite what I expected since its sounding the array of stored composite signal which contain ( signal with 0.8s = slowInterp signal of 0.3s ). I have include all the codes and functions. Basically, I need the sound output in while loop to sync with the composite signal for example: if I have a signal that repeats every 1s, I would expect to hear a beep in a while loop that runs for 10s to produce 10 beeps, etc
It is hard to tell exactly what you need, but probably doing interpolation on the sequence that is sampled at the slower rate would work for your application.
If t1s are your times from your faster sequence, and t2s are times from your slower sequence, and slow is your slower sequence then do:
slowInterp = interp1(t2s, slow, t1s);
now you will have the sequency slow sampled at the faster rate.
This is only useful for displaying the time series. If you are doing any spectral analysis, this will introduce artifacts, but that is a more advanced topic.
Using the resample function in the signal processing toolbox could also be useful.

Setting sampling rate in MATLAB for Arduino

I'm having trouble getting consistent results with the code I am using. I want to run my Arduino for a specific amount of time (say 20 seconds) and collect data from the analog pin with a specific sampling rate (say four samples a second). The code is as follows.
a_pin = 0;
tic;
i = 0;
while toc < 20
i = i + 1;
time(i) = toc;
v(i) = a.analogRead(a_pin);
pause(.25);
end
Is there a way to set the loop to run a specific time and then in the loop sample at a different rate?
You can try this:
a_pin = 0;
fs = 4; % sampling frequency (samplings per second)
mt = 20; % time for measurements
ind = 1;
nind = 1;
last_beep = 0;
tic;
while toc < mt
time(ind) = toc;
v(ind) = a.analogRead(a_pin);
% wait for appropriate time for next measurement
while( nind == ind )
nind = floor(toc*fs) + 1;
end
ind = nind;
% beep every second
if (ceil(toc) > last_beep)
beep(); % don't know if this one exist, check docs
last_beep = ceil(toc);
end
end
Maximal sampling time for a single Arduino analog read command is around 0.04 s, in practice I'd go minimally 0.05. Adding two read operations is in the order of 2*0.04, in practice more like 0.1 s. I think it is mainly limited by the USB communication speeds.
I am also new at arduino, but having implemented a real time analysis for EEG using it, on practice, I was able to sample 2 analog channels with a samplinf frequency between 57 and 108Hz. It was very variable (calculated through tic/toc), but it is still proper for realtime processing in my case.
My code uses a While loop, a series of memory updates, digital pin manipulations, plot of trace (drawnow) and seems to run smoothly enough
My answer is simply here : 0.0283 sec for sampling 2 analog inputs in my case.
Cheers