MATLAB实战:Arduino硬件交互项目方案
以下是一个使用MATLAB与Arduino进行硬件交互的项目方案,涵盖传感器数据采集和执行器控制。本方案使用MATLAB的Arduino硬件支持包,无需额外编写Arduino固件。
系统组成
-
硬件:
-
Arduino Uno
-
温度传感器(如LM35)
-
光敏电阻+10kΩ电阻
-
加速度传感器(MPU6050)
-
舵机(SG90)
-
LED+220Ω电阻
-
连接线若干
-
-
软件:
-
MATLAB R2019a+
-
Arduino Support Package(安装方法:MATLAB主页 → 附加功能 → 获取硬件支持包 → Arduino)
-
步骤1:硬件连接
组件 | Arduino引脚 |
---|---|
LM35 Vout | A0 |
光敏电阻分压 | A1 |
MPU6050 SDA | A4 |
MPU6050 SCL | A5 |
舵机信号线 | D9 |
LED阳极 | D13 |
步骤2:MATLAB代码实现
2.1 初始化Arduino连接
clear; clc;
a = arduino('COM3', 'Uno', 'Libraries', {'I2C', 'Servo'}); % 替换COM3为实际端口
% 初始化传感器
mpu = device(a, 'I2CAddress', 0x68, 'bus', 0); % MPU6050初始化
writeRegister(mpu, hex2dec('6B'), hex2dec('00'), 'int8'); % 唤醒传感器
% 初始化执行器
servo = servo(a, 'D9');
ledPin = 'D13';
2.2 实时数据采集与可视化
% 创建实时图形窗口
figure('Name', 'Sensor Data');
subplot(3,1,1); tempPlot = animatedline; title('Temperature (°C)');
subplot(3,1,2); lightPlot = animatedline; title('Light Intensity');
subplot(3,1,3); accelPlot = animatedline; title('Acceleration (g)');
% 数据采集参数
duration = 60; % 秒
ts = 0.1; % 采样间隔
t = 0;
% 主循环
while t < duration
% 读取温度传感器 (LM35)
tempVolt = readVoltage(a, 'A0');
tempC = tempVolt * 100; % LM35转换公式
% 读取光强 (0-5V)
lightVolt = readVoltage(a, 'A1');
% 读取加速度 (MPU6050)
accelX = readAcceleration(mpu);
% 更新实时图形
addpoints(tempPlot, t, tempC);
addpoints(lightPlot, t, lightVolt);
addpoints(accelPlot, t, accelX(1)); % 只显示X轴
% 动态控制执行器
if tempC > 30
writeDigitalPin(a, ledPin, 1); % 温度过高时亮LED
writePosition(servo, 0.8); % 舵机转到90%
else
writeDigitalPin(a, ledPin, 0);
writePosition(servo, 0.2); % 舵机回位
end
% 更新循环
t = t + ts;
pause(ts - 0.01); % 补偿计算时间
end
2.3 数据处理扩展(示例:移动平均滤波)
% 在循环中添加数据处理
persistent tempBuffer;
if isempty(tempBuffer)
tempBuffer = zeros(1,10);
end
tempBuffer = [tempBuffer(2:end), tempC];
filteredTemp = mean(tempBuffer);
关键技能点详解
-
硬件接口:
-
使用
arduino()
对象统一管理硬件连接 -
专用设备接口(
device()
用于I2C传感器) -
引脚模式自动配置(模拟输入/数字输出/PWM)
-
-
串口通信:
-
底层通过串口协议通信(波特率自动协商)
-
支持同步/异步读写操作
-
-
实时数据处理:
-
animatedline
实现流式数据可视化 -
循环内集成数据处理算法(如滤波)
-
执行器闭环控制(基于传感器反馈)
-
故障排除
-
端口识别问题:
-
运行
arduinoio.IDEReset
重置IDE关联 -
设备管理器中检查驱动状态
-
-
I2C通信失败:
-
确认传感器地址(
0x68
或0x69
) -
检查接线是否松动(SDA/SCL交叉连接)
-
-
实时性不足:
-
减少采样间隔(最小可达0.01秒)
-
关闭实时绘图提升性能
-