Push switch with Arduino

30 views (last 30 days)
sky keeper
sky keeper on 24 Apr 2021
Answered: sky keeper on 24 Apr 2021
I have a push swtich connect to matlab through arduino.i want to write a function for counting push swtich on and off counting. Function y fun (u) Count= 0; Ifu==0 Count=count+1; y = count;

Accepted Answer

Clayton Gotberg
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;
% end
end
delay(50/1000); % Limits the rate the button is tested
end
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.

More Answers (1)

sky keeper
sky keeper on 24 Apr 2021
Function y = (u) Count =0; While u==0 If u~=u Count = count+1; Y = count; End End

Categories

Find more on Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!