【问题标题】:Numerical data from simulink to arduino uno从 simulink 到 arduino uno 的数值数据
【发布时间】:2016-05-28 22:15:22
【问题描述】:

我想将数值数据从 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);
    }
}

【问题讨论】:

    标签: matlab arduino simulink arduino-uno


    【解决方案1】:

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

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

    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);
      }
    }
    

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

    谢谢大家!!

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2016-05-25
      • 2017-12-13
      • 1970-01-01
      • 2012-07-03
      相关资源
      最近更新 更多