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

14 views (last 30 days)
how to send output of matlab code to arduino for controlling purpose

Answers (1)

William Gaillard
William Gaillard on 28 Mar 2019
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.

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!