How to Control Arduino with MATLAB
How can I control digital inputs on an Arduino using MATLAB?
Here is a hello world~
of serial communication between MATLAB and Arduino. This communication will be utilized for switching the states of digital outputs in Arduino UNO. This is a pretty generic method and will work for other micro controllers of the same family. Arduino UNO has only one port for serial communication.
What the heck is a Serial Port?
A serial port is a data communication channel where 1 bit at a time is transferred.
Why do we need Serial Ports?
Serial port handles communication between connected devices . Today nearly every IoT works due to serial ports.
How does it work?
Sending character S via Serial Port
In serial communication the receiver sends a character (say ‘s’) by converting the character to it’s binary code ( 01110011 ). The converted character is transmitted via Serial Port from transmitter to receiver via fluctuations in the voltage.
Getting Started
Connect Arduino UNO to the laptop.
Write/paste the following code.
Arduino
Methods
Serial.begin(9600)
It opens serial port with 9600 bauds (data transfer rate).
Serial.available
Check if data is received from computer.
digitalWrite(5, HIGH);
Turn on pin 5 on Arduino UNO.
Arduino Program
int incomingByte = 0;
void setup() {
Serial.begin(9600);
for (int i=5; i<=12; i++){
pinMode(i, OUTPUT);
}
}
void loop() {
if (Serial.available() > 0){
incomingByte = Serial.read();
Serial.println(incomingByte);
switch (incomingByte){
case 0:
digitalWrite(5, LOW);
break;
case 1:
digitalWrite(5, HIGH);
break;
///////////////////////
case 2:
digitalWrite(6, LOW);
break;
case 3:
digitalWrite(6, HIGH);
break;
///////////////////////
case 4:
digitalWrite(7, LOW);
break;
case 5:
digitalWrite(7, HIGH);
break;
///////////////////////
case 6:
digitalWrite(8, LOW);
break;
case 7:
digitalWrite(8, HIGH);
break;
///////////////////////
case 8:
digitalWrite(9, LOW);
break;
case 9:
digitalWrite(9, HIGH);
break;
///////////////////////
case 10:
digitalWrite(10, LOW);
break;
case 11:
digitalWrite(10, HIGH);
break;
///////////////////////
case 12:
digitalWrite(11, LOW);
break;
case 13:
digitalWrite(11, HIGH);
break;
///////////////////////
case 14:
digitalWrite(12, LOW);
break;
case 15:
digitalWrite(12, HIGH);
break;
///////////////////////
}
}
}
- Compile & Upload.
MATLAB Side
- Open MATLAB and copy this program
%MATLAB Code for Serial Communication with Arduinofclose(instrfind);
delete(instrfind);
x=serial('COM5','BaudRate', 9600);
fopen(x)
go = true;while go
a = input('Enter 1 to turn ON LED & 0 to turn OFF or 2 to exit, press: ');
fwrite(x, a, 'char');
if (a == 2)
go=false;
end
end
fclose(x)fclose(x)