I want to check if I receive a dot ('.') on serial port in Matlab. For this I run for loop for 10 times in which I check if I got '.' on serial port then display "A dot is received" otherwise display whatever is receive. But on receiving '.' on serial port it is not displaying "A dot is receibed". Here is my code:-
s=serial('COM5', 'BaudRate',9600);%, 'DataBits',8, 'Terminator','');
fopen(s);
disp('Port succefully Opened');
count=0;
checkdot = '.';
for x = 1:10
recv= fscanf(s);
z = char(recv);
if (z== '.')
disp('A dot is received');
else
disp(z);
end
end
fclose(s);
And here is my output on command window:-
>> Serialcomm
Port succefully Opened
.
.
.
.
.
.
.
.
.
.
So, please tell me where is the mistake.
You can use deblank (removes all whitespace characters) or strtrim (removes only leading and trailing whitespace) to get rid of unwanted characters:
a = sprintf('.\r\n');
disp(a)
.
strcmp(a,'.')
ans =
0
strcmp(strtrim(a),'.')
ans =
1
Also, you're using fscanf to retrieve data from the serial port, try using fgetl instead. fgetl gets one line and discards terminators, so should only retrieve the . (in theory).
Related
In matlab i'm coding a Ceaser Cipher, but the space shows up as a 'y' character.
How can I replace that with a space
case 4
disp('Breaking Ceaser Cipher')
cs = menu('Please Enter your Choice','Encryption','Decryption');
if cs==1
c = input('Enter the message: ','s');
sh = str2double(input('Enter shift: ','s'));
c=upper(c);
lc=length(c);
for i=1:lc
p(i)=int16(c(i))-65+sh;
end
p=mod(p,26)+97;
p=char(p);
disp( p)
end
end
output example:
Breaking Ceaser Cipher
Enter the message:
my name is jeff
Enter shift:
5
rdysfrjynxyojkk
Here we see that the encryption is correct, but the space is being replaced by 'y'. It does not replace the character 'y' when used as an input, the space bar somehow comes out as a 'y'.
I'v also tried using p2 = regexprep(c, 'y', ' ') in order to replace the 'y' string with space.Also looked into isspace function. No luck
You are halfway there:
spaces=isspace(c)
% make array of spaces
out=blanks(size(c));
% get array without spaces
c=c(~spaces);
% do stuff to c, without spaces.
p=mod(p,26)+97;
p=char(p);
% Fill p in corresponding locations
out(~spaces)=p;
I'm working on reading device reply using QBasic. The problem is the qbasic wait for the newline or CHR$(13) before outputting the data but my device reply don't have CHR$(13) (example: "OK") so qbasic hang waiting for newline.
How can i get the reply or read comport even without newline? is this possible?
[EDIT]
CLS
OPEN "com2:9600,n,8,1,BIN,cs,ds,rs" FOR RANDOM AS #1
param$ ="Some data"
PRINT #1, param$
DO WHILE b$ <> "*CLOSE*"
INPUT #1, b$
PRINT b$
LOOP
That is my code but in that code it can't read *CLOSE* because no newline after *CLOSE*.
And another thing the device delay 5 sec before replying.
Could you give an example of your code? I suspect you are using INPUT#n , but maybe instead you should use INPUT$(x). I found an example here, see code below
a$ = ""
DO
IF LOC(1) THEN a$ = a$ + INPUT$(1, 1)
LOOP UNTIL INSTR(a$, "OK")
This code sample demonstrates accessing modem in Basic.
REM Reset modem source:
CLS
OPEN "COM2:9600,N,8,1,BIN,CS,DS,RS" FOR RANDOM AS #1
Reset$ = "ATZ" + CHR$(13) + CHR$(10)
PRINT #1, Reset$;
Inp$ = ""
DO
IF LOC(1) THEN
Inp$ = Inp$ + INPUT$(1, 1)
IF INSTR(Inp$, "OK") THEN
PRINT "Modem reset."
EXIT DO
END IF
END IF
LOOP
END
AIR, ID
AIR.SIT
50 1 1 1 0 0 2 1
43.57 -116.24 1. 857.7
Hi, All,
I have a text file like above. Now in Matlab, I want to create 5000 text files, changing the number "2" (the specific number in the 3rd row) from 1 to 5000 in each file, while keeping other contents the same. In every loop, the changed number is the same with the loop number. And the output in every loop is saved into a new text file, with the name like AIR_LoopNumber.SIT.
I've spent some time writing on that. But it is kind of difficult for a newby. Here is what I have:
% - Read source file.
fid = fopen ('Air.SIT');
n = 1;
textline={};
while (~feof(fid))
textline(n,1)={fgetl(fid)};
end
FileName=Air;
% - Replace characters when relevant.
for i = 1 : 5000
filename = sprintf('%s_%d.SIT','filename',i);
end
Anybody can help on finishing the program?
Thanks,
James
If your file is so short you do not have to read it line by line. Just read the full thing in one variable, modify only the necessary part of it before each write, then write the full variable back in one go.
%% // read the full file as a long sequence of 'char'
fid = fopen ('Air.SIT');
fulltext = fread(fid,Inf,'char') ;
fclose(fid) ;
%% // add a few blank placeholder (3 exactly) to hold the 4 digits when we'll be counting 5000
fulltext = [fulltext(1:49) ; 32 ; 32 ; 32 ; fulltext(50:end) ] ;
idx2replace = 50:53 ; %// save the index of the characters which will be modified each loop
%% // Go for it
baseFileName = 'AIR_%d.SIT' ;
for iFile = 1:1000:5000
%// build filename
filename = sprintf(baseFileName,iFile);
%// modify the string to write
fulltext(idx2replace) = num2str(iFile,'%04d').' ; %//'
%// write the file
fidw = fopen( filename , 'w' ) ;
fwrite(fidw,fulltext) ;
fclose(fidw) ;
end
This example works with the text in your example, you may have to adjust slightly the indices of the characters to replace if your real case is different.
Also I set a step of 1000 for the loop to let you try and see if it works without writing 1000's of file. When you are satisfied with the result, remove the 1000 step in the for loop.
Edit:
The format specifier %04d I gave in the first solution insure the output will take 4 characters, and it will pad any smaller number with zero (ex: 23 => 0023). It is sometimes desirable to keep the length constant, and in your particular example it made things easier because the output string would be exactly the same length for all the files.
However it is not mandatory at all, if you do not want the loop number to be padded with zero, you can use the simple format %d. This will only use the required number of digits.
The side effect is that the output string will be of different length for different loop number, so we cannot use one string for all the iterations, we have to recreate a string at each iteration. So the simple modifications are as follow. Keep the first paragraph of the solution above as is, and replace the last 2 paragraphs with the following:
%% // prepare the block of text before and after the character to change
textBefore = fulltext(1:49) ;
textAfter = fulltext(51:end) ;
%% // Go for it
baseFileName = 'AIR_%d.SIT' ;
for iFile = 1:500:5000
%// build filename
filename = sprintf(baseFileName,iFile);
%// rebuild the string to write
fulltext = [textBefore ; num2str(iFile,'%d').' ; textAfter ]; %//'
%// write the file
fidw = fopen( filename , 'w' ) ;
fwrite(fidw,fulltext) ;
fclose(fidw) ;
end
Note:
The constant length of character for a number may not be important in the file, but it can be very useful for your file names to be named AIR_0001 ... AIR_0023 ... AIR_849 ... AIR_4357 etc ... because in a list they will appear properly ordered in any explorer windows.
If you want your files named with constant length numbers, the just use:
baseFileName = 'AIR_%04d.SIT' ;
instead of the current line.
I'm trying to make an algorithm in Matlab that scans the character array from left to right and if it encounters a space, it should do nothing, but if it encounters 2 consecutive spaces, it should start printing the remaining quantities of array from next line. for example,
inpuut='a bc d';
after applying this algorithm, the final output should have to be:
a bc
d
but this algorithm is giving me the output as:
a bc
d d
Also, if someone has got a more simpler algorithm to do this task, do help me please :)
m=1; t=1;
inpuut='a bc d';
while(m<=(length(inpuut)))
if((inpuut(m)==' ')&&(inpuut(m+1)==' '))
n=m;
fprintf(inpuut(t:(n-1)));
fprintf('\n');
t=m+2;
end
fprintf(inpuut(t));
if(t<length(inpuut))
t=t+1;
elseif(t==length(inpuut))
t=t-1;
else
end
m=m+1;
end
fprintf('\n');
OK I gave up telling why your code doesn't work. This is a working one.
inpuut='a bc d ';
% remove trailing space
while (inpuut(end)==' ')
inpuut(end)=[];
end
str = regexp(inpuut, ' ', 'split');
for ii = 1:length(str)
fprintf('%s\n', str{ii});
end
regexp with 'split' option splits the string into a cell array, with delimiter defined in the matching expression.
fprintf is capable of handling complicated strings, much more than printing a single string.
You can remove the trailing space before printing, or do it inside the loop (check if the last cell is empty, but it's more costly).
You can use regexprep to replace two consecutive spaces by a line feed:
result_string = regexprep(inpuut, ' ', '\n');
If you need to remove trailing spaces: use this first:
result_string = regexprep(inpuut, ' $', '');
I have a solution without using regex, but I assumed you wanted to print on 2 lines maximum.
Example: with 'a b c hello':
a b
c hello
and not:
a b
c
hello
In any case, here is the code:
inpuut = 'a b c';
while(length(inpuut) > 2)
% Read the next 2 character
first2char = inpuut(1:2);
switch(first2char)
case ' ' % 2 white spaces
% we add a new line and print the rest of the input
fprintf('\n%s', inpuut(3:end));
inpuut = [];
otherwise % not 2 white spaces
% Just print one character
fprintf('%s', inpuut(1))
inpuut(1) = [];
end
end
fprintf('%s\n', inpuut);
There is for example a big big score
for 2 hours
and there is need to see how many more before the end of
do output on the screen of the outer loop
but the values and there are many, such as 70 000
Question - how to remove a line break when printing to screen
not to receive 70 000 lines
and to see only the current display in one line?
Instead of using disp to display text to the screen, use fprintf, which requires you to enter line breaks manually.
Compare
>> disp('Hello, '), disp('World')
Hello,
World
with
>> fprintf('Hello, '), fprintf('World\n')
Hello, World
The \n at the end of 'World\n' signifies a line break (or newline as they're commonly called).
Try this function, which you can use in place of disp for a string argument. It displays to the command window, and remembers the message it has displayed. When you call it the next time, it first deletes the previous output from the command window (using ASCII backspace characters), then prints the new message.
In this way you only get to see the last message, and the command window doesn't fill up with old messages.
function teleprompt(s)
%TELEPROMPT prints to the command window, over-writing the last message
%
% TELEPROMPT(S)
% TELEPROMPT() % Terminate
%
% Input S is a string.
persistent lastMsg
if isempty(lastMsg)
lastMsg = '';
end
if nargin == 0
lastMsg = [];
fprintf('\n');
return
end
fprintf(repmat('\b', 1, numel(sprintf(lastMsg))));
fprintf(s);
lastMsg = s;