From 6929095e2b243fbcb587daf74a8f0a9b81592519 Mon Sep 17 00:00:00 2001 From: Alexey_Tiurnikov Date: Wed, 11 Mar 2026 12:06:26 +0300 Subject: [PATCH] Initial commit: GalvoScan --- .DS_Store | Bin 0 -> 6148 bytes .gitignore | 5 + .vscode/extensions.json | 10 ++ include/README | 37 +++++ lib/README | 46 +++++++ platformio.ini | 7 + src/main.cpp | 291 ++++++++++++++++++++++++++++++++++++++++ test/README | 11 ++ 8 files changed, 407 insertions(+) create mode 100644 .DS_Store create mode 100644 .gitignore create mode 100644 .vscode/extensions.json create mode 100644 include/README create mode 100644 lib/README create mode 100644 platformio.ini create mode 100644 src/main.cpp create mode 100644 test/README diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5172429f264de2441865cb4700216d4256da9242 GIT binary patch literal 6148 zcmeH~J!%6%427R!7lt%jx}3%b$PET#pTHLgIFQEJ;E>dF^gR7ES*H$5cmnB-G%I%Z zD|S`@Z2$T80!#olbXV*=%*>dt@PRwdU#I)^a=X5>;#J@&VrHyNnC;iLL0pQvfVyTmjO&;ssLc!1UOG})p;=82 zR;?Ceh}WZ?+UmMqI#RP8R>OzYoz15hnq@nzF`-!xQ4j$Um=RcIKKc27r2jVm&svm< zfC&6E0=7P!4tu^-ovjbA=k?dB`g+i*aXG_}p8zI)6mRKa+;6_1_R^8c3Qa!(fk8n8 H{*=HsM+*^= literal 0 HcmV?d00001 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/include/README b/include/README new file mode 100644 index 0000000..49819c0 --- /dev/null +++ b/include/README @@ -0,0 +1,37 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the convention is to give header files names that end with `.h'. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/README b/lib/README new file mode 100644 index 0000000..9379397 --- /dev/null +++ b/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into the executable file. + +The source code of each library should be placed in a separate directory +("lib/your_library_name/[Code]"). + +For example, see the structure of the following example libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional. for custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +Example contents of `src/main.c` using Foo and Bar: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +The PlatformIO Library Dependency Finder will find automatically dependent +libraries by scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..3c32427 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,7 @@ +[env:nucleo_f429zi] +platform = ststm32 +board = nucleo_f429zi +framework = arduino + +monitor_speed = 115200 +upload_protocol = stlink diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..d046fc1 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,291 @@ +#include +#include + +// Пины DAC (Nucleo-F429ZI): PA4 — X, PA5 — Y +static const uint8_t DAC_PIN_X = PA4; +static const uint8_t DAC_PIN_Y = PA5; +// Пины обратной связи (аналоговый вход): A0 — X_fb, A1 — Y_fb +static const uint8_t ADC_PIN_FB_X = A0; +static const uint8_t ADC_PIN_FB_Y = A1; + +// Настройка наклона: положительное значение вычитает долю X из Y (против часовой) +static const float TILT_Y_DEG =0.0f; + +static const uint16_t DAC_MAX = 4095; +static const uint16_t DAC_MID = DAC_MAX / 2; +static const uint32_t AUTO_REPORT_MS = 200; // период телеметрии в авто-режиме + +// Неблокирующее чтение строки до '\n' +static String readLine() { + static String buffer; + while (Serial.available()) { + char c = (char)Serial.read(); + if (c == '\r') continue; + if (c == '\n') { + String line = buffer; + buffer = ""; + line.trim(); + return line; + } + buffer += c; + } + return String(); +} + +// Применить координаты (смещение в кодах относительно середины), учесть наклон и вывести на DAC +static void applyPosition(int32_t off_x, int32_t off_y) { + const float tilt_k = tanf(TILT_Y_DEG * (float)M_PI / 180.0f); + const float x_rot = (float)off_x; + const float y_rot = (float)off_y - tilt_k * (float)off_x; + + int32_t dac_x = (int32_t)lroundf((float)DAC_MID + x_rot); + int32_t dac_y = (int32_t)lroundf((float)DAC_MID + y_rot); + + if (dac_x < 0) dac_x = 0; + if (dac_x > DAC_MAX) dac_x = DAC_MAX; + if (dac_y < 0) dac_y = 0; + if (dac_y > DAC_MAX) dac_y = DAC_MAX; + + analogWrite(DAC_PIN_X, (uint16_t)dac_x); + analogWrite(DAC_PIN_Y, (uint16_t)dac_y); +} + +// Считать обратную связь с A0/A1 и вывести в консоль +static void printFeedback() { + auto readAvg3 = [](uint8_t pin) -> uint16_t { + uint32_t acc = 0; + for (int i = 0; i < 3; ++i) { + acc += (uint32_t)analogRead(pin); + } + return (uint16_t)(acc / 3U); + }; + + uint16_t fb_x = readAvg3(ADC_PIN_FB_X); + uint16_t fb_y = readAvg3(ADC_PIN_FB_Y); + + Serial.print(F("FB A0=")); + Serial.print(fb_x); + Serial.print(F(" A1=")); + Serial.println(fb_y); +} + +static void printPrompt(int32_t step_codes) { + Serial.println(); + Serial.print(F("Шаг (коды DAC): ")); + Serial.println(step_codes); + Serial.println(F("Команды: w=вверх, s=вниз, a=влево, d=вправо, stepN=новый шаг")); + Serial.println(F("auto v|h SPEED — авто по вертикали/горизонтали, stop — остановка авто")); + Serial.print(F("> ")); +} + +// Попытаться обновить шаг командой вида "stepN" (например, step200) +static bool tryUpdateStep(const String& line, int32_t& step_codes) { + if (line.length() < 5) return false; // минимум "step1" + + if (!(tolower(line[0]) == 's' && tolower(line[1]) == 't' && + tolower(line[2]) == 'e' && tolower(line[3]) == 'p')) { + return false; + } + + String num = line.substring(4); + num.trim(); + long v = num.toInt(); + + if (v <= 0 || v > (long)DAC_MAX) { + Serial.println(F("Формат: stepN, где N от 1 до 4095.")); + Serial.print(F("> ")); + return true; // команда распознана, но число некорректно + } + + step_codes = (int32_t)v; + Serial.print(F("Новый шаг: ")); + Serial.println(step_codes); + Serial.print(F("> ")); + return true; +} + +void setup() { + Serial.begin(115200); + while (!Serial) {} + Serial.setTimeout(50); + + analogWriteResolution(12); + analogReadResolution(12); + analogWrite(DAC_PIN_X, DAC_MID); + analogWrite(DAC_PIN_Y, DAC_MID); + + Serial.println(F("Galvo control: вводи шаг в кодах DAC и двигай w/a/s/d.")); + Serial.print(F("Введи шаг (по умолчанию 100): ")); +} + +void loop() { + static bool step_set = false; + static int32_t step_codes = 100; + static float off_x = 0.0f; + static float off_y = 0.0f; + static bool auto_mode = false; + static bool auto_vertical = true; // true = X (вверх/вниз), false = Y (влево/вправо) + static float auto_speed = 0.0f; // кодов DAC в секунду + static uint32_t last_update_us = 0; // для интегрирования скорости + static uint32_t last_report_ms = 0; // для периодической печати + + const float limit = (float)DAC_MID; + + // Обновляем координаты для авто-режима даже без входа с Serial + uint32_t now_us = micros(); + if (last_update_us == 0) last_update_us = now_us; + float dt = (now_us - last_update_us) / 1000000.0f; + last_update_us = now_us; + + bool auto_moved = false; + if (auto_mode && dt > 0.0f) { + float* axis = auto_vertical ? &off_x : &off_y; + *axis += auto_speed * dt; + + if (*axis > limit) { + *axis = limit; + auto_speed = -fabsf(auto_speed); // отражение от верхней/правой границы + } else if (*axis < -limit) { + *axis = -limit; + auto_speed = fabsf(auto_speed); // отражение от нижней/левой границы + } + + auto_moved = true; + } + + if (auto_moved) { + applyPosition((int32_t)lroundf(off_x), (int32_t)lroundf(off_y)); + uint32_t now_ms = millis(); + if (now_ms - last_report_ms >= AUTO_REPORT_MS) { + Serial.print(F("AUTO ")); + Serial.print(auto_vertical ? F("X") : F("Y")); + Serial.print(F(" off=")); + Serial.print((int32_t)lroundf(auto_vertical ? off_x : off_y)); + Serial.print(F(" speed=")); + Serial.print(auto_speed); + Serial.println(F(" код/с")); + printFeedback(); + Serial.print(F("> ")); + last_report_ms = now_ms; + } + } + + String line = readLine(); + if (line.length() == 0) return; + + if (!step_set) { + long v = line.toInt(); + if (v > 0 && v <= (long)DAC_MAX) { + step_codes = (int32_t)v; + } + step_set = true; + printPrompt(step_codes); + return; + } + + String lower = line; + lower.toLowerCase(); + + // Остановка авто-режима + if (lower == "stop") { + auto_mode = false; + auto_speed = 0.0f; + Serial.println(F("Авто-режим остановлен.")); + Serial.print(F("> ")); + return; + } + + // Запуск авто-режима: auto v|h SPEED + if (lower.startsWith("auto")) { + String tail = lower.substring(4); + tail.trim(); + + if (tail == "stop") { + auto_mode = false; + auto_speed = 0.0f; + Serial.println(F("Авто-режим остановлен.")); + Serial.print(F("> ")); + return; + } + + if (tail.length() == 0) { + Serial.println(F("Формат: auto v|h SPEED, например auto v 800")); + Serial.print(F("> ")); + return; + } + + char axis = tail[0]; + if (axis != 'v' && axis != 'h' && axis != 'x' && axis != 'y') { + Serial.println(F("Ось должна быть v (вертикаль/X) или h (горизонталь/Y).")); + Serial.print(F("> ")); + return; + } + + String speed_str = tail.substring(1); + speed_str.trim(); + if (speed_str.startsWith("=")) speed_str = speed_str.substring(1); + + float spd = speed_str.toFloat(); + if (speed_str.length() == 0 || spd == 0.0f) { + Serial.println(F("Нужна ненулевая скорость, пример: auto h -1200")); + Serial.print(F("> ")); + return; + } + + auto_mode = true; + auto_vertical = (axis == 'v' || axis == 'x'); + auto_speed = spd; + last_update_us = micros(); + last_report_ms = millis(); + + Serial.print(F("Авто-режим: ")); + Serial.print(auto_vertical ? F("вертикаль") : F("горизонталь")); + Serial.print(F(", скорость ")); + Serial.print(auto_speed); + Serial.println(F(" код/с")); + Serial.print(F("> ")); + return; + } + + char cmd = lower[0]; + bool moved = false; + + // Команда смены шага: stepN + if (tryUpdateStep(line, step_codes)) { + return; + } + + if (cmd == 'w') { + off_x += (float)step_codes; // вверх = X+ + moved = true; + } else if (cmd == 's') { + off_x -= (float)step_codes; // вниз = X- + moved = true; + } else if (cmd == 'a') { + off_y -= (float)step_codes; // влево = Y- + moved = true; + } else if (cmd == 'd') { + off_y += (float)step_codes; // вправо = Y+ + moved = true; + } else { + Serial.println(F("Неизвестная команда. Используй w/a/s/d, auto v|h SPEED или stop.")); + } + + // Ограничиваем смещения, чтобы не выйти за диапазон DAC + if (off_x > limit) off_x = limit; + if (off_x < -limit) off_x = -limit; + if (off_y > limit) off_y = limit; + if (off_y < -limit) off_y = -limit; + + if (moved) { + applyPosition((int32_t)lroundf(off_x), (int32_t)lroundf(off_y)); + int32_t off_x_int = (int32_t)lroundf(off_x); + int32_t off_y_int = (int32_t)lroundf(off_y); + Serial.print(F("X_off=")); + Serial.print(off_x_int); + Serial.print(F(" Y_off=")); + Serial.println(off_y_int); + printFeedback(); + Serial.print(F("> ")); + } +} diff --git a/test/README b/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html