본문 바로가기
Programming/Sensors

Distance Measurement by Ultra Sensor

by OKOK 2017. 4. 5.

There are  two ways t o measure physical distance.

Analog : reuler

Digtal : Untra sensor (HCSR-04)


Digital is very convenient. Measure using ultra sensor.

Error rate 1 - 2% means it is available in real life easily.


Connect the data acquistion device NI6009 and Matlab.

Matlab code: 2 Scripts.


1. UltraSensor.m

%% Ultra Sensor


%% Device setting

a = daq.getDevices


% Session for Input(echo)

ai = daq.createSession('ni')

ai.Rate = 48000;

ai.DurationInSeconds = 1;

ai.NotifyWhenDataAvailableExceeds = 48000;


% Port for Input(echo)

aic = addAnalogInputChannel(ai, 'Dev1', 'ai0', 'Voltage')

aic.TerminalConfig = 'SingleEnded'

aic.Range = [-5.0 5.0]


%%  

% Session for Output(trig)

do = daq.createSession('ni')

% Port for Output(trig)

doc = addDigitalChannel(do, 'Dev1', 'port0/line0:7', 'OutputOnly')

% Output Initailization

init = [0 0 0 0 0 0 0 0];

one = [1 0 0 0 0 0 0 0];

outputSingleScan(do, init);


%% Background

global data;

global time;

global x1;

global x2;


data = [];

time = [];

lh = addlistener(ai, 'DataAvailable', @plotData);

startBackground(ai)


for i = 1:1:1 % 3 times for trigger

%pause(0.5) % throw out trash data

outputSingleScan(do, one);

pause(0.01); % 0,001s > 0.00001s

outputSingleScan(do, init);

pause(0.1); % 0.1s > 0.06s    

end


%% Distance = Time * Velocity

distance = ((x2-x1)*(1/48000) * 340/2)*100

%% cftool

x = [20 40 60 80 100];

y = [20.25 39.31 59.5 78.98 98.81]

cftool(x,y) 


2. plotData.m

%% Background plotData function -> Data, Time = []


function plotData(src, event)

global data;

data = [data;event.Data];

global  time;

time = [time;event.TimeStamps];

global x1;

global x2;


global flag;

flag = 0;


for i=1:1:length(event.Data)

    if event.Data(i) >= 2.5

        if flag == 0;

            flag = 1;

            x1 = i

        end

    else event.Data(i) < 2.5

        if flag == 1;

            flag = 0;

            x2 = i

        end

    end        

end



plot(time,data)


end



The results are as follows


Echo Pulse Output sample

    

ruler measurement(cm)

2

20

40

60

80

100

180

Sensor measurement(cm)

2.75

20.25

39.3125

59.5

78.9792

98.8125

121

Error rate(%)

37.5

1.25

1.72

0.83

1.28

1.19

32.8