-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMovementInterface.m
More file actions
109 lines (105 loc) · 3.39 KB
/
MovementInterface.m
File metadata and controls
109 lines (105 loc) · 3.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
classdef MovementInterface < hgsetget
properties
sensors = {'1','2'}
mouse1
mouse2
end
properties
serialObj
serialTag
serialPort = 'COM4'
serialBaudRate = 9600
end
properties (SetObservable)
state = 'ready'
end
methods
function obj = MovementInterface(serialPort)
if nargin > 0
obj.serialPort = serialPort;
end
obj.serialObj = serial(obj.serialPort);
set(obj.serialObj,...
'BytesAvailableFcn',@(src,evnt)readSerialFcn(obj,src,evnt),...
'BaudRate',obj.serialBaudRate);
%'FlowControl',);
obj.mouse1 = SensorMike('1');
obj.mouse2 = SensorMike('2');
end
function msg = readSerialFcn(obj,~,~)
try
if strcmp(obj.state,'running')
msg = fscanf(obj.serialObj,'%s');
else
fprintf('Serial port is closed. Flushing and resuming\n');
flushinput(obj.serialObj);
fopen(obj.serialObj);
msg = fscanf(obj.serialObj,'%s');
end
msg = msg(:)';
msg = obj.parsedeltas(msg);
catch me
warning(me.message)
disp(me.stack(1))
disp(me.stack(2))
end
end
function start(obj)
try
flushinput(obj.serialObj);
fopen(obj.serialObj);
disp('STARTING MovementInterface')
catch err
disp(err.message);
disp(err.stack(1))
disp(err.stack(2))
instrhwinfo('serial') %KD
delete(instrfindall); %KD
obj.serialObj = serial(obj.serialPort);
set(obj.serialObj,...
'BytesAvailableFcn',@(src,evnt)readSerialFcn(obj,src,evnt),...
'BaudRate',obj.serialBaudRate);
% 'FlowControl','hardware');
fopen(obj.serialObj);
end
obj.state = 'running';
end
function stop(obj)
try
disp('stopping...')
fclose(obj.serialObj);%todo: cleanup with instrument control toolbox tools
disp('stopped!')
catch err
disp(err);
end
end
function msg = parsedeltas(obj,msg)
if isempty(msg)
msg = NaN;
return
end
sensornum = msg(1);
if ~any(strcmp(sensornum,obj.sensors))
msg = [];
return
end
x_index = regexp(msg,'[x]*');
y_index = regexp(msg,'[y]*');
dx = str2double(msg(x_index+1:y_index-1));
dy = str2double(msg(y_index+1:end));
if isa(dx,'double') && isa(dy,'double')
obj.(sprintf('mouse%s',sensornum)).dx = dx;
obj.(sprintf('mouse%s',sensornum)).dy = dy;
else
error('bad sensor data!');
end
end
function delete(obj)
if ~isempty(obj.serialObj) && isvalid(obj.serialObj)
fclose(obj.serialObj);
delete(obj.serialObj);
end
instrreset
end
end
end