2017-03-28 102 views
0

我想用Matlab R2016b控制Prior ProScan II控制器和擬合電動舞臺。 Manual用R2010b測試,得到了同樣的結果。該階段的相關命令是VS(第46頁),P(第43頁),PS(第44頁)。在一個普通的終端中,緊接着舞臺暫停後,我可以發出P或PS命令,返回X軸和Y軸的當前位置。如果在Matlab提示符下完成,可能需要一兩秒鐘才能返回正確的值,然後返回'R' - 可能不是前一個命令的ACK,因爲它是在init之後返回的,沒有任何R-ACKed命令。當在單獨的.m文件的腳本中使用時,它只能返回'R'。我在main.m文件的代碼如下:Matlab串行通信不一致

%Opening serial port 
s = serial('COM9'); 
set(s,'BaudRate',9600,'Terminator','CR'); %Note that CR will be concatenated to all commands 
fopen(s); 
s  %print for debugging 

t=1  %loop index 

while true 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
    %Here is code to mess with a joystick that works fine, using VS command 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

    if button(joy, 3) == 1   %Button3 of joystick should trigger position reading 
     fprintf(s,'vs,0,0');  %Halt joystick movement 
     pause(1)     %Debouncing 
     fprintf(s,'p');    %Axe-pos reading command 
     fgets(s)     %Reading the answer 
end 


%This way to increment follows the skipped parts and is required for timing 
if mod(t, 100)==0 
     fprintf(s,'%s',Command); 
     t=1; 
    else 
     t=t+1; 
end 

如果if..end該段從MATLAB提示符下調用,它工作在大多數情況下的罰款。

>> s = openserial() 
%properties as before, skipped to save space 
>> fprintf(s,'ps'); 
>> fgets(s) 

ans = 

100000,100000 

>> fprintf(s,'p'); 
>> fgets(s) 

ans = 

100000,100000,0 

如果我按Ctrl + C從無限循環的,但離開串行開放和問題

>> fprintf(s,'p'); 
>> fgets(s) 

ans = 

R 

回報。使用fscanf()而不是fgets()會得到相同的結果。

是否有任何已知的fprintf()或上面提到的可能導致此問題的bug?我能做些什麼才能在腳本中成功並一致地閱讀?謝謝你的回答。

+0

解決方法是在暫停(1)之前強制刷新串行輸入緩衝區,flushinput(s)。我仍然不知道爲什麼它在腳本之外運行良好,而不是在腳本之內。 – navigator

回答

0

解決方法是在線路暫停(1)之前強制刷新串行輸入緩衝區,flushinput(s)。出於某種原因,即使fscanf()而不是fgets()也不會刷新它。我仍然不知道爲什麼它在腳本之外運行良好,但不在其中。此外,它也在單獨的腳本中工作。

+0

嗨,我有一個類似的超時時間問題在這裏給出 - https://stackoverflow.com/questions/48667884/timeout-on-waiting-for-command-from-serial-communication-device-using-matlab。你有沒有遇到過這樣的問題? –