Why Combine Arduino Microcontrollers with MATLAB & Simulink?
The synergy between Arduino open-source microcontrollers and MATLAB/Simulink provides an unparalleled ecosystem for rapid prototyping, Hardware-in-the-Loop (HIL) testing, and production-grade embedded deployment. Using the official MATLAB Support Package for Arduino Hardware, engineers can stream real-time analog and digital sensor telemetry directly into MATLAB's analytical workspace, visualize high-frequency signals with App Designer GUIs, and execute closed-loop digital signal processing algorithms without low-level C register manipulation.
For production systems, Simulink Embedded Coder auto-generates optimized, standalone ANSI C/C++ code that flashes directly to ATmega328, SAM3X8E, and ESP32 targets, empowering students and researchers to implement state-space controllers, Kalman filters, and IoT edge nodes with zero manual coding errors.
Core Toolboxes Used
- MATLAB Support Package for Arduino
- Simulink & Embedded Coder
- Control System & System Identification
- Instrument Control & Serial Toolbox
- ThingSpeak & Industrial IoT Cloud
- Sensor Fusion and Tracking Toolbox
1. Arduino Uno IR Sensor Project & Remote Control Decoder
BeginnerDecode NEC infrared remote control pulse-width modulated (PWM) signals using an IR receiver diode connected to an Arduino microcontroller. Digital pulses captured by Arduino GPIO pins are processed in MATLAB real-time GUI for automated lighting, robotic command execution, and home automation.
% Connect Arduino and configure digital pin
a = arduino('COM3', 'Uno');
configurePin(a, 'D2', 'DigitalInput');
configurePin(a, 'D8', 'DigitalOutput');
disp('Listening for IR Remote Signals...');
while true
if readDigitalPin(a, 'D2') == 0 % Active Low IR pulse detected
writeDigitalPin(a, 'D8', 1); % Toggle Status LED
disp('IR Signal Decoded: Command Executed');
pause(0.2);
writeDigitalPin(a, 'D8', 0);
end
end
2. ATmega328 Arduino Uno Board Hardware Integration & Serial Telemetry
BeginnerComprehensive hardware interfacing architecture covering Arduino Uno ATmega328P architecture, high-frequency 10-bit ADC sampling, digital PWM duty cycle modulation, and high-speed UART serial telemetry streaming into MATLAB data arrays.
% Initialize Arduino & Real-Time Live Plot
a = arduino('COM3', 'Uno');
figure('Name', 'Real-Time ADC Telemetry', 'Color', 'w');
hLine = plot(nan, nan, 'b-', 'LineWidth', 1.8);
grid on; xlabel('Sample'); ylabel('Voltage (V)');
ylim([0 5.2]);
voltageData = zeros(1, 200);
for k = 1:200
voltageData(k) = readVoltage(a, 'A0');
set(hLine, 'XData', 1:k, 'YData', voltageData(1:k));
drawnow limitrate;
end
3. Low-Cost Real Color Picker Based on Arduino & TCS3414 / TCS34725 CS
IntermediateBuild an accurate color measurement spectrophotometer using an I2C optical color sensor (TCS3414CS/TCS34725) integrated with Arduino and MATLAB. Converts raw Red, Green, Blue, and Clear channel photodetection into CIE 1931 XYZ and CIE L*a*b* color coordinates with white balance calibration.
% Connect Arduino I2C Color Sensor
a = arduino('COM3', 'Uno', 'Libraries', 'I2C');
colorSensor = i2cdev(a, '0x29'); % TCS34725 Address
% Enable Sensor & Read RGB Channels
write(colorSensor, hex2dec('80'), hex2dec('03')); % Power ON
data = read(colorSensor, 8, 'uint8');
clear = double(bitshift(data(2),8) + data(1));
red = double(bitshift(data(4),8) + data(3)) / clear;
green = double(bitshift(data(6),8) + data(5)) / clear;
blue = double(bitshift(data(8),8) + data(7)) / clear;
rgb_normalized = min(max([red, green, blue], 0), 1);
lab_val = rgb2lab(rgb_normalized);
fprintf('Normalized RGB: [%.2f, %.2f, %.2f] | Lab: [%.1f, %.1f, %.1f]\n', ...
rgb_normalized, lab_val);
4. Low-Cost COTS Rendezvous Depth Sensor for Satellites
AdvancedAutonomous spacecraft proximity operations and orbital rendezvous docking sensor suite using commercial-off-the-shelf (COTS) Time-of-Flight LIDAR depth sensors, ARM embedded microcontrollers, and MATLAB 3D point cloud registration algorithms.
% 3D Point Cloud Registration for Spacecraft Pose Estimation
fixedCloud = pcread('cubesat_cad_model.ply');
movingCloud = pointCloud(rand(500, 3)*0.5); % Streamed from ToF Sensor
% Iterative Closest Point (ICP) 6-DOF Alignment
[tform, regCloud, rmse] = pcregistericp(movingCloud, fixedCloud, ...
'Metric', 'planeToPlane', 'MaxIterations', 50);
fprintf('Docking Pose Estimation RMSE: %.4f m\n', rmse);
disp('Translation Vector (X, Y, Z):');
disp(tform.Translation);
5. Assistive Mobile Robotics for Healthcare & Medicine Delivery
AdvancedDesign an intelligent autonomous mobile robot (AMR) for contactless medication delivery in hospitals. Features ultrasonic obstacle avoidance array, differential drive Arduino locomotion, A* global path planning, and ROS/MATLAB cloud logging for patient delivery verification.
% Path Planning & Pure Pursuit Navigation
map = binaryOccupancyMap(20, 20, 10);
setOccupancy(map, [5 5; 5 6; 5 7; 10 12], 1);
planner = plannerAStar(map);
startPose = [2, 2]; goalPose = [15, 18];
path = plan(planner, startPose, goalPose);
controller = controllerPurePursuit;
controller.Waypoints = path;
controller.DesiredLinearVelocity = 0.4; % m/s
controller.LookaheadDistance = 0.5;
disp('Trajectory Computed: Ready for Arduino Motion Execution');
6. Multiple Input Digital Stethoscope Apparatus with Arduino
IntermediateMulti-channel phonocardiogram (PCG) acoustic acquisition platform capturing body acoustic vibrations across 5 anatomical chest diaphragms. Digitized via Arduino high-speed ADC sampling and filtered in MATLAB for heart murmur and S1/S2 heart sound detection.
% 5-Channel Digital Stethoscope Signal Filtering
Fs = 2000; % 2 kHz ADC Sampling Rate
bpFilt = designfilt('bandpassiir', 'FilterOrder', 4, ...
'HalfPowerFrequency1', 20, 'HalfPowerFrequency2', 250, ...
'SampleRate', Fs);
% Zero-phase filtering of PCG acoustic stream
raw_pcg = readVoltage(a, 'A1'); % Live Stream from Arduino
clean_pcg = filtfilt(bpFilt, raw_pcg);
[pks, locs] = findpeaks(clean_pcg, 'MinPeakDistance', Fs*0.4);
fprintf('Detected Heart Rate: %.1f BPM\n', length(pks)*60 / (length(raw_pcg)/Fs));
7. Multi-Bot Easy Control Hierarchy Architecture & Swarm Coordination
IntermediateHierarchical multi-robot control framework coordinating heterogeneous mobile robots (differential drive rovers, holonomic ground bots, and omnidirectional platforms) via centralized MATLAB supervisory intelligence and distributed Arduino edge motor nodes.
% Leader-Follower Swarm Formation Control
numBots = 3;
leaderPose = [5.0, 5.0, pi/4];
offsetAngles = [-pi/3, pi/3]; distance = 1.0;
for i = 1:2
followerTarget(i, 1) = leaderPose(1) - distance*cos(leaderPose(3) + offsetAngles(i));
followerTarget(i, 2) = leaderPose(2) - distance*sin(leaderPose(3) + offsetAngles(i));
fprintf('Bot %d Target: (%.2f, %.2f)\n', i+1, followerTarget(i, 1), followerTarget(i, 2));
end
8. IoT Safety System for Underground Coal Mines with Real-Time Analytics
AdvancedWireless sensor network (WSN) deployed in underground mines for toxic gas detection (Methane CH4, Carbon Monoxide CO, and Hydrogen Sulfide H2S), temperature, humidity, and RSSI-based miner localization using Arduino wireless nodes and MATLAB cloud analytics.
% Cloud Gas Analytics & Threshold Detection
channelID = 123456; readKey = 'THINGSPEAK_READ_KEY';
[data, timeStamps] = thingSpeakRead(channelID, 'Fields', [1, 2, 3], ...
'NumPoints', 100, 'ReadKey', readKey);
ch4_ppm = data(:, 1); co_ppm = data(:, 2); temp_c = data(:, 3);
% Anomaly Detection & Early Hazard Alarm
hazardIdx = find(ch4_ppm > 1000 | co_ppm > 50);
if ~isempty(hazardIdx)
warning('EMERGENCY HAZARD: Gas Limit Exceeded in Zone %d', hazardIdx(end));
end
9. FPGA Custom Accelerators with MATLAB Overlays & Microcontroller Co-Design
AdvancedHigh-Level Synthesis (HLS) and Just-In-Time Assembly of custom hardware coprocessor IP cores generated directly from high-level MATLAB algorithms. Couples an Arduino/ARM supervisor microcontroller with an FPGA accelerator for real-time matrix factorization and deep learning inference.
% Fixed-Point HDL Code Generation for Matrix Multiplication
hdlCfg = coder.config('hdl');
hdlCfg.TargetLanguage = 'VHDL';
hdlCfg.GenerateHDLTestBench = true;
% Define Fixed-Point Types: signed 16-bit word, 8-bit fraction
T = numerictype(1, 16, 8);
F = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap');
A_fi = fi(randn(4,4), T, F);
B_fi = fi(randn(4,4), T, F);
codegen -config hdlCfg matrix_mult_hdl -args {A_fi, B_fi};
10. Battery Electric Vehicle (BEV) Powertrain Multi-Objective Optimization
AdvancedMulti-objective genetic algorithm (NSGA-II) optimizing battery pack energy capacity, motor torque-speed mapping, and gear reduction ratios for single and dual-motor electric vehicles. Integrates Arduino as an embedded Battery Management System (BMS) Hardware-in-the-Loop controller.
% NSGA-II Multi-Objective Powertrain Optimization
opts = optimoptions('gamultiobj', 'PopulationSize', 50, ...
'MaxGenerations', 100, 'PlotFcn', @gaplotpareto);
nvars = 3; % [GearRatio, BatteryPackCells, MotorPeakTorque]
lb = [4.0, 80, 150]; ub = [12.0, 140, 450];
[xOpt, fval] = gamultiobj(@bev_objective_fun, nvars, [], [], [], [], lb, ub, opts);
disp('Optimal Pareto Solutions (Energy vs Accel):');
disp(fval(1:5, :));
11. Real-Time PID DC Motor Speed & Position Control with Optical Encoder
IntermediateDesign, tune, and implement a closed-loop digital PID controller for a geared DC motor driven by an L298N H-Bridge with optical quadrature encoder feedback. Evaluates step responses, anti-windup integration, and load disturbance rejection in real time.
% Experimental DC Motor PID Speed Loop
a = arduino('COM3', 'Uno', 'Libraries', 'RotaryEncoder');
enc = rotaryEncoder(a, 'D2', 'D3', 360); % 360 CPR Encoder
Kp = 1.85; Ki = 0.65; Kd = 0.08;
target_rpm = 150; integral_err = 0; prev_err = 0;
for k = 1:300
current_pos = readCount(enc);
measured_rpm = (current_pos / 360) * 60 / 0.02; % 20ms delta
resetCount(enc);
error = target_rpm - measured_rpm;
integral_err = integral_err + error * 0.02;
derivative = (error - prev_err) / 0.02;
pwm_cmd = min(max((Kp*error + Ki*integral_err + Kd*derivative)/255, 0), 1);
writePWMDutyCycle(a, 'D9', pwm_cmd);
prev_err = error;
pause(0.02);
end
12. Arduino Ultrasonic Radar & 2D Polar Obstacle Mapping System
BeginnerDevelop a 180-degree ultrasonic sweep radar using an HC-SR04 ultrasonic distance sensor mounted on an SG90 servo motor. Sweeps continuously and renders an interactive 2D polar radar display in MATLAB with real-time target distance and angle coordinates.
% 180-Degree Servo Ultrasonic Radar Sweep
a = arduino('COM3', 'Uno', 'Libraries', {'Servo', 'Ultrasonic'});
s = servo(a, 'D9');
u = ultrasonic(a, 'D12', 'D13');
figure('Name', 'Ultrasonic Radar Screen', 'Color', 'k');
angles = linspace(0, pi, 90);
ranges = zeros(1, 90);
for i = 1:90
writePosition(s, (i-1)/89); % Sweep 0 to 180 deg
ranges(i) = readDistance(u) * 100; % Distance in cm
polarplot(angles(1:i), ranges(1:i), 'g-o', 'LineWidth', 1.5);
rlim([0 200]); thetalim([0 180]); drawnow;
end
13. IoT Smart Weather & Environmental Station with ThingSpeak Cloud
IntermediateDeploy a connected micro-climate weather station measuring ambient temperature, relative humidity (DHT22), barometric pressure, altitude (BMP280), and air quality (MQ135). Streams sensor streams over WiFi to MathWorks ThingSpeak IoT cloud for automated forecasting and dew-point modeling.
% Read Sensors & Stream to ThingSpeak IoT Cloud
channelID = 987654; writeKey = 'THINGSPEAK_WRITE_API_KEY';
temp_C = 26.4; humidity_pct = 58.2; pressure_hPa = 1013.25;
dew_point = temp_C - ((100 - humidity_pct)/5);
thingSpeakWrite(channelID, [temp_C, humidity_pct, pressure_hPa, dew_point], ...
'Fields', [1, 2, 3, 4], 'WriteKey', writeKey);
disp('Weather Telemetry Successfully Pushed to ThingSpeak');
14. Autonomous 2-Wheel Self-Balancing Robot with MPU6050 IMU & Kalman Filter
AdvancedModel and construct an inverted pendulum 2-wheel self-balancing robotic rover (Segway-type). Fuses accelerometer and gyroscope rate measurements from an MPU6050 6-DOF IMU using an Extended Kalman Filter (EKF), executing a state-feedback LQR controller for upright stability.
% 6-DOF IMU Complementary & Kalman Filter Fusion
dt = 0.01; alpha = 0.98; pitch = 0;
a = arduino('COM3', 'Uno', 'Libraries', 'I2C');
imu = mpu6050(a);
for k = 1:500
[accel, gyro] = read(imu);
accel_pitch = atan2d(accel(2), sqrt(accel(1)^2 + accel(3)^2));
gyro_rate = gyro(1); % deg/s
% Complementary Filter Fusion
pitch = alpha * (pitch + gyro_rate * dt) + (1 - alpha) * accel_pitch;
% LQR Actuation Effort Computation
u_pwm = - (14.2 * (pitch*pi/180) + 2.8 * (gyro_rate*pi/180));
end
15. Smart Dual-Axis Solar Tracker with LDR Sensors & Servo Actuation
BeginnerMaximize solar photovoltaic (PV) power harvesting efficiency using an intelligent dual-axis (azimuth and elevation) sun tracker. Evaluates differential light intensity from four Light Dependent Resistors (LDRs) and commands dual high-torque servo motors to maintain normal incidence sunlight rays.
% Dual-Axis Sun Tracking Algorithm
a = arduino('COM3', 'Uno', 'Libraries', 'Servo');
servoAzimuth = servo(a, 'D9');
servoElevation = servo(a, 'D10');
% Read 4 LDR Light Intensities
topL = readVoltage(a, 'A0'); topR = readVoltage(a, 'A1');
botL = readVoltage(a, 'A2'); botR = readVoltage(a, 'A3');
avgTop = (topL + topR)/2; avgBot = (botL + botR)/2;
avgLeft = (topL + botL)/2; avgRight = (topR + botR)/2;
if abs(avgTop - avgBot) > 0.1
disp('Adjusting Elevation Angle...');
end
16. MAX30102 Heart Rate & SpO2 Pulse Oximeter Health Telemetry System
IntermediateNon-invasive real-time photoplethysmography (PPG) biomedical health monitoring using a MAX30102 optical sensor connected via I2C to Arduino. Processes dual Red and Infrared light absorption curves in MATLAB to compute instantaneous pulse rate (BPM) and blood oxygen saturation (SpO2 %).
% Dual-Wavelength PPG Blood Oxygen Saturation Estimation
fs = 100; % 100 Hz Sampling
red_ac = detrend(red_raw); ir_ac = detrend(ir_raw);
ratio_of_ratios = (std(red_ac) / mean(red_raw)) / (std(ir_ac) / mean(ir_raw));
% Empirical Empirical Calibration Curve
SpO2 = 110 - 25 * ratio_of_ratios;
[pks, locs] = findpeaks(ir_ac, 'MinPeakDistance', fs*0.5);
BPM = length(pks) * 60 / (length(ir_ac)/fs);
fprintf('Vital Signs: Heart Rate = %.1f BPM | SpO2 = %.1f%%\n', BPM, SpO2);
17. Gesture-Controlled 4-DOF Robotic Arm with Flex Sensors & Kinematics
IntermediateHuman-machine interface (HMI) smart glove instrumented with flex bend sensors and an MPU6050 accelerometer to mirror human hand gestures onto a 4-DOF articulated robotic arm manipulator in real time. Forward and inverse kinematics are computed in MATLAB.
% 4-DOF Robotic Arm Inverse Kinematics Mapping
robot = loadrobot('kinovaGen3', 'DataFormat', 'row');
ik = inverseKinematics('RigidBodyTree', robot);
% Read Gesture Glove Flex Sensor & Map to Cartesian Coordinates
flex_val = readVoltage(a, 'A0'); % Finger Flex Voltage
targetPos = [0.4, 0.2, 0.1 + (flex_val/5)*0.3];
targetTform = trvec2tform(targetPos);
[configSol, solInfo] = ik('EndEffector_Link', targetTform, ones(1,6), robot.homeConfiguration);
disp('Joint Servo Angles Computed Successfully');
18. Precision Temperature Chamber PID Control Using Arduino & Peltier Element
BeginnerPrecision thermal regulation chamber utilizing a thermoelectric Peltier cooler/heater driven by a MOSFET PWM stage with high-precision DS18B20 digital 1-Wire temperature sensor feedback. Closed-loop PID control programmed in MATLAB keeps chamber temperatures stable within ±0.1°C.
% Thermal Chamber Closed-Loop PID Temperature Control
a = arduino('COM3', 'Uno');
setpoint_C = 37.0; % Target Incubation Temp (37°C)
Kp = 0.15; Ki = 0.02; integral_term = 0;
for t = 1:600
volt = readVoltage(a, 'A0'); % LM35: 10 mV / °C
current_temp = volt * 100;
error = setpoint_C - current_temp;
integral_term = min(max(integral_term + error*0.5, -10), 10);
pwm_duty = min(max(Kp*error + Ki*integral_term, 0), 1);
writePWMDutyCycle(a, 'D9', pwm_duty);
pause(0.5);
end
📚 MATLAB Blogs
Physics-Informed Neural Networks (PINNs) for Microgrid Dynamics and Power Flow in MATLAB
LatestModern microgrids operate with low physical inertia, rapid inverter switching dynamics, and intermittent...
Learn MoreROS 2 and MATLAB Co-Simulation for Autonomous Mobile Robot Path Tracking Using NMPC
LatestTracking complex trajectories with non-holonomic mobile robots requires handling physical constraints such as actuato...
Learn MoreFrequently Asked Questions — Arduino & MATLAB Projects
Clear, expert answers regarding hardware compatibility, real-time serial streaming, Simulink code generation, and HIL simulation.
- In the MATLAB toolstrip, navigate to Home > Add-Ons > Get Hardware Support Packages.
- Search for
MATLAB Support Package for Arduino Hardwareand click Install. - Connect your Arduino board to your computer via USB, open Windows Device Manager (or Terminal on macOS/Linux) to identify the COM port (e.g.
COM3). - In MATLAB, test the connection by creating an object:
a = arduino('COM3', 'Uno', 'Libraries', {'I2C', 'SPI', 'Servo', 'Ultrasonic'}).
Simulink Standalone Deployment (Embedded Coder): Your Simulink block diagram is cross-compiled into highly optimized standalone C/C++ binary code and flashed directly into the microcontroller’s flash memory. Once programmed, the Arduino operates completely independently in the field without any PC connection.
- Set the UART baud rate to 115200 bps or 250000 bps in both MATLAB (
serialport) and your Arduino sketch. - Transmit binary byte streams (e.g.
Serial.write()withuint8orfloat32) instead of slow ASCII string formatting withSerial.println(). - Use asynchronous callbacks in MATLAB (
configureCallback(s, "byte", N, @callbackFun)) to read data immediately as packets arrive. - Ensure non-blocking circular buffers are used so the serial hardware buffer never overflows.
- 8-bit AVR: Arduino Uno, Nano, Mega 2560, Leonardo, Micro, Pro Mini.
- 32-bit ARM Cortex: Arduino Due (SAM3X8E), Arduino Zero (SAMD21), Nano 33 BLE / 33 IoT, MKR series.
- WiFi & Bluetooth IoT Modules: ESP32 and ESP8266 boards via TCP/IP, UDP, MQTT, and the ThingSpeak Support Package.
- Controller on Hardware, Plant in Simulation: The physical Arduino runs the embedded control algorithm (e.g. PID or Kalman filter), sending PWM signals into MATLAB, while Simulink simulates the virtual plant (e.g. DC motor, quadrotor, or power converter) and feeds simulated sensor states back to the Arduino.
- Simulink External Mode: Code runs directly on the microcontroller while Simulink provides live bidirectional parameter tuning and Scope monitoring in real time.
- 100% custom, original, and verified MATLAB scripts (
.m) and Simulink models (.slx). - Complete wiring diagrams, circuit schematics, and component datasheets.
- One-on-one debugging sessions for serial communication, timer interrupts, and I2C/SPI sensors.
- Comprehensive technical reports, algorithm explanations, and PowerPoint presentations ready for university submission.