Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a82084a8f6 | ||
|
|
e39d9e487e | ||
|
|
bf389cd012 | ||
|
|
11df24f592 | ||
|
|
6c38a1db37 | ||
|
|
9607a26f8f | ||
|
|
1d93605cc3 | ||
|
|
be4cf10d7e |
+5
-1
@@ -4,8 +4,12 @@ __pycache__
|
|||||||
*.csv
|
*.csv
|
||||||
*.typ
|
*.typ
|
||||||
*.pdf
|
*.pdf
|
||||||
|
*.py
|
||||||
|
*.png
|
||||||
|
*.csv
|
||||||
|
scripts
|
||||||
|
|
||||||
# Vélarsértækar skrár sem PlatformIO býr til sjálft
|
# Skrár sem PlatformIO býr til sjálft
|
||||||
.vscode/c_cpp_properties.json
|
.vscode/c_cpp_properties.json
|
||||||
.vscode/launch.json
|
.vscode/launch.json
|
||||||
compile_commands.json
|
compile_commands.json
|
||||||
|
|||||||
@@ -10,14 +10,12 @@ skinparam state {
|
|||||||
[*] --> Initialization
|
[*] --> Initialization
|
||||||
|
|
||||||
state Initialization
|
state Initialization
|
||||||
Initialization : Entry / Stop motor
|
Initialization : Entry / Stop motor
|
||||||
Initialization : Do / Initialize internal parameters
|
Initialization : Entry / Initialize internal parameters
|
||||||
Initialization : Do / Reset speed measurement
|
Initialization : Entry / Reset speed measurement
|
||||||
Initialization : Do / Wait 2 seconds
|
Initialization : Do / Wait 2 seconds
|
||||||
Initialization : Exit / Send Boot-up message
|
Initialization : Exit / Send Boot-up message
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
state Operational
|
state Operational
|
||||||
Operational : Entry / LED on
|
Operational : Entry / LED on
|
||||||
Operational : Do / Run speed controller
|
Operational : Do / Run speed controller
|
||||||
@@ -28,9 +26,7 @@ state Stopped
|
|||||||
Stopped : Do / Blink LED at 2 Hz
|
Stopped : Do / Blink LED at 2 Hz
|
||||||
Stopped : Exit / LED off
|
Stopped : Exit / LED off
|
||||||
|
|
||||||
|
Initialization --> Operational : initialization complete
|
||||||
|
|
||||||
Initialization --> Operational : initialization\n complete
|
|
||||||
Operational --> Initialization : reset
|
Operational --> Initialization : reset
|
||||||
Operational --> Stopped : fault detected
|
Operational --> Stopped : fault detected
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,19 @@
|
|||||||
class State;
|
class State;
|
||||||
|
|
||||||
|
|
||||||
|
// Gildi úr einni keyrslu á hraðastýringunni, til útprentunar
|
||||||
|
struct ControlSample
|
||||||
|
{
|
||||||
|
double ref_rpm;
|
||||||
|
double actual_rpm;
|
||||||
|
double pwm_actual;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
class MotorController
|
class MotorController
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
static constexpr double DEFAULT_REFERENCE_RPM = 40.0;
|
static constexpr double DEFAULT_REFERENCE_RPM = 25.0;
|
||||||
static constexpr double PWM_PER_PERCENT = 255.0 / 100.0;
|
static constexpr double PWM_PER_PERCENT = 255.0 / 100.0;
|
||||||
static const uint8_t LED_PIN = 5; // PB5 = D13 = LED_BUILTIN
|
static const uint8_t LED_PIN = 5; // PB5 = D13 = LED_BUILTIN
|
||||||
|
|
||||||
@@ -42,13 +51,6 @@ public:
|
|||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
// void set_states(
|
|
||||||
// State* initialization,
|
|
||||||
// State* operational,
|
|
||||||
// State* stopped
|
|
||||||
// );
|
|
||||||
|
|
||||||
|
|
||||||
void begin();
|
void begin();
|
||||||
|
|
||||||
void update();
|
void update();
|
||||||
@@ -67,12 +69,15 @@ public:
|
|||||||
bool fault_active();
|
bool fault_active();
|
||||||
|
|
||||||
|
|
||||||
void run_speed_controller();
|
// Skilar true ef ný mæling var tekin og sample fyllt út
|
||||||
|
bool run_speed_controller(ControlSample& sample);
|
||||||
|
|
||||||
void stop_motor();
|
void stop_motor();
|
||||||
|
|
||||||
void reset_speed_measurement();
|
void reset_speed_measurement();
|
||||||
|
|
||||||
|
void reset_controller();
|
||||||
|
|
||||||
void led_on();
|
void led_on();
|
||||||
|
|
||||||
void led_off();
|
void led_off();
|
||||||
|
|||||||
@@ -3,9 +3,17 @@
|
|||||||
|
|
||||||
#include "state.h"
|
#include "state.h"
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
|
||||||
class OperationalState : public State
|
class OperationalState : public State
|
||||||
{
|
{
|
||||||
|
private:
|
||||||
|
static constexpr double SAMPLE_PERIOD_MS = 4.0;
|
||||||
|
|
||||||
|
// uint32_t svo teljarinn flæði ekki yfir eftir ~4 mín (eins og uint16_t)
|
||||||
|
uint32_t sample_count = 0;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
void enter() override;
|
void enter() override;
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,14 @@
|
|||||||
|
|
||||||
class P_controller
|
class P_controller
|
||||||
{
|
{
|
||||||
private:
|
protected:
|
||||||
double Kp;
|
double Kp;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
P_controller(double Kp);
|
P_controller(double Kp);
|
||||||
|
virtual ~P_controller() {}
|
||||||
double update(double ref, double actual);
|
virtual double update(double ref, double actual);
|
||||||
|
virtual void reset() {}
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#ifndef PI_CONTROLLER_H
|
||||||
|
#define PI_CONTROLLER_H
|
||||||
|
|
||||||
|
#include "p_controller.h"
|
||||||
|
|
||||||
|
class PI_controller : public P_controller
|
||||||
|
{
|
||||||
|
private:
|
||||||
|
static constexpr double U_MAX = 100.0; // %
|
||||||
|
static constexpr double U_MIN = -100.0; // %
|
||||||
|
|
||||||
|
double Ti;
|
||||||
|
double T;
|
||||||
|
double integral;
|
||||||
|
public:
|
||||||
|
PI_controller(double Kp, double Ti, double T);
|
||||||
|
double update(double ref, double actual) override;
|
||||||
|
void reset() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -14,4 +14,12 @@ board = nanoatmega328new
|
|||||||
framework = arduino
|
framework = arduino
|
||||||
|
|
||||||
monitor_speed = 115200
|
monitor_speed = 115200
|
||||||
|
test_framework = unity
|
||||||
|
test_build_src = yes
|
||||||
|
|
||||||
|
|
||||||
|
; [env:native]
|
||||||
|
; platform = native
|
||||||
|
; test_framework = unity
|
||||||
|
; test_build_src = yes
|
||||||
|
; build_src_filter = -<*> +<p_controller.cpp> +<pi_controller.cpp>
|
||||||
|
|||||||
+121
-36
@@ -1,46 +1,113 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""
|
||||||
Teiknar step response-plott ur CSV-gognum sem Arduino-verkefnid prentar ut
|
Teiknar step response-plott ur CSV-gognum sem Arduino-verkefnid prentar ut
|
||||||
(dalkar: time_ms, ref_rpm, actual_rpm, pwm_requested, pwm_actual).
|
i Operational state (dalkar: time_ms, ref_rpm, actual_rpm, pwm_actual).
|
||||||
|
|
||||||
pwm_requested = Kp * error * 2.55, oklippt (getur farid langt yfir +-255)
|
pwm_actual = stýrimerkid klippt vid +-255, þ.e. þad sem raunverulega
|
||||||
pwm_actual = sama gildi en klippt vid +-255, þ.e. þad sem raunverulega
|
var sent a motor.set() / vélbúnaðinn
|
||||||
var sent a motor.set() / vélbúnaðinn
|
|
||||||
|
Hausinn er prentadur i hvert skipti sem farid er inn i Operational, svo ein
|
||||||
|
skra getur innihaldid nokkrar keyrslur. Adeins sidasta keyrslan er teiknud.
|
||||||
|
|
||||||
|
Skriptan metur lika sveiflutima (Tu) og utslag ef kerfid sveiflast, sem
|
||||||
|
nytist til ad finna Ku/Tu fyrir Ziegler-Nichols.
|
||||||
|
|
||||||
Notkun:
|
Notkun:
|
||||||
python plot_step_response.py [inntak.csv] [uttak.png] [titill]
|
python plot_step_response.py [inntak.csv] [uttak.png] [titill] [--no-pwm]
|
||||||
|
|
||||||
|
--no-pwm teiknar bara RPM (PWM-dalkurinn ma lika vanta i CSV-skranni)
|
||||||
|
|
||||||
Sjalfgefid: data/step_response.csv -> data/step_response.png
|
Sjalfgefid: data/step_response.csv -> data/step_response.png
|
||||||
"""
|
"""
|
||||||
import sys
|
import sys
|
||||||
import csv
|
import csv
|
||||||
|
import statistics
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
|
||||||
|
COLUMNS = ["time_ms", "ref_rpm", "actual_rpm", "pwm_actual"]
|
||||||
|
REQUIRED = ["time_ms", "ref_rpm", "actual_rpm"]
|
||||||
|
|
||||||
|
# Onnur nofn sem eldri utgafur firmware-sins hafa notad fyrir sama dalk
|
||||||
|
ALIASES = {"pwm": "pwm_actual"}
|
||||||
|
|
||||||
|
|
||||||
|
def empty_cols():
|
||||||
|
return {key: [] for key in COLUMNS}
|
||||||
|
|
||||||
|
|
||||||
def load_csv(path):
|
def load_csv(path):
|
||||||
cols = {"time_ms": [], "ref_rpm": [], "actual_rpm": [],
|
cols = empty_cols()
|
||||||
"pwm_requested": [], "pwm_actual": []}
|
header = None
|
||||||
with open(path, newline="") as f:
|
with open(path, newline="") as f:
|
||||||
reader = csv.DictReader(f)
|
for row in csv.reader(f):
|
||||||
for row in reader:
|
if row and row[0].strip() == "time_ms":
|
||||||
try:
|
header = [name.strip() for name in row]
|
||||||
for key in cols:
|
header = [ALIASES.get(name, name) for name in header]
|
||||||
cols[key].append(float(row[key]))
|
missing = [key for key in REQUIRED if key not in header]
|
||||||
except (ValueError, KeyError):
|
if missing:
|
||||||
# sleppir linum sem eru ekki gild data (t.d. rusl fyrir/eftir)
|
sys.exit(f"Dalka vantar i haus {row}: {missing}")
|
||||||
for key in cols:
|
|
||||||
if len(cols[key]) > len(cols["time_ms"]):
|
|
||||||
cols[key].pop()
|
|
||||||
continue
|
continue
|
||||||
|
if header is None:
|
||||||
|
# rusl a undan fyrsta haus (t.d. "State: Initialization")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
values = {key: float(row[header.index(key)])
|
||||||
|
for key in COLUMNS if key in header}
|
||||||
|
except (ValueError, IndexError):
|
||||||
|
# sleppir linum sem eru ekki gild data (t.d. "State: ...")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Timinn byrjar aftur a 0 -> ny keyrsla, hendum theirri gomlu
|
||||||
|
if cols["time_ms"] and values["time_ms"] <= cols["time_ms"][-1]:
|
||||||
|
cols = empty_cols()
|
||||||
|
|
||||||
|
for key in values:
|
||||||
|
cols[key].append(values[key])
|
||||||
return cols
|
return cols
|
||||||
|
|
||||||
|
|
||||||
def plot(cols, out_path, title_suffix=""):
|
def estimate_oscillation(time_s, actual_rpm):
|
||||||
|
"""
|
||||||
|
Metur sveiflutima ut fra uppleid i gegnum medaltal seinni helmings
|
||||||
|
gagnanna (fyrri helmingur er transient). Hysteresis kemur i veg fyrir
|
||||||
|
ad sudid i rpm-maelingunni gefi falskar skurdpunkta.
|
||||||
|
Skilar (Tu [s], utslag [rpm]) eda None ef engin skyr sveifla.
|
||||||
|
"""
|
||||||
|
half = len(actual_rpm) // 2
|
||||||
|
t = time_s[half:]
|
||||||
|
y = actual_rpm[half:]
|
||||||
|
if len(y) < 20:
|
||||||
|
return None
|
||||||
|
|
||||||
|
mean = statistics.fmean(y)
|
||||||
|
band = 0.25 * statistics.pstdev(y)
|
||||||
|
if band == 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
crossings = []
|
||||||
|
below = y[0] < mean - band
|
||||||
|
for ti, yi in zip(t, y):
|
||||||
|
if below and yi > mean + band:
|
||||||
|
crossings.append(ti)
|
||||||
|
below = False
|
||||||
|
elif not below and yi < mean - band:
|
||||||
|
below = True
|
||||||
|
|
||||||
|
if len(crossings) < 3:
|
||||||
|
return None
|
||||||
|
|
||||||
|
periods = [b - a for a, b in zip(crossings, crossings[1:])]
|
||||||
|
amplitude = (max(y) - min(y)) / 2.0
|
||||||
|
return statistics.fmean(periods), amplitude
|
||||||
|
|
||||||
|
|
||||||
|
def plot(cols, out_path, title_suffix="", show_pwm=True):
|
||||||
time_s = [t / 1000.0 for t in cols["time_ms"]]
|
time_s = [t / 1000.0 for t in cols["time_ms"]]
|
||||||
ref_rpm = cols["ref_rpm"]
|
ref_rpm = cols["ref_rpm"]
|
||||||
actual_rpm = cols["actual_rpm"]
|
actual_rpm = cols["actual_rpm"]
|
||||||
pwm_requested = cols["pwm_requested"]
|
|
||||||
pwm_actual = cols["pwm_actual"]
|
pwm_actual = cols["pwm_actual"]
|
||||||
|
show_pwm = show_pwm and len(pwm_actual) == len(time_s)
|
||||||
|
|
||||||
fig, ax1 = plt.subplots(figsize=(10, 5))
|
fig, ax1 = plt.subplots(figsize=(10, 5))
|
||||||
|
|
||||||
@@ -52,14 +119,17 @@ def plot(cols, out_path, title_suffix=""):
|
|||||||
ax1.set_ylabel("Angular velocity [RPM]")
|
ax1.set_ylabel("Angular velocity [RPM]")
|
||||||
ax1.grid(True, alpha=0.3)
|
ax1.grid(True, alpha=0.3)
|
||||||
|
|
||||||
ax2 = ax1.twinx()
|
lines, labels = ax1.get_legend_handles_labels()
|
||||||
ax2.plot(time_s, pwm_requested, label="PWM requested (unclamped)",
|
if show_pwm:
|
||||||
color="#d62728", linewidth=1.0, alpha=0.5, linestyle=":")
|
ax2 = ax1.twinx()
|
||||||
ax2.plot(time_s, pwm_actual, label="PWM actual (clamped)",
|
ax2.plot(time_s, pwm_actual, label="PWM actual (clamped)",
|
||||||
color="#d62728", linewidth=1.4)
|
color="#d62728", linewidth=1.4)
|
||||||
ax2.axhline(255, color="#d62728", linewidth=0.6, alpha=0.3)
|
ax2.axhline(255, color="#d62728", linewidth=0.6, alpha=0.3)
|
||||||
ax2.axhline(-255, color="#d62728", linewidth=0.6, alpha=0.3)
|
ax2.axhline(-255, color="#d62728", linewidth=0.6, alpha=0.3)
|
||||||
ax2.set_ylabel("PWM [-255, 255]")
|
ax2.set_ylabel("PWM [-255, 255]")
|
||||||
|
lines2, labels2 = ax2.get_legend_handles_labels()
|
||||||
|
lines += lines2
|
||||||
|
labels += labels2
|
||||||
|
|
||||||
# Merkjum stokkpunktinn (fyrsta stadin thar sem ref hoppar fra 0)
|
# Merkjum stokkpunktinn (fyrsta stadin thar sem ref hoppar fra 0)
|
||||||
step_idx = next((i for i, r in enumerate(ref_rpm) if r > 0), None)
|
step_idx = next((i for i, r in enumerate(ref_rpm) if r > 0), None)
|
||||||
@@ -69,12 +139,23 @@ def plot(cols, out_path, title_suffix=""):
|
|||||||
ax1.text(time_s[step_idx], max(actual_rpm) * 1.02, " step",
|
ax1.text(time_s[step_idx], max(actual_rpm) * 1.02, " step",
|
||||||
fontsize=9, va="bottom")
|
fontsize=9, va="bottom")
|
||||||
|
|
||||||
lines1, labels1 = ax1.get_legend_handles_labels()
|
osc = estimate_oscillation(time_s, actual_rpm)
|
||||||
lines2, labels2 = ax2.get_legend_handles_labels()
|
# if osc is not None:
|
||||||
ax1.legend(lines1 + lines2, labels1 + labels2, loc="lower right",
|
# tu, amplitude = osc
|
||||||
fontsize=8)
|
# print(f"Sveifla: Tu = {tu * 1000:.1f} ms, utslag = +-{amplitude:.2f} RPM")
|
||||||
|
# ax1.text(0.99, 0.98, f"Tu ≈ {tu * 1000:.1f} ms\n"
|
||||||
|
# f"amplitude ≈ ±{amplitude:.2f} RPM",
|
||||||
|
# transform=ax1.transAxes, fontsize=9, va="top", ha="right",
|
||||||
|
# bbox=dict(facecolor="white", alpha=0.8, edgecolor="#cccccc"))
|
||||||
|
# else:
|
||||||
|
# print("Engin skyr sveifla fannst i seinni helmingi gagnanna")
|
||||||
|
|
||||||
title = "Double step response: RPM and PWM over time"
|
ax1.legend(lines, labels, loc="lower right", fontsize=8)
|
||||||
|
|
||||||
|
if show_pwm:
|
||||||
|
title = "Step response: RPM and PWM over time"
|
||||||
|
else:
|
||||||
|
title = "Step response: RPM over time"
|
||||||
if title_suffix:
|
if title_suffix:
|
||||||
title += f" ({title_suffix})"
|
title += f" ({title_suffix})"
|
||||||
fig.suptitle(title)
|
fig.suptitle(title)
|
||||||
@@ -84,8 +165,12 @@ def plot(cols, out_path, title_suffix=""):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
in_path = sys.argv[1] if len(sys.argv) > 1 else "data/twostep.csv"
|
show_pwm = "--no-pwm" not in sys.argv
|
||||||
out_path = sys.argv[2] if len(sys.argv) > 2 else "data/twostep.png"
|
args = [a for a in sys.argv[1:] if a != "--no-pwm"]
|
||||||
title_suffix = sys.argv[3] if len(sys.argv) > 3 else ""
|
in_path = args[0] if len(args) > 0 else "data/step_response.csv"
|
||||||
|
out_path = args[1] if len(args) > 1 else "data/step_response.png"
|
||||||
|
title_suffix = args[2] if len(args) > 2 else ""
|
||||||
data = load_csv(in_path)
|
data = load_csv(in_path)
|
||||||
plot(data, out_path, title_suffix)
|
if not data["time_ms"]:
|
||||||
|
sys.exit(f"Engin gogn fundust i {in_path}")
|
||||||
|
plot(data, out_path, title_suffix, show_pwm)
|
||||||
|
|||||||
+12
-6
@@ -1,9 +1,12 @@
|
|||||||
|
// main.cpp er sleppt i test-build (pio test) svo setup()/loop() rekist ekki a prof
|
||||||
|
#ifndef PIO_UNIT_TESTING
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <avr/interrupt.h>
|
#include <avr/interrupt.h>
|
||||||
|
|
||||||
#include "rotary_encoder_driver.h"
|
#include "rotary_encoder_driver.h"
|
||||||
#include "motor_driver.h"
|
#include "motor_driver.h"
|
||||||
#include "p_controller.h"
|
#include "pi_controller.h"
|
||||||
|
|
||||||
#include "motor_controller.h"
|
#include "motor_controller.h"
|
||||||
|
|
||||||
@@ -16,9 +19,12 @@ RotaryEncoderDriver encoder;
|
|||||||
|
|
||||||
MotorDriver motor;
|
MotorDriver motor;
|
||||||
|
|
||||||
const double KP = 12.5;
|
const double Kp = 10.125; // Ku * 0.45
|
||||||
|
const double Ti = 0.0334; // Tu * 0.83 37
|
||||||
|
const double T = 0.004; // 0.004
|
||||||
|
|
||||||
P_controller controller(KP);
|
// P_controller controller(Kp);
|
||||||
|
PI_controller controller(Kp, Ti, T);
|
||||||
|
|
||||||
|
|
||||||
InitializationState initialization_state;
|
InitializationState initialization_state;
|
||||||
@@ -52,8 +58,7 @@ int main()
|
|||||||
motor.begin();
|
motor.begin();
|
||||||
|
|
||||||
sei();
|
sei();
|
||||||
|
|
||||||
|
|
||||||
// motor_controller.set_states(
|
// motor_controller.set_states(
|
||||||
// &initialization_state,
|
// &initialization_state,
|
||||||
// &operational_state,
|
// &operational_state,
|
||||||
@@ -86,4 +91,5 @@ int main()
|
|||||||
|
|
||||||
// int main(){
|
// int main(){
|
||||||
// return 0;
|
// return 0;
|
||||||
// }
|
// }
|
||||||
|
#endif // PIO_UNIT_TESTING
|
||||||
|
|||||||
+35
-11
@@ -92,20 +92,39 @@ void MotorController::to_operational()
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void MotorController::run_speed_controller()
|
bool MotorController::run_speed_controller(ControlSample& sample)
|
||||||
{
|
{
|
||||||
if (encoder.new_speed_available())
|
if (!encoder.new_speed_available())
|
||||||
{
|
{
|
||||||
double actual = encoder.rpm();
|
return false;
|
||||||
|
|
||||||
double pwm_percent =
|
|
||||||
controller.update(reference_rpm, actual);
|
|
||||||
|
|
||||||
double pwm =
|
|
||||||
pwm_percent * PWM_PER_PERCENT;
|
|
||||||
|
|
||||||
motor.set(pwm);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
double actual = encoder.rpm();
|
||||||
|
|
||||||
|
double pwm_percent =
|
||||||
|
controller.update(reference_rpm, actual);
|
||||||
|
|
||||||
|
double pwm =
|
||||||
|
pwm_percent * PWM_PER_PERCENT;
|
||||||
|
|
||||||
|
// Klippt hér svo pwm_actual sé nákvæmlega það sem fer á mótorinn
|
||||||
|
if (pwm > 255.0)
|
||||||
|
{
|
||||||
|
pwm = 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pwm < -255.0)
|
||||||
|
{
|
||||||
|
pwm = -255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
motor.set(pwm);
|
||||||
|
|
||||||
|
sample.ref_rpm = reference_rpm;
|
||||||
|
sample.actual_rpm = actual;
|
||||||
|
sample.pwm_actual = pwm;
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -120,6 +139,11 @@ void MotorController::reset_speed_measurement()
|
|||||||
encoder.reset_speed_measurement();
|
encoder.reset_speed_measurement();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void MotorController::reset_controller()
|
||||||
|
{
|
||||||
|
controller.reset();
|
||||||
|
}
|
||||||
|
|
||||||
void MotorController::to_stopped()
|
void MotorController::to_stopped()
|
||||||
{
|
{
|
||||||
transition_to(stopped_state);
|
transition_to(stopped_state);
|
||||||
|
|||||||
@@ -8,7 +8,14 @@ void OperationalState::enter()
|
|||||||
{
|
{
|
||||||
Serial.println("State: Operational");
|
Serial.println("State: Operational");
|
||||||
|
|
||||||
|
context->reset_controller();
|
||||||
|
|
||||||
context->led_on();
|
context->led_on();
|
||||||
|
|
||||||
|
// Tíminn byrjar á 0 í hvert skipti sem farið er inn í Operational
|
||||||
|
sample_count = 0;
|
||||||
|
|
||||||
|
Serial.println("time_ms,ref_rpm,actual_rpm");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Part 1
|
// Part 1
|
||||||
@@ -31,7 +38,20 @@ void OperationalState::update()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
context->run_speed_controller();
|
ControlSample sample;
|
||||||
|
|
||||||
|
if (context->run_speed_controller(sample))
|
||||||
|
{
|
||||||
|
sample_count++;
|
||||||
|
|
||||||
|
Serial.print(sample_count * SAMPLE_PERIOD_MS, 1);
|
||||||
|
Serial.print(",");
|
||||||
|
Serial.print(sample.ref_rpm, 1);
|
||||||
|
Serial.print(",");
|
||||||
|
Serial.println(sample.actual_rpm, 2);
|
||||||
|
// Serial.print(",");
|
||||||
|
// Serial.println(sample.pwm_actual, 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#include "pi_controller.h"
|
||||||
|
|
||||||
|
PI_controller::PI_controller(double Kp, double Ti, double T) : P_controller(Kp), Ti(Ti), T(T), integral(0.0)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
double PI_controller::update(double ref, double actual)
|
||||||
|
{
|
||||||
|
double e = ref - actual;
|
||||||
|
double new_integral = integral + e * T;
|
||||||
|
double u = Kp * (e + new_integral / Ti);
|
||||||
|
|
||||||
|
if (u > U_MAX)
|
||||||
|
{
|
||||||
|
u = U_MAX;
|
||||||
|
}
|
||||||
|
else if (u < U_MIN)
|
||||||
|
{
|
||||||
|
u = U_MIN;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
integral = new_integral;
|
||||||
|
}
|
||||||
|
return u;
|
||||||
|
// return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PI_controller::reset()
|
||||||
|
{
|
||||||
|
integral = 0.0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
#include <unity.h>
|
||||||
|
|
||||||
|
// #ifdef ARDUINO
|
||||||
|
#include <Arduino.h>
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
#include "p_controller.h"
|
||||||
|
#include "pi_controller.h"
|
||||||
|
|
||||||
|
static const double KP = 2.0;
|
||||||
|
static const double TI = 1.0;
|
||||||
|
static const double T = 0.1;
|
||||||
|
static const double TOL = 1e-4; // double er 32-bita float a AVR
|
||||||
|
|
||||||
|
// void setUp(void) {}
|
||||||
|
// void tearDown(void) {}
|
||||||
|
|
||||||
|
// Normal flow: engin villa -> ekkert úttak
|
||||||
|
void test_zero_error_gives_zero_output(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, 0.0, c.update(10.0, 10.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal flow: fyrsta skref u = Kp * (e + e*T/Ti)
|
||||||
|
void test_first_step(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
double e = 5.0;
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, KP * (e + e * T / TI), c.update(e, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal flow: stöðug villa safnast upp, u_n = Kp * (e + n*e*T/Ti)
|
||||||
|
void test_integral_accumulates(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
double e = 5.0;
|
||||||
|
double u = 0.0;
|
||||||
|
for (int n = 1; n <= 5; n++)
|
||||||
|
{
|
||||||
|
u = c.update(e, 0.0);
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, KP * (e + n * e * T / TI), u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal flow: þegar villan er orðin 0 heldur integralið úttakinu uppi
|
||||||
|
void test_output_held_when_error_zero(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
double e = 5.0;
|
||||||
|
for (int n = 0; n < 5; n++)
|
||||||
|
{
|
||||||
|
c.update(e, 0.0);
|
||||||
|
}
|
||||||
|
double E = 5 * e * T;
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, KP * E / TI, c.update(0.0, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alt flow: villa langt utan getu -> mettun í +100 %
|
||||||
|
void test_saturates_high(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, 100.0, c.update(10000.0, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alt flow: mettun í -100 %
|
||||||
|
void test_saturates_low(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, -100.0, c.update(-10000.0, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alt flow: anti-windup. Eftir langa mettun á lítil neikvæð villa
|
||||||
|
// strax að gefa úttak undir mettun (integralið óx ekki)
|
||||||
|
void test_no_integral_windup(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
for (int n = 0; n < 1000; n++)
|
||||||
|
{
|
||||||
|
c.update(10000.0, 0.0);
|
||||||
|
}
|
||||||
|
double u = c.update(0.0, 1.0); // e = -1
|
||||||
|
TEST_ASSERT_TRUE(u < 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alt flow: reset (stopped -> operational) hreinsar integralið
|
||||||
|
void test_reset_clears_integral(void)
|
||||||
|
{
|
||||||
|
PI_controller c(KP, TI, T);
|
||||||
|
for (int n = 0; n < 5; n++)
|
||||||
|
{
|
||||||
|
c.update(5.0, 0.0);
|
||||||
|
}
|
||||||
|
c.reset();
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, 0.0, c.update(0.0, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Polymorphism: kall í gegnum P_controller& gefur PI hegðun
|
||||||
|
void test_polymorphic_update(void)
|
||||||
|
{
|
||||||
|
PI_controller pi(KP, TI, T);
|
||||||
|
P_controller& c = pi;
|
||||||
|
double e = 5.0;
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, KP * (e + e * T / TI), c.update(e, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// P_controller hegðar sér óbreytt
|
||||||
|
void test_p_controller_unchanged(void)
|
||||||
|
{
|
||||||
|
P_controller c(KP);
|
||||||
|
TEST_ASSERT_FLOAT_WITHIN(TOL, KP * 5.0, c.update(5.0, 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
// init();
|
||||||
|
delay(2000);
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(test_zero_error_gives_zero_output);
|
||||||
|
RUN_TEST(test_first_step);
|
||||||
|
RUN_TEST(test_integral_accumulates);
|
||||||
|
RUN_TEST(test_output_held_when_error_zero);
|
||||||
|
RUN_TEST(test_saturates_high);
|
||||||
|
RUN_TEST(test_saturates_low);
|
||||||
|
RUN_TEST(test_no_integral_windup);
|
||||||
|
RUN_TEST(test_reset_clears_integral);
|
||||||
|
RUN_TEST(test_polymorphic_update);
|
||||||
|
RUN_TEST(test_p_controller_unchanged);
|
||||||
|
// return UNITY_END();
|
||||||
|
UNITY_END();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {}
|
||||||
|
|
||||||
|
// #ifdef ARDUINO
|
||||||
|
// void setup()
|
||||||
|
// {
|
||||||
|
// delay(2000); // bida eftir serial tengingu eftir reset
|
||||||
|
// run_tests();
|
||||||
|
// }
|
||||||
|
|
||||||
|
// void loop()
|
||||||
|
// {
|
||||||
|
// }
|
||||||
|
// #else
|
||||||
|
// int main(int argc, char** argv)
|
||||||
|
// {
|
||||||
|
// return run_tests();
|
||||||
|
// }
|
||||||
|
// #endif
|
||||||
Reference in New Issue
Block a user