Arduino Programming using MATLAB, 1st Edition (2015)
3. Working with Digital I/O
In this chapter I'm going to explain how to work with digital I/O on Arduino board and write a program for demo.
3.1 Getting Started
MATLAB support for Arduino board provides three functions which we can use on digital I/O processing. The following is the functions:
· configurePin() is used to define pin mode either as input or output. Reference: http://www.mathworks.com/help/supportpkg/arduinoio/ref/configurepin.html
· writeDigitalPin() is used to write digital data into a specific digital pin. Reference: http://www.mathworks.com/help/supportpkg/arduinoio/ref/writedigitalpin.html
· readDigitalPin() is used to read digital input on specific digital pin. Reference: http://www.mathworks.com/help/supportpkg/arduinoio/ref/readdigitalpin.html
To illustrate how to work with digital I/O, we build a simple program by utilizing LED and pushbutton.
3.2 Demo : LED and Pushbutton
we build a program using LED and pushbutton. When we press a pushbutton, LED will lighting. It's a simple;).
3.2.1 Wiring
The following is hardware wiring:
· LED is connected to Arduino digital pin 9
· Pushbutton is connected to Arduino digital pin 8
A sample of hardware implementation is shown in Figure below.
3.2.2 Writing a Program
Now you can write these scripts.
function [] = led_pushbutton()
pushbutton = 'D8';
led = 'D9';
board = arduino();
finishup = onCleanup(@() exitprogram(board));
configurePin(board,pushbutton,'DigitalInput');
disp('press Ctr-C to exit');
while1
state = readDigitalPin(board,pushbutton);
writeDigitalPin(board,led,state);
disp(state);
pause(0.5);
end
end
functionexitprogram(b)
clear b;
disp('program has exit');
end
We use onCleanup(), http://www.mathworks.com/help/matlab/ref/oncleanup.html , to catch CTRL+C for quiting the program.
Save this program into file, called led_pushbutton.m.
3.2.3 Testing
Run this program by typing this command on Command Window on Matlab.
>> led_pushbutton
Press pushbutton. Then, you should see lighting LED. Press CTRL+C to exit program.
Program output:
LED is lighting while a pushbutton is pressed.