---
# System prepended metadata

title: 自控實驗四補充教學

---

# 實驗四繪圖教學
## 擷取 Arduino 數據至 Matlab
於實驗中開啟Serial monitor，可見 Arduino 會傳出兩組數據分別為 `Setpoint` 以及 `Encoder Counter`， 將其複製至Excel

![image](https://hackmd.io/_uploads/rkrrMm3rT.png =300x)

貼上至Excel後使用文字匯入精靈將字串分離

![image](https://hackmd.io/_uploads/BkzbQmnHT.png =300x)

![image](https://hackmd.io/_uploads/Sy5P7mnHT.png =300x)

分離後即可將C、D兩欄匯入至Matlab中。

## Matlab 繪製響應圖

開啟 [Matlab Script](https://hackmd.io/@guanlunlu/AC_matlab_script)，先執行第一個Section
```matlab!
%%
% Run this section first, then paste arduino data from excel
exp_data = []

% Copy data from Excel to exp_data
```
雙擊右側Workspace窗口`exp_data`，將Excel數據貼上，即完成數據匯入

![image](https://hackmd.io/_uploads/rJpi4m3r6.png =300x)

![image](https://hackmd.io/_uploads/S1VBHXnB6.png =200x)

執行第二個Section，為數據加上timestamp
```matlab!
%%
% add timestamp data to matlab array (100 Hz)
[datalength, col] = size(exp_data);
ts = linspace(0, 0.01*datalength, datalength);

exp_data = [transpose(ts), exp_data]

% exp_data format is performed as:
% exp_data = [time(sec), setpoint, encoder_counter(resp.)]
```

## 調整Simulink的Sampling Rate 以及 Step input的起始時間
* 將Simulink中的sampling rate調為0.01 (Arduino的Sampling rate) (Sinewave 同理)
* 將Step的起始時間調整至與實驗數據相同
![image](https://hackmd.io/_uploads/BksOUmhBp.png)

## 執行Matlab script 最後一個section 即可完成繪圖
```matlab!
%%
% plot setpoint
plot(exp_data(:,1), exp_data(:,2), 'LineWidth',1)
hold on

% plot motor response
plot(exp_data(:,1), exp_data(:,3), 'LineWidth',1)
hold on

% plot simulink response
plot(out.simout.Time, out.simout.Data(:,2), 'LineWidth',1)
legend("setpoint", "motor response", "simulink response")
hold off

xlabel("time (sec)")
ylabel("position (count)")

% set x range of plot
xlim([-1, 6])
grid on
```


![image](https://hackmd.io/_uploads/B1gizLr8a.png)
