Push switch with Arduino
26 views (last 30 days)
Clayton Gotberg on 24 Apr 2021
If you have the Arduino support package, you can directly read the values of the digital I/O pins. After that, it's a matter of logic to determine the press count:
a = arduino; % Prepare to address the Arduino
% Perform any more setup for the Arduino
button_pin = 'D13'; % Change value to whichever digital pin is meant to be read.
pin_value_save = 0;
count = 0;
while true % this loop will run until you cancel it with Ctrl+C
pin_value = readDigitalPin(a, button_pin); % Measure value of button
if pin_value ~= pin_value_save % When the value of the pin changes
pin_value_save = pin_value;
count = count + 1; % Increment the count - note this counts presses and releases
% if pin_value == 1 % Uncomment this and delete above line to only count button presses
% count = count+1;
delay(50/1000); % Limits the rate the button is tested
If you need this to run in the background while your program does other things it gets significantly more complex, though. MATLAB only has interrupts in Simulink and GUI callback functions, so you'll need to restructure things in that way.
If you don't have the support package, you'll want to have Arduino send a signal when the value of the button pin changes, using the Serial.println() function in Arduino and the serial functions in MATLAB to interpret the results. The best part of this method is that the Arduino's serial buffer will hold any values (up to 64) from the Arduino until the script gets back to it, so you can ask MATLAB to do other things and just read in the buffer when possible. Then, you can just count the size of the buffer to figure out how many more events have happened since the last reading.