How to control keyboard in matlab using the data from the serial port?
5 views (last 30 days)
Show older comments
Iam working in an Arduino project where it sends data to the serial port and the matlab receives it and a key press is done according to the data.
% code
import java.awt.Robot;
import java.awt.event.*;
robot = Robot();
%code
s=serial('COM5');
set(s,'BaudRate', 9600);
set(s,'DataBits', 8);
set(s,'StopBits', 1);
fopen(s);
s.ReadAsyncMode = 'continuous';
data=0;
%code
while 1
data=fscanf(s);
if data==1
robot.keyPress(java.awt.event.KeyEvent.VK_W);
end
display(data);
end
fclose(s);
I have uploaded the my Matlab file iam currently using. Where if the data==1 the "W" key should be pressed by matlab. The code key press event code works well when it is no in if condition. Need a solution please.
0 Comments
Answers (1)
Walter Roberson
on 12 Dec 2015
You are using fscanf(s) . The default format for fscanf serial is %c , which is character. In order for a character to compare equal to 1 it would have to be char(1), the Start of Header (SOH) character.
If you want to receive numeric data then you should specify a numeric format for the fscanf(). If you want to compare to the digit 1 then you need to compare to the digit 1, which is '1', char(49), not 1
10 Comments
Walter Roberson
on 13 Dec 2015
49 13 10 is '1' followed by carriage return followed by linefeed. You should configure your serial port to use CR/LF termination, and you should use fgetl() instead of fscanf(). The result of fgetl() will be characters with no line terminator. You can then strcmp() that to '1' (strcmp() is safer than == for characters in case the input is not exactly one character).
See Also
Categories
Find more on ROS Toolbox 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!