How to replicate an Arduino timer function in Matlab?
Show older comments
I'm using the Mathworks Arduino Support Package and trying to replicate the function of an Arduino script in Matlab. The code should control an ultrasonic sensor to measure distance to a moving object.
The sensor returns its measurement readings by varying the time it holds a nominated Arduino I/O pin high. So, I need to have Matlab watch that input pin, timing the period it takes to go from digital low, to high, to low again.
In Arduino speak I have the native "pulseIn" function, which is used in this way:
pulse_duration=pulseIn(sensor_signal_pin, HIGH)
Can anyone suggest the best way to do this in Matlab?
I've been trying variations on a while loop, but making an embarrassing mess of it. This sort of thing:
while a.digitalRead(sensor_signal_pin)==1;
tic;
end
toc
pulse_duration=toc-tic;
The "a.digitalRead(sensor_signal_pin)" command simply instructs Matlab to read the value of the nominated Arduino pin, checking for high or low signal (1 or 0).
Anyone offer a suggestion? I need to do this as neatly as possible because the timing is important - if I don't time the duration the input pin is held high correctly, my distance readings will be inaccurate.
Thanks if you can offer advice.
G.
1 Comment
Gautam Vallabha
on 5 Apr 2012
If you want to measure elapsed time on the order of tens of milliseconds, you need to do it by adding a custom capability to the .pde file, as in Felipe's answer below. Doing the timing measurement from MATLAB will lead to a lot of variability due to
a) the communication latency in the serial request and the response, and
b) Operating system variability (e.g., if there are other high-priority processes running on the host OS that preempt MATLAB).
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!