Question

I'm trying to read in an integer value between 1 and 999 on arduino, the number is sent from matlab serially. My code on arduino is:

   while (Serial.available() <= 0) {
     Serial.println('A', BYTE);   // send a capital A
     delay(300);
   }
   dec = Serial.read();
   Serial.print("I recieved: ");
   Serial.println(dec);

My Code on matlab for sending is as follows:

numSec = 408;

s1 = serial('COM3');    % define serial port
s1.BaudRate=9600;               % define baud rate
set(s1, 'terminator', 'LF');   
% define the terminator for println
fopen(s1);

try                             % use try catch to ensure fclose
                                % signal the arduino to start collection
w=fscanf(s1,'%s');              % must define the input % d or %s, etc.
if (w=='A')
    display(['Collecting data']);
    %fprintf(s1,'%2d\n',numSec);     % establishContact
    fwrite(s1, numSec);
end

disp(fscanf(s1,'%s'));

Results were:

 Collecting data 
 I recieved:255

The number I'm trying to send is 408. Any ideas?

Was it helpful?

Solution

I found that using Serial.parseInt() reads in everything that you need. I also ended up reading in a float by using Serial.parseFloat() Esentially what it does is reads until it reaches a non int or non float character.

On matlab I ended up just using fprintf(s1, '%d\n', numSec);

OTHER TIPS

Serial.read only reads a single byte, which can be between 0 and 255. You need to send your number as 3 ascii characters, 52 48 56, read them in with a do...while loop, then parse them into numbers. The details of how you do that will depend on your exact application (i.e., are you always expecting a 3 digit number, or are you expecting a range of numbers).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top