🎯 Миссия: Увеличить время автономной работы робота на 30%+
⭐ Метод: Научное исследование + алгоритмическая оптимизация
👨🏫 Учитель: Ахметов Рустам
🏫 Школа: ГБОУ № 1362
📅 Дата: 2025-06-14
⏰ Время: 105 минут
Создаем робота-марафонца:
“Оптимизация алгоритмов движения может существенно увеличить время автономной работы робота без снижения его функциональности”
Проверяем экспериментально!
Ваша команда исследователей должна:
Этап 1: Базовые измерения (Контрольная группа)
1// Эталонный алгоритм для сравнения
2void standardMovement() {
3 robot.setSpeed(200); // Высокая скорость
4 robot.moveForward(100); // Резкий старт
5 robot.stop(); // Резкая остановка
6 delay(1000); // Пауза
7}
Этап 2: Исследование факторов
Этап 3: Разработка оптимизации
1// Оптимизированный алгоритм
2void energyEfficientMovement() {
3 robot.smoothAccelerate(optimalSpeed, smoothAccel);
4 robot.maintainSpeed(optimalSpeed, distance);
5 robot.smoothDecelerate(0, smoothDecel);
6 robot.enterPowerSaveMode();
7}
Мощность и энергия: \[P = U \times I \quad [\text{Вт}]\]
\[E = P \times t = U \times I \times t \quad [\text{Дж}]\]Время автономной работы: \[t_{автономия} = \frac{C_{аккумулятор} \times U_{номинал}}{I_{средний}} \quad [\text{час}]\]
где C - емкость аккумулятора (Ач), I - средний ток потребления (А)
1[Аккумулятор 7.4V] → [Датчик тока INA219] → [Контроллер] → [Моторы]
2 ↓
3 [Компьютер с Arduino IDE]
4 ↓
5 [График в реальном времени]
Технические характеристики:
1#include <Wire.h>
2#include <Adafruit_INA219.h>
3
4class EnergyMeter {
5private:
6 Adafruit_INA219 ina219;
7 float totalEnergy = 0; // Общая потребленная энергия (Дж)
8 unsigned long lastTime = 0;
9
10public:
11 void initialize() {
12 ina219.begin();
13 Serial.begin(9600);
14 Serial.println("=== ENERGY OPTIMIZATION LAB ===");
15 Serial.println("Time(s)\tCurrent(mA)\tPower(mW)\tEnergy(J)");
16 lastTime = millis();
17 }
18
19 void measureAndLog() {
20 unsigned long currentTime = millis();
21 float deltaTime = (currentTime - lastTime) / 1000.0; // секунды
22
23 float voltage = ina219.getBusVoltage_V();
24 float current = ina219.getCurrent_mA();
25 float power = voltage * current; // мВт
26
27 // Накапливаем энергию
28 totalEnergy += (power / 1000.0) * deltaTime; // Джоули
29
30 // Логирование данных
31 Serial.print((currentTime - startTime) / 1000.0, 2);
32 Serial.print("\t");
33 Serial.print(current, 1);
34 Serial.print("\t");
35 Serial.print(power, 1);
36 Serial.print("\t");
37 Serial.println(totalEnergy, 3);
38
39 lastTime = currentTime;
40 }
41
42 float getCurrentConsumption() {
43 return ina219.getCurrent_mA();
44 }
45
46 float getTotalEnergy() {
47 return totalEnergy;
48 }
49
50 void resetMeasurement() {
51 totalEnergy = 0;
52 lastTime = millis();
53 }
54};
55
56EnergyMeter energyMeter;
Таблица 1: Базовые измерения
Режим работы | Длительность (с) | Ток мин (мА) | Ток макс (мА) | Ток средний (мА) | Энергия (Дж) |
---|---|---|---|---|---|
Покой | 30 | ___ | ___ | ___ | ___ |
Медленно (PWM=100) | 30 | ___ | ___ | ___ | ___ |
Средне (PWM=150) | 30 | ___ | ___ | ___ | ___ |
Быстро (PWM=200) | 30 | ___ | ___ | ___ | ___ |
Максимум (PWM=255) | 30 | ___ | ___ | ___ | ___ |
Таблица 2: Динамические режимы
Тип движения | Ток старта (мА) | Ток движения (мА) | Ток торможения (мА) | Общая энергия (Дж) |
---|---|---|---|---|
Резкий старт | ___ | ___ | ___ | ___ |
Плавный старт | ___ | ___ | ___ | ___ |
Резкое торможение | ___ | ___ | ___ | ___ |
Плавное торможение | ___ | ___ | ___ | ___ |
1class AdvancedEnergyAnalyzer {
2private:
3 vector<float> currentHistory;
4 vector<float> powerHistory;
5 int windowSize = 50; // Окно для анализа
6
7public:
8 void addMeasurement(float current, float power) {
9 currentHistory.push_back(current);
10 powerHistory.push_back(power);
11
12 // Ограничиваем размер истории
13 if (currentHistory.size() > windowSize) {
14 currentHistory.erase(currentHistory.begin());
15 powerHistory.erase(powerHistory.begin());
16 }
17 }
18
19 float calculateEfficiency() {
20 if (powerHistory.size() < 2) return 0;
21
22 float avgPower = 0;
23 float minPower = powerHistory[0];
24 float maxPower = powerHistory[0];
25
26 for (float power : powerHistory) {
27 avgPower += power;
28 minPower = min(minPower, power);
29 maxPower = max(maxPower, power);
30 }
31 avgPower /= powerHistory.size();
32
33 // Эффективность как обратная величина от разброса
34 float efficiency = avgPower / (maxPower - minPower + 1);
35 return efficiency;
36 }
37
38 bool detectPowerSpike() {
39 if (currentHistory.size() < 5) return false;
40
41 float recent = currentHistory.back();
42 float average = 0;
43
44 for (int i = currentHistory.size() - 5; i < currentHistory.size() - 1; i++) {
45 average += currentHistory[i];
46 }
47 average /= 4;
48
49 // Скачок тока более чем в 2 раза
50 return recent > average * 2.0;
51 }
52
53 void generateReport() {
54 Serial.println("=== ADVANCED ENERGY ANALYSIS ===");
55 Serial.print("Efficiency score: ");
56 Serial.println(calculateEfficiency(), 2);
57
58 if (detectPowerSpike()) {
59 Serial.println("WARNING: Power spike detected!");
60 }
61
62 Serial.print("Average power consumption: ");
63 float avgPower = 0;
64 for (float power : powerHistory) avgPower += power;
65 Serial.print(avgPower / powerHistory.size(), 2);
66 Serial.println(" mW");
67 }
68};
Функция для автоматизированных измерений:
1class AutomatedTestSuite {
2private:
3 EnergyMeter meter;
4 int testDuration = 30000; // 30 секунд на тест
5
6public:
7 void runSpeedDependencyTest() {
8 Serial.println("=== SPEED DEPENDENCY TEST ===");
9
10 int speeds[] = {0, 50, 100, 150, 200, 255};
11
12 for (int speed : speeds) {
13 Serial.print("Testing speed: ");
14 Serial.println(speed);
15
16 meter.resetMeasurement();
17 robot.setSpeed(speed);
18
19 unsigned long startTime = millis();
20 float totalCurrent = 0;
21 int measurements = 0;
22
23 while (millis() - startTime < testDuration) {
24 float current = meter.getCurrentConsumption();
25 totalCurrent += current;
26 measurements++;
27
28 meter.measureAndLog();
29 delay(100);
30 }
31
32 robot.stop();
33
34 float avgCurrent = totalCurrent / measurements;
35 float estimatedRuntime = (BATTERY_CAPACITY * 1000) / avgCurrent; // минуты
36
37 Serial.print("Speed: ");
38 Serial.print(speed);
39 Serial.print(" | Avg Current: ");
40 Serial.print(avgCurrent, 1);
41 Serial.print(" mA | Runtime: ");
42 Serial.print(estimatedRuntime, 1);
43 Serial.println(" min");
44
45 delay(5000); // Пауза между тестами
46 }
47 }
48
49 void runAccelerationTest() {
50 Serial.println("=== ACCELERATION TEST ===");
51
52 float accelerations[] = {0.5, 1.0, 2.0, 5.0, 10.0}; // м/с²
53
54 for (float accel : accelerations) {
55 Serial.print("Testing acceleration: ");
56 Serial.print(accel);
57 Serial.println(" m/s²");
58
59 meter.resetMeasurement();
60 robot.smoothAccelerate(150, accel);
61
62 delay(3000); // Наблюдаем процесс разгона
63
64 robot.stop();
65
66 Serial.print("Acceleration energy: ");
67 Serial.print(meter.getTotalEnergy(), 3);
68 Serial.println(" J");
69
70 delay(2000);
71 }
72 }
73};
График 1: Зависимость тока от скорости
1Ток потребления (мА)
2 ↑
32000│ ●
4 │ ●
51500│ ●
6 │ ●
71000│ ●
8 │●
9 500│
10 │
11 0└─────────────────────► Скорость PWM
12 0 50 100 150 200 255
График 2: Время автономной работы
1Время работы (мин)
2 ↑
3 120│●
4 │ ●
5 90│ ●
6 │ ●
7 60│ ●
8 │ ●
9 30│ ●
10 │ ●
11 0└─────────────────────► Скорость PWM
12 0 50 100 150 200 255
Математический анализ:
1class OptimizationAnalyzer {
2private:
3 vector<pair<int, float>> speedCurrentData;
4
5public:
6 void addDataPoint(int speed, float current) {
7 speedCurrentData.push_back(make_pair(speed, current));
8 }
9
10 int findOptimalSpeed() {
11 if (speedCurrentData.size() < 3) return 100; // Значение по умолчанию
12
13 float bestEfficiency = 0;
14 int optimalSpeed = 100;
15
16 for (auto& point : speedCurrentData) {
17 int speed = point.first;
18 float current = point.second;
19
20 if (speed == 0) continue; // Пропускаем состояние покоя
21
22 // Эффективность = скорость / ток
23 float efficiency = (float)speed / current;
24
25 if (efficiency > bestEfficiency) {
26 bestEfficiency = efficiency;
27 optimalSpeed = speed;
28 }
29 }
30
31 Serial.print("Optimal speed found: ");
32 Serial.print(optimalSpeed);
33 Serial.print(" (efficiency: ");
34 Serial.print(bestEfficiency, 3);
35 Serial.println(")");
36
37 return optimalSpeed;
38 }
39
40 float calculatePowerSavings(int originalSpeed, int optimizedSpeed) {
41 float originalCurrent = getCurrentForSpeed(originalSpeed);
42 float optimizedCurrent = getCurrentForSpeed(optimizedSpeed);
43
44 float savings = (originalCurrent - optimizedCurrent) / originalCurrent * 100;
45 return max(0.0f, savings);
46 }
47
48private:
49 float getCurrentForSpeed(int speed) {
50 // Интерполяция для нахождения тока при заданной скорости
51 for (int i = 0; i < speedCurrentData.size() - 1; i++) {
52 if (speed >= speedCurrentData[i].first && speed <= speedCurrentData[i+1].first) {
53 float ratio = (float)(speed - speedCurrentData[i].first) /
54 (speedCurrentData[i+1].first - speedCurrentData[i].first);
55 return speedCurrentData[i].second +
56 ratio * (speedCurrentData[i+1].second - speedCurrentData[i].second);
57 }
58 }
59 return speedCurrentData.back().second; // Последнее значение
60 }
61};
1class MLOptimizer {
2private:
3 struct TrainingData {
4 float speed;
5 float acceleration;
6 float load;
7 float current;
8 };
9
10 vector<TrainingData> trainingSet;
11
12public:
13 void addTrainingExample(float speed, float accel, float load, float current) {
14 trainingSet.push_back({speed, accel, load, current});
15 }
16
17 float predictCurrent(float speed, float accel, float load) {
18 if (trainingSet.empty()) return 1000; // Значение по умолчанию
19
20 // Простая k-nearest neighbors
21 vector<pair<float, float>> distances;
22
23 for (auto& data : trainingSet) {
24 float distance = sqrt(
25 pow(data.speed - speed, 2) +
26 pow(data.acceleration - accel, 2) +
27 pow(data.load - load, 2)
28 );
29 distances.push_back(make_pair(distance, data.current));
30 }
31
32 // Сортируем по расстоянию
33 sort(distances.begin(), distances.end());
34
35 // Берем среднее от 3 ближайших соседей
36 float avgCurrent = 0;
37 int k = min(3, (int)distances.size());
38
39 for (int i = 0; i < k; i++) {
40 avgCurrent += distances[i].second;
41 }
42
43 return avgCurrent / k;
44 }
45
46 vector<float> optimizeParameters(float targetRuntime) {
47 float bestSpeed = 100;
48 float bestAccel = 1.0;
49 float bestRuntime = 0;
50
51 // Перебираем возможные комбинации
52 for (int speed = 50; speed <= 200; speed += 10) {
53 for (float accel = 0.5; accel <= 3.0; accel += 0.5) {
54 float predictedCurrent = predictCurrent(speed, accel, 1.0);
55 float predictedRuntime = (BATTERY_CAPACITY * 1000) / predictedCurrent;
56
57 if (predictedRuntime > bestRuntime && predictedRuntime >= targetRuntime) {
58 bestRuntime = predictedRuntime;
59 bestSpeed = speed;
60 bestAccel = accel;
61 }
62 }
63 }
64
65 return {bestSpeed, bestAccel, bestRuntime};
66 }
67};
1. Плавные профили движения:
1class SmoothMotionController {
2private:
3 float currentSpeed = 0;
4 float targetSpeed = 0;
5 float acceleration = 1.0; // м/с² (настраиваемый параметр)
6
7public:
8 void setTargetSpeed(float target, float accel = 1.0) {
9 targetSpeed = target;
10 acceleration = accel;
11 }
12
13 void update(float deltaTime) {
14 if (abs(targetSpeed - currentSpeed) < 0.1) {
15 currentSpeed = targetSpeed; // Достигли цели
16 return;
17 }
18
19 float speedChange = acceleration * deltaTime;
20
21 if (targetSpeed > currentSpeed) {
22 currentSpeed = min(targetSpeed, currentSpeed + speedChange);
23 } else {
24 currentSpeed = max(targetSpeed, currentSpeed - speedChange);
25 }
26
27 // Применяем скорость к моторам
28 robot.setSpeed((int)currentSpeed);
29 }
30
31 bool isAtTargetSpeed() {
32 return abs(targetSpeed - currentSpeed) < 0.1;
33 }
34
35 float getCurrentSpeed() {
36 return currentSpeed;
37 }
38};
2. Адаптивное управление мощностью:
1class AdaptivePowerManager {
2private:
3 bool lowPowerMode = false;
4 float batteryLevel = 1.0; // 0-1
5 unsigned long lastActivity = 0;
6
7public:
8 void updateBatteryLevel(float voltage) {
9 // Оценка уровня заряда по напряжению
10 batteryLevel = map(voltage, 6.0, 8.4, 0.0, 1.0);
11 batteryLevel = constrain(batteryLevel, 0.0, 1.0);
12 }
13
14 void checkPowerMode() {
15 if (batteryLevel < 0.3) {
16 enableLowPowerMode();
17 } else if (batteryLevel > 0.7) {
18 disableLowPowerMode();
19 }
20
21 // Автоматический переход в режим сна
22 if (millis() - lastActivity > 30000) { // 30 секунд неактивности
23 enterSleepMode();
24 }
25 }
26
27 float getSpeedMultiplier() {
28 if (lowPowerMode) {
29 return 0.7; // Снижаем максимальную скорость на 30%
30 }
31 return 1.0;
32 }
33
34 int getOptimalSpeed(int requestedSpeed) {
35 float multiplier = getSpeedMultiplier();
36 return (int)(requestedSpeed * multiplier);
37 }
38
39private:
40 void enableLowPowerMode() {
41 if (!lowPowerMode) {
42 lowPowerMode = true;
43 Serial.println("LOW POWER MODE ACTIVATED");
44 }
45 }
46
47 void disableLowPowerMode() {
48 if (lowPowerMode) {
49 lowPowerMode = false;
50 Serial.println("NORMAL POWER MODE RESTORED");
51 }
52 }
53
54 void enterSleepMode() {
55 Serial.println("Entering sleep mode...");
56 // Отключаем все несущественные системы
57 robot.stop();
58 // В реальности здесь был бы переход в режим сна микроконтроллера
59 }
60};
1class EnergyEfficientPathPlanner {
2private:
3 struct Waypoint {
4 float x, y;
5 float preferredSpeed;
6 float energyCost;
7 };
8
9 vector<Waypoint> waypoints;
10
11public:
12 void addWaypoint(float x, float y, float speed = 100) {
13 Waypoint wp = {x, y, speed, 0};
14 wp.energyCost = calculateEnergyCost(wp);
15 waypoints.push_back(wp);
16 }
17
18 vector<Waypoint> optimizePath() {
19 if (waypoints.size() < 2) return waypoints;
20
21 // Оптимизируем скорости для минимизации общего энергопотребления
22 for (int i = 0; i < waypoints.size(); i++) {
23 if (i == 0 || i == waypoints.size() - 1) {
24 // Первая и последняя точки - плавный старт/стоп
25 waypoints[i].preferredSpeed = 80;
26 } else {
27 // Промежуточные точки - оптимальная скорость
28 waypoints[i].preferredSpeed = findOptimalSpeedForSegment(i);
29 }
30 }
31
32 return waypoints;
33 }
34
35 void executeOptimizedPath() {
36 SmoothMotionController motion;
37
38 for (auto& wp : waypoints) {
39 Serial.print("Moving to waypoint (");
40 Serial.print(wp.x); Serial.print(", ");
41 Serial.print(wp.y); Serial.print(") at speed ");
42 Serial.println(wp.preferredSpeed);
43
44 // Плавный переход к новой скорости
45 motion.setTargetSpeed(wp.preferredSpeed, 0.5); // Мягкое ускорение
46
47 // Движение к точке
48 moveToPosition(wp.x, wp.y, motion);
49
50 Serial.print("Waypoint reached. Energy cost: ");
51 Serial.print(wp.energyCost, 2);
52 Serial.println(" J");
53 }
54 }
55
56private:
57 float calculateEnergyCost(Waypoint& wp) {
58 // Упрощенная модель энергозатрат
59 float distance = sqrt(wp.x * wp.x + wp.y * wp.y);
60 float energyPerMeter = 0.1 + (wp.preferredSpeed / 1000.0); // Дж/м
61 return distance * energyPerMeter;
62 }
63
64 float findOptimalSpeedForSegment(int index) {
65 // Анализируем условия сегмента
66 float distance = calculateSegmentDistance(index);
67
68 if (distance < 50) {
69 return 60; // Короткий сегмент - низкая скорость
70 } else if (distance > 200) {
71 return 120; // Длинный сегмент - умеренная скорость
72 } else {
73 return 90; // Средний сегмент - средняя скорость
74 }
75 }
76
77 void moveToPosition(float x, float y, SmoothMotionController& motion) {
78 // Упрощенная навигация
79 float targetAngle = atan2(y, x) * 180 / PI;
80 float distance = sqrt(x*x + y*y);
81
82 // Поворот к цели
83 robot.turnToAngle(targetAngle);
84 delay(1000);
85
86 // Движение к цели с контролем скорости
87 unsigned long startTime = millis();
88 while (millis() - startTime < distance * 50) { // 50 мс на см
89 motion.update(0.1); // 100 мс интервал
90 delay(100);
91 }
92
93 motion.setTargetSpeed(0, 2.0); // Плавная остановка
94 while (!motion.isAtTargetSpeed()) {
95 motion.update(0.1);
96 delay(100);
97 }
98 }
99};
1class PredictiveEnergyOptimizer {
2private:
3 struct SystemState {
4 float batteryVoltage;
5 float ambientTemp;
6 float robotLoad;
7 float terrainDifficulty;
8 unsigned long timestamp;
9 };
10
11 vector<SystemState> stateHistory;
12
13public:
14 void recordSystemState() {
15 SystemState state;
16 state.batteryVoltage = energyMeter.getVoltage();
17 state.ambientTemp = getAmbientTemperature();
18 state.robotLoad = getCurrentLoad();
19 state.terrainDifficulty = assessTerrain();
20 state.timestamp = millis();
21
22 stateHistory.push_back(state);
23
24 // Ограничиваем историю последними 100 записями
25 if (stateHistory.size() > 100) {
26 stateHistory.erase(stateHistory.begin());
27 }
28 }
29
30 float predictRemainingRuntime() {
31 if (stateHistory.size() < 10) return 60; // Значение по умолчанию
32
33 // Анализируем тренд разряда батареи
34 float avgVoltageDecline = calculateVoltageDeclineRate();
35 float currentVoltage = stateHistory.back().batteryVoltage;
36 float cutoffVoltage = 6.0; // Минимальное напряжение
37
38 float remainingTime = (currentVoltage - cutoffVoltage) / avgVoltageDecline;
39 return max(0.0f, remainingTime / 60.0f); // Конвертируем в минуты
40 }
41
42 void adaptiveSpeedOptimization(float targetRuntime) {
43 float predictedRuntime = predictRemainingRuntime();
44
45 if (predictedRuntime < targetRuntime * 0.8) {
46 // Критически мало времени - переходим в экономный режим
47 Serial.println("CRITICAL BATTERY: Entering ultra-eco mode");
48 maxAllowedSpeed = 50;
49 accelerationLimit = 0.3;
50 } else if (predictedRuntime < targetRuntime) {
51 // Мало времени - умеренная экономия
52 Serial.println("LOW BATTERY: Entering eco mode");
53 maxAllowedSpeed = 80;
54 accelerationLimit = 0.5;
55 } else {
56 // Достаточно времени - нормальный режим
57 maxAllowedSpeed = 150;
58 accelerationLimit = 1.0;
59 }
60 }
61
62private:
63 float maxAllowedSpeed = 150;
64 float accelerationLimit = 1.0;
65
66 float calculateVoltageDeclineRate() {
67 if (stateHistory.size() < 2) return 0.01; // По умолчанию
68
69 float totalDecline = 0;
70 int samples = 0;
71
72 for (int i = 1; i < stateHistory.size(); i++) {
73 float timeDiff = (stateHistory[i].timestamp - stateHistory[i-1].timestamp) / 1000.0;
74 float voltageDiff = stateHistory[i-1].batteryVoltage - stateHistory[i].batteryVoltage;
75
76 if (timeDiff > 0) {
77 totalDecline += voltageDiff / timeDiff; // В/с
78 samples++;
79 }
80 }
81
82 return samples > 0 ? totalDecline / samples : 0.01;
83 }
84
85 float getCurrentLoad() {
86 // Оценка нагрузки на основе потребления тока
87 float current = energyMeter.getCurrentConsumption();
88 return map(current, 100, 2000, 0.0, 1.0); // Нормализация 0-1
89 }
90
91 float assessTerrain() {
92 // Упрощенная оценка сложности местности
93 float currentEffort = energyMeter.getCurrentConsumption();
94 float baselineEffort = 500; // мА на ровной поверхности
95
96 return currentEffort / baselineEffort;
97 }
98};
Стандартизированный тест:
1class PerformanceValidator {
2private:
3 struct TestResult {
4 string algorithmName;
5 float totalEnergy; // Джоули
6 float averageCurrent; // мА
7 float peakCurrent; // мА
8 float efficiency; // Скорость/Ток
9 float estimatedRuntime; // минуты
10 int completedCycles; // Количество пройденных циклов
11 };
12
13public:
14 TestResult runStandardizedTest(string algName, function<void()> algorithm) {
15 Serial.print("Testing algorithm: ");
16 Serial.println(algName.c_str());
17
18 TestResult result;
19 result.algorithmName = algName;
20
21 energyMeter.resetMeasurement();
22
23 unsigned long testStart = millis();
24 unsigned long testDuration = 120000; // 2 минуты тест
25
26 float totalCurrent = 0;
27 float maxCurrent = 0;
28 int measurements = 0;
29 int cycles = 0;
30
31 while (millis() - testStart < testDuration) {
32 unsigned long cycleStart = millis();
33
34 // Выполняем один цикл алгоритма
35 algorithm();
36 cycles++;
37
38 // Измеряем энергопотребление
39 float current = energyMeter.getCurrentConsumption();
40 totalCurrent += current;
41 maxCurrent = max(maxCurrent, current);
42 measurements++;
43
44 energyMeter.measureAndLog();
45 }
46
47 // Заполняем результаты
48 result.totalEnergy = energyMeter.getTotalEnergy();
49 result.averageCurrent = totalCurrent / measurements;
50 result.peakCurrent = maxCurrent;
51 result.completedCycles = cycles;
52 result.estimatedRuntime = (BATTERY_CAPACITY * 1000) / result.averageCurrent;
53 result.efficiency = (float)cycles / result.averageCurrent;
54
55 return result;
56 }
57
58 void compareResults(vector<TestResult> results) {
59 Serial.println("\n=== PERFORMANCE COMPARISON ===");
60 Serial.println("Algorithm\t\tAvg Current\tRuntime\tEfficiency\tImprovement");
61
62 if (results.empty()) return;
63
64 TestResult baseline = results[0]; // Первый результат как базовый
65
66 for (auto& result : results) {
67 float improvement = (result.estimatedRuntime - baseline.estimatedRuntime) /
68 baseline.estimatedRuntime * 100;
69
70 Serial.print(result.algorithmName.c_str());
71 Serial.print("\t");
72 Serial.print(result.averageCurrent, 1);
73 Serial.print(" mA\t");
74 Serial.print(result.estimatedRuntime, 1);
75 Serial.print(" min\t");
76 Serial.print(result.efficiency, 3);
77 Serial.print("\t");
78 Serial.print(improvement > 0 ? "+" : "");
79 Serial.print(improvement, 1);
80 Serial.println("%");
81 }
82
83 // Находим лучший результат
84 auto bestResult = max_element(results.begin(), results.end(),
85 [](const TestResult& a, const TestResult& b) {
86 return a.estimatedRuntime < b.estimatedRuntime;
87 });
88
89 Serial.print("\nBEST ALGORITHM: ");
90 Serial.println(bestResult->algorithmName.c_str());
91 Serial.print("Runtime improvement: ");
92 float bestImprovement = (bestResult->estimatedRuntime - baseline.estimatedRuntime) /
93 baseline.estimatedRuntime * 100;
94 Serial.print(bestImprovement, 1);
95 Serial.println("%");
96 }
97};
Алгоритм 1: Базовый (контроль)
1void baselineAlgorithm() {
2 robot.setSpeed(200); // Высокая скорость
3 robot.moveForward(500); // 5 метров
4 robot.turnRight(90); // Поворот на 90°
5 robot.moveForward(500); // Еще 5 метров
6 robot.turnRight(90); // Возврат
7 robot.stop();
8 delay(2000); // Пауза
9}
Алгоритм 2: Оптимизированный
1void optimizedAlgorithm() {
2 SmoothMotionController motion;
3 AdaptivePowerManager power;
4
5 // Плавный старт
6 motion.setTargetSpeed(optimalSpeed, 0.5);
7 while (!motion.isAtTargetSpeed()) {
8 motion.update(0.1);
9 delay(100);
10 }
11
12 // Движение с оптимальной скоростью
13 robot.moveForward(500);
14
15 // Адаптивное управление поворотом
16 motion.setTargetSpeed(60, 1.0); // Снижаем скорость для поворота
17 while (!motion.isAtTargetSpeed()) {
18 motion.update(0.1);
19 delay(100);
20 }
21
22 robot.smoothTurn(90);
23
24 // Продолжение маршрута
25 motion.setTargetSpeed(optimalSpeed, 0.5);
26 robot.moveForward(500);
27
28 // Плавная остановка
29 motion.setTargetSpeed(0, 1.0);
30 while (!motion.isAtTargetSpeed()) {
31 motion.update(0.1);
32 delay(100);
33 }
34
35 // Энергосберегающая пауза
36 power.enterLowPowerMode();
37 delay(1000);
38}
Игра 1: “Базовый vs Оптимизированный”
Игра 2: “Адаптивная скорость”
Игра 3: “Энергия команды”
Типичные улучшения:
Параметр оптимизации | Экономия энергии | Увеличение времени работы |
---|---|---|
Плавный старт/стоп | 15-25% | 18-30% |
Оптимальная скорость | 20-40% | 25-50% |
Адаптивное управление | 10-20% | 12-25% |
Планирование маршрута | 5-15% | 6-18% |
КОМПЛЕКСНАЯ ОПТИМИЗАЦИЯ | 35-60% | 45-80% |
Основные закономерности:
1// Итоговые рекомендации для энергоэффективного робота
2class EnergyEfficiencyGuidelines {
3public:
4 static const int OPTIMAL_SPEED = 120; // PWM 0-255
5 static const float SMOOTH_ACCELERATION = 0.5; // м/с²
6 static const int ECO_MODE_THRESHOLD = 30; // % заряда
7 static const int SLEEP_TIMEOUT = 30000; // мс неактивности
8
9 static void applyOptimalSettings(Robot& robot) {
10 robot.setDefaultSpeed(OPTIMAL_SPEED);
11 robot.setAccelerationProfile(SMOOTH_ACCELERATION);
12 robot.enableEcoMode(ECO_MODE_THRESHOLD);
13 robot.setSleepTimeout(SLEEP_TIMEOUT);
14
15 Serial.println("Optimal energy settings applied!");
16 }
17
18 static void printOptimizationReport(float baseRuntime, float optimizedRuntime) {
19 float improvement = (optimizedRuntime - baseRuntime) / baseRuntime * 100;
20
21 Serial.println("=== OPTIMIZATION REPORT ===");
22 Serial.print("Baseline runtime: ");
23 Serial.print(baseRuntime, 1);
24 Serial.println(" minutes");
25
26 Serial.print("Optimized runtime: ");
27 Serial.print(optimizedRuntime, 1);
28 Serial.println(" minutes");
29
30 Serial.print("Improvement: ");
31 Serial.print(improvement, 1);
32 Serial.println("%");
33
34 if (improvement >= 30) {
35 Serial.println("🏆 EXCELLENT optimization!");
36 } else if (improvement >= 20) {
37 Serial.println("✅ GOOD optimization!");
38 } else if (improvement >= 10) {
39 Serial.println("⚠️ Moderate optimization");
40 } else {
41 Serial.println("❌ Optimization needed");
42 }
43 }
44};
Научные навыки:
Инженерные компетенции:
Экологическое сознание:
Научные открытия нашей лаборатории:
Практическая значимость:
“Настоящая оптимизация рождается не из случайных попыток, а из глубокого понимания физических процессов, систематических измерений и научного анализа данных!”
1. Научный отчет Оформите результаты исследования в виде научного отчета:
2. Схема оптимизированного алгоритма Создайте блок-схему вашего оптимизированного алгоритма движения с пояснениями каждого блока и обоснованием принятых решений.
3. Расширенное исследование Проведите дополнительные эксперименты:
4. Техно-экономический анализ Рассчитайте экономический эффект от внедрения ваших оптимизаций:
5. Исследовательский проект Выберите одну из передовых тем для углубленного исследования:
6. Разработка библиотеки Создайте программную библиотеку энергооптимизации для роботов:
Мы стали настоящими исследователями:
Практические результаты:
Ваши исследования - часть глобальных усилий:
Профессии, где нужны ваши навыки:
Поздравляем с завершением лаборатории энергооптимизации!
Сегодня вы не просто изучили теорию - вы стали исследователями, которые:
Эти навыки помогут вам изменить мир к лучшему!
Энергоэффективность в робототехнике:
Для продолжающих исследования:
Программное обеспечение для анализа:
Специальности для энергооптимизаторов:
Поздравляем с успешным завершением исследования! Продолжайте создавать энергоэффективное будущее! 🔋🌱🚀✨