从simulink到arduino uno的数值数据



我想将数值数据从 Simulink 发送到 Arduino Uno。

因为我不知道如何在 Simulink 中让它工作,所以我只是尝试使用 Matlab。

此代码以char的形式发送数值数据。所以一次一个角色到Arduino。之后,我必须连接字符来构造数值,然后将其交给Arduino进行处理。然后用同样的方式将其发送回 Matlab。

我想知道是否有可能将数值数据作为数字发送到Arduino,并将其作为数值数据发送回Matlab/simulink。

这是我在 Matlab 中使用的代码:

close all; clear all ;  clc;
delete (instrfind({'Port'},{'COM5'}))
s = serial('COM5');
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',4800);
set(s,'Parity','none');
fopen(s)
while (1)
    if  (s.BytesAvailable)
        readData=fscanf(s)
    else
        fprintf(s,'arduino');
    end
end
fclose(s)

这是我在Arduino中使用的代码:

int sensorPin = A0;  
int sensorValue = 0; 
char incomingData;
void setup() {
  Serial.begin(4800);
}
void loop() {
    if (Serial.available() > 0) 
    {
      incomingData = Serial.read(); //read incoming data
      Serial.println(incomingData);
      delay(100);
    }
    else {
      sensorValue = analogRead(sensorPin);
      Serial.println(sensorValue);    
      delay(100);
    }
}

我已经问过上面的问题。现在我找到了答案,所以我想和你分享。

首先,您必须关闭与串行端口的所有通信,并初始化通信的值。你这样做。

close all ;  clc;
delete (instrfind({'Port'},{'COM3'}))
s = serial('COM3');
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',9600);
set(s,'Parity','none');

雷马克 :并非总是有"COM3"端口,因此您必须在Arduino中查看您正在使用哪个端口。此外,您还必须在matlab和Arduino中制作"BaudRate"的精确值。

其次,您发送浮点数,然后以这种方式读取它:

YourValue = 123.456; % This is just an exemple
while (1)
    fprintf(s,'%f',YourValue);  % sendig the value to the Arduino
    readData=fscanf(s,'%f')     % receiving the value from the Arduino and printing it
end
fclose(s)

现在,对于Arduino部分,它很简单。代码显示如下:

int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float incomingData;
void setup() {
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()) 
  {
    incomingData = Serial.parseFloat(); //read incoming data
    delay(100);
  }
  else 
  {
    Serial.println(incomingData);
    delay(100);
  }
}

Remarque :当我将许多值从 matlab 发送到 Arduino 时,我会将它们发送回 matlab。我的第一个值总是以这种方式 [] 或这种方式打印 0。我不知道问题出在哪里。

谢谢大家!!

最新更新