How to control keyboard in matlab using the data from the serial port?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2015-12-12
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 个评论
Walter Roberson
2015-12-13
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).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 ROS Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!