How to control keyboard in matlab using the data from the serial port?
1 回表示 (過去 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!