Serial Communication problem fread() in while loop
6 次查看(过去 30 天)
显示 更早的评论
Hi, I am trying to make MATLAB capture an image upon received a character 'c' at serial port. The following is my coding
% Start up the video
vid = videoinput('winvideo', 1);
preview(vid);
%Wait for signal from pushbutton
s = serial('COM12');
while(w ~='c')
fopen(s)
a=1
w = fread(s) ;
a=2
fclose(s)
end
Image = getsnapshot(vid);
imagesc(Image)
closepreview(vid)
delete(vid);
I've tried without using the while loop, using an if statement instead before the getsnapshot, but the execution continue to getsnapshot when the fread timeout and fail (because 'c' not yet received at serial port). Therefore i try to add the while loop, but the result turn out the same. execution step out from while loop even before the condition (w==c) is met.
I tried out seeting the timeout of serial port, but instead of doing what i expected, the capture of image delayed, even when 'c' is sent to serial port.
Anyone here give suggestion on how i can change my code to function as what i desire?
0 个评论
回答(1 个)
Walter Roberson
2012-5-18
fopen() before the loop. Initialize w before the loop. If you use fread(), specify the number of characters to read and specify that you expect characters and want characters output. fclose() after the loop.
Before you fopen(), set() the properties of "s" for BytesAvailableFcnMode to 'byte', and Terminator to '' . The 'byte' mode is important: otherwise the fread() will not return until timeout or you receive a line terminator.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!