How To Send Data From MATLAB To Your Arduino

by Miguel on July 4, 2011

in Arduino

In my previous post I shows you how to send data from the Arduino to a MATLAB script, in this post I will show you how to do the opposite.

What Will The Program Do?

This program will simply turn the Arduino’s built in LED in pin 13 on or off when you press 1 or 2 respectively, pressing 0 will exit the MATLAB program and end communication with the Arduino.

Arduino Serial Communication Code

int ledPin=13;
int matlabData;

void setup() 
{
  pinMode(ledPin,OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
   
   if(Serial.available()>0) // if there is data to read
   {
    matlabData=Serial.read(); // read data
    if(matlabData==1)
      digitalWrite(ledPin,HIGH); // turn light on
    else if(matlabData==2)
      digitalWrite(ledPin,LOW); // turn light off
  }
}

MATLAB Serial Communication Code

clear all
clc

answer=1; % this is where we'll store the user's answer
arduino=serial('COM4','BaudRate',9600); % create serial communication object on port COM4

fopen(arduino); % initiate arduino communication

while answer
    fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
    answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

Previous post:

Next post: