How to control keyboard in matlab using the data from the serial port?

5 views (last 30 days)
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.

Answers (1)

Walter Roberson
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
Mohamed Fazil
Mohamed Fazil on 13 Dec 2015
data =
49 13 10
i got something like this.I used a note pad keeping it near by and made the cursor to go on top of it and click. But also it dint work.
% code
import java.awt.Robot;
import java.awt.event.*;
robot = Robot;
mouse = Robot;
s=serial('COM5');
set(s,'BaudRate', 9600);
set(s,'DataBits', 8);
set(s,'StopBits', 1);
fopen(s);
s.ReadAsyncMode = 'continuous';
________________________________________________________
mouse.mouseMove(0,0);
for i = 0:250
mouse.mouseMove(60,i);
pause(0.00001);
end
mouse.mousePress(InputEvent.BUTTON1_MASK);
pause(0.00001);
mouse.mouseRelease(InputEvent.BUTTON1_MASK);
____________________________________________
while 1
data=fscanf(s);
data=double(data);
display(data);
if data=='1'
robot.keyPress(java.awt.event.KeyEvent.VK_W);
else
try
robot.keyRelease(java.awt.event.KeyEvent.VK_W);
end
end
end
fclose(s);
Walter Roberson
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).

Sign in to comment.

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!