how to send data from matlab to arduino and blink a led depending on the data received from matlab ?

3 次查看(过去 30 天)
how to send output of matlab code to arduino for controlling purpose

回答(1 个)

William Gaillard
William Gaillard 2019-3-28
In Matlab
fclose(instrfind);
clc
clear all
s=serial('COM4','BAUDRATE',9600); %to create the serial port in MATLAB
fopen(s); %open the serial port
A=[1 4 7]; % A is an 1x3 array of class 'double' containing 24 bytes (8 bytes per element)
fwrite(s,A); % writes the binary data A to the device connected to the serial port object, s.
fclose(instrfind);
In Arduino
byte b[2]; // three byte array
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED pin on arduino
}
void loop() {
if (Serial.available() > 0)
{
for (int i=0; i<3; i++){
b[i] = Serial.read();
}
if (b[0] == 1) { //switch on the led
digitalWrite(13, HIGH);
}
if (b[0] == 2) { //switch off the led
digitalWrite(13, LOW);
}
}
}
Load the Arduino code then follow the instrucitons on this link (https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection/) to prevent Arduino from resetting. For me I have an Uno and I use a 100 nF capacitor between reset and ground. The capacitor should be connected after you get the code on the Arduino. Note: to reprogram your Arduino you will need to disconnect the capacitor.
Once the Arduino code is uploaded and the capactior connected, then run the Matlab code. If the first value in the array 'A' in Matlab is a 1 then the LED will turn on. If the not then it will turn off.

类别

Help CenterFile Exchange 中查找有关 MATLAB Support Package for Arduino Hardware 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by