简体   繁体   English

从Matlab到arduino顺序读取int

[英]Reading in an int serially from Matlab to arduino

I'm trying to read in an integer value between 1 and 999 on arduino, the number is sent from matlab serially. 我正在尝试在arduino上读取1到999之间的整数值,该数字是从Matlab串行发送的。 My code on arduino is: 我在arduino上的代码是:

   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: 我在matlab上发送的代码如下:

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? 我要发送的号码是408。有什么想法吗?

I found that using Serial.parseInt() reads in everything that you need. 我发现使用Serial.parseInt()可以读取所需的所有内容。 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. 我还通过使用Serial.parseFloat()最终读取了一个浮点数,从本质上来说,直到它到达一个非int或非浮点字符为止,它一直在读取。

On matlab I ended up just using fprintf(s1, '%d\\n', numSec); 在matlab上,我最终仅使用fprintf(s1,'%d \\ n',numSec);

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. Serial.read只读取一个字节,可以在0到255之间。您需要以3个ascii字符( 52 48 56发送数字,并使用do...while循环读取它们,然后将它们解析为数字。 The details of how you do that will depend on your exact application (ie, are you always expecting a 3 digit number, or are you expecting a range of numbers). 具体操作方式将取决于您的确切应用(即,您始终希望输入3位数字,还是希望输入数字范围)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM