├── .gitattributes
├── .github
└── workflows
│ └── tg-send.yml
├── LICENSE
├── README.md
├── README_EN.md
├── examples
└── test
│ └── test.ino
├── keywords.txt
├── library.properties
└── src
└── SoftServo.h
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.github/workflows/tg-send.yml:
--------------------------------------------------------------------------------
1 |
2 | name: Telegram Message
3 | on:
4 | release:
5 | types: [published]
6 | jobs:
7 | build:
8 | name: Send Message
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: send telegram message on push
12 | uses: appleboy/telegram-action@master
13 | with:
14 | to: ${{ secrets.TELEGRAM_TO }}
15 | token: ${{ secrets.TELEGRAM_TOKEN }}
16 | disable_web_page_preview: true
17 | message: |
18 | ${{ github.event.repository.name }} v${{ github.event.release.tag_name }}
19 | ${{ github.event.release.body }}
20 | https://github.com/${{ github.repository }}
21 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Alex
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/GyverLibs/SoftServo/releases/latest/download/SoftServo.zip)
2 | [](https://registry.platformio.org/libraries/gyverlibs/SoftServo)
3 | [](https://alexgyver.ru/)
4 | [](https://alexgyver.ru/support_alex/)
5 | [](https://github-com.translate.goog/GyverLibs/SoftServo?_x_tr_sl=ru&_x_tr_tl=en)
6 |
7 | [](https://t.me/GyverLibs)
8 |
9 | # SoftServo
10 | Библиотека для программного управления Servo (на базе millis/micros)
11 | - Не использует дополнительный аппаратный таймер
12 | - Работает на millis() и micros()
13 | - Синтаксис как у Servo.h
14 | - Режим работы асинхронный и с delay
15 | - Повышенная произвводительность для AVR
16 |
17 | ### Совместимость
18 | Совместима со всеми Arduino платформами (используются Arduino-функции)
19 |
20 | ## Содержание
21 | - [Установка](#install)
22 | - [Инициализация](#init)
23 | - [Использование](#usage)
24 | - [Пример](#example)
25 | - [Версии](#versions)
26 | - [Баги и обратная связь](#feedback)
27 |
28 |
29 | ## Установка
30 | - Библиотеку можно найти по названию **SoftServo** и установить через менеджер библиотек в:
31 | - Arduino IDE
32 | - Arduino IDE v2
33 | - PlatformIO
34 | - [Скачать библиотеку](https://github.com/GyverLibs/SoftServo/archive/refs/heads/main.zip) .zip архивом для ручной установки:
35 | - Распаковать и положить в *C:\Program Files (x86)\Arduino\libraries* (Windows x64)
36 | - Распаковать и положить в *C:\Program Files\Arduino\libraries* (Windows x32)
37 | - Распаковать и положить в *Документы/Arduino/libraries/*
38 | - (Arduino IDE) автоматическая установка из .zip: *Скетч/Подключить библиотеку/Добавить .ZIP библиотеку…* и указать скачанный архив
39 | - Читай более подробную инструкцию по установке библиотек [здесь](https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA)
40 | ### Обновление
41 | - Рекомендую всегда обновлять библиотеку: в новых версиях исправляются ошибки и баги, а также проводится оптимизация и добавляются новые фичи
42 | - Через менеджер библиотек IDE: найти библиотеку как при установке и нажать "Обновить"
43 | - Вручную: **удалить папку со старой версией**, а затем положить на её место новую. "Замену" делать нельзя: иногда в новых версиях удаляются файлы, которые останутся при замене и могут привести к ошибкам!
44 |
45 |
46 |
47 | ## Инициализация
48 | ```cpp
49 | SoftServo myservo;
50 | ```
51 |
52 |
53 | ## Использование
54 | ```cpp
55 | void attach(int pin, int min = 500, int max = 2400); // подключить с указанием мин и макс импульса
56 | void detach(); // отключить
57 | void asyncMode(); // переключить в асинхронный режим
58 | void delayMode(); // переключить в режим задержки (по умолч)
59 | bool tick(); // тикер, вызывать как можно чаще, в асинхронном режиме вернёт true во время отработки импульса
60 | void write(int value); // поставить на угол
61 | void writeMicroseconds(int us); // поставить на импульс
62 | int read(); // вернуть текущий угол
63 | int readMicroseconds(); // вернуть текущий импульс
64 | bool attached(); // true если серво подключена
65 | ```
66 |
67 |
68 | ## Пример
69 | Остальные примеры смотри в **examples**!
70 | ```cpp
71 | #include "SoftServo.h"
72 |
73 | SoftServo myservo;
74 |
75 | void setup() {
76 | myservo.attach(5);
77 |
78 | // asyncMode - вызов tick не блокирует код на величину импульса (0.7-2.5 мс)
79 | // но работа будет нестабильной при наличии задержек в коде
80 | // в этом режиме tick вернёт true на период импульса, можно запрещать
81 | // тяжёлые функции на этот период
82 | myservo.asyncMode();
83 |
84 | // delayMode - вызов tick блокирует код на величину импульса (0.7-2.5 мс) - по умолчанию
85 | myservo.delayMode();
86 | }
87 |
88 | int val = 0;
89 | void loop() {
90 | // тикер - вызывать как можно чаще для каждого экземпляра
91 | myservo.tick();
92 |
93 | // двигаем туда сюда
94 | static uint32_t tmr;
95 | if (millis() - tmr >= 50) {
96 | tmr = millis();
97 | static int dir = 5;
98 | val += dir;
99 | if (val >= 180 || val <= 0) dir = -dir; // разворачиваем
100 | myservo.write(val);
101 | }
102 | }
103 | ```
104 |
105 |
106 | ## Версии
107 | - v1.0
108 | - v1.1 - переделан FastIO
109 | - v1.1.1 - убран FastIO
110 | - v1.2 - мелкие фиксы
111 |
112 |
113 | ## Баги и обратная связь
114 | При нахождении багов создавайте **Issue**, а лучше сразу пишите на почту [alex@alexgyver.ru](mailto:alex@alexgyver.ru)
115 | Библиотека открыта для доработки и ваших **Pull Request**'ов!
116 |
117 |
118 | При сообщении о багах или некорректной работе библиотеки нужно обязательно указывать:
119 | - Версия библиотеки
120 | - Какой используется МК
121 | - Версия SDK (для ESP)
122 | - Версия Arduino IDE
123 | - Корректно ли работают ли встроенные примеры, в которых используются функции и конструкции, приводящие к багу в вашем коде
124 | - Какой код загружался, какая работа от него ожидалась и как он работает в реальности
125 | - В идеале приложить минимальный код, в котором наблюдается баг. Не полотно из тысячи строк, а минимальный код
126 |
--------------------------------------------------------------------------------
/README_EN.md:
--------------------------------------------------------------------------------
1 | This is an automatic translation, may be incorrect in some places. See sources and examples!
2 |
3 | # SoftServo
4 | Library for Servo software control (based on Millis/Micros)
5 | - does not use an additional hardware timer
6 | - works on Millis () and micros ()
7 | - syntax like Servo.h
8 | - Asynchronous operating mode and with Delay
9 | - increased producing for avr
10 |
11 | ## compatibility
12 | Compatible with all arduino platforms (used arduino functions)
13 |
14 | ## Content
15 | - [installation] (# Install)
16 | - [initialization] (#init)
17 | - [use] (#usage)
18 | - [Example] (# Example)
19 | - [versions] (#varsions)
20 | - [bugs and feedback] (#fedback)
21 |
22 |
23 | ## Installation
24 | - The library can be found by the name ** SoftServo ** and installed through the library manager in:
25 | - Arduino ide
26 | - Arduino ide v2
27 | - Platformio
28 | - [download the library] (https://github.com/gyverlibs/softServo/archive/refs/heads/main.zip) .ZIP archive for manual installation:
29 | - unpack and put in * C: \ Program Files (X86) \ Arduino \ Libraries * (Windows X64)
30 | - unpack and put in * C: \ Program Files \ Arduino \ Libraries * (Windows X32)
31 | - unpack and put in *documents/arduino/libraries/ *
32 | - (Arduino id) Automatic installation from. Zip: * sketch/connect the library/add .Zip library ... * and specify downloaded archive
33 | - Read more detailed instructions for installing libraries [here] (https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%BD%D0%BE%BE%BE%BED0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA)
34 | ### Update
35 | - I recommend always updating the library: errors and bugs are corrected in the new versions, as well as optimization and new features are added
36 | - through the IDE library manager: find the library how to install and click "update"
37 | - Manually: ** remove the folder with the old version **, and then put a new one in its place.“Replacement” cannot be done: sometimes in new versions, files that remain when replacing are deleted and can lead to errors!
38 |
39 |
40 |
41 | ## initialization
42 | `` `CPP
43 | SoftServo MyServo;
44 | `` `
45 |
46 |
47 | ## Usage
48 | `` `CPP
49 | Void attach (int pin, int min = 500, int max = 2400);// Connect with min and max pulse
50 | VOID Detach ();// Disable
51 | Void asyncmode ();// switch to asynchronous mode
52 | VOID DELAYMODE ();// switch to delay mode (default)
53 | Bool Tick ();// ticker, call as often as possible, in asynchronous mode will return True while working out a pulse
54 | VOID Write (int Value);// put on a corner
55 | VOID Writemicroseconds (Int US);// put on an impulse
56 | int Read ();// Return the current corner
57 | intMicroseconds ();// Return the current impulse
58 | Bool Attached ();// true if the servo is connected
59 | `` `
60 |
61 |
62 | ## Example
63 | The rest of the examples look at ** Examples **!
64 | `` `CPP
65 | #include "SoftServo.h"
66 |
67 | SoftServo MyServo;
68 |
69 | VOID setup () {
70 | MyServo.attach (5);
71 |
72 | // asyncmode - Tick call does not block the code for the value of the pulse (0.7-2.5 ms)
73 | // But the work will be unstable if there are delays in the code
74 | // In this mode, Tick will return True for the impulse period, you can prohibit
75 | // heavy functions for this period
76 | MyServo.asyncmode ();
77 |
78 | // Delaymode - Tick call blocks the code for the value of the pulse (0.7-2.5 ms) - by default
79 | MyServo.Delaymode ();
80 | }
81 |
82 | Int ValCranberries = 0;
83 | VOID loop () {
84 | // ticker - call as often as possible for each copy
85 | MyServo.tick ();
86 |
87 | // move here
88 | Static uint32_t tmr;
89 | if (millis () - tmr> = 50) {
90 | TMR = Millis ();
91 | Static inti = 5;
92 | val += dir;
93 | if (val> = 180 || val <= 0) die = -dir;// unfold
94 | MyServo.write (val);
95 | }
96 | }
97 | `` `
98 |
99 |
100 | ## versions
101 | - V1.0
102 | - V1.1 - Redeled Fastio
103 | - V1.1.1 - removed Fastio
104 | - V1.2 - Small fixes
105 |
106 |
107 | ## bugs and feedback
108 | Create ** Issue ** when you find the bugs, and better immediately write to the mail [alex@alexgyver.ru] (mailto: alex@alexgyver.ru)
109 | The library is open for refinement and your ** pull Request ** 'ow!
110 |
111 |
112 | When reporting about bugs or incorrect work of the library, it is necessary to indicate:
113 | - The version of the library
114 | - What is MK used
115 | - SDK version (for ESP)
116 | - version of Arduino ide
117 | - whether the built -in examples work correctly, in which the functions and designs are used, leading to a bug in your code
118 | - what code has been loaded, what work was expected from it and how it works in reality
119 | - Ideally, attach the minimum code in which the bug is observed.Not a canvas of a thousand lines, but a minimum code
--------------------------------------------------------------------------------
/examples/test/test.ino:
--------------------------------------------------------------------------------
1 | #include "SoftServo.h"
2 |
3 | SoftServo myservo;
4 |
5 | void setup() {
6 | myservo.attach(5);
7 |
8 | // asyncMode - вызов tick не блокирует код на величину импульса (0.7-2.5 мс)
9 | // но работа будет нестабильной при наличии задержек в коде
10 | // в этом режиме tick вернёт true на период импульса, можно запрещать
11 | // тяжёлые функции на этот период
12 | myservo.asyncMode();
13 |
14 | // delayMode - вызов tick блокирует код на величину импульса (0.7-2.5 мс) - по умолчанию
15 | myservo.delayMode();
16 | }
17 |
18 | int val = 0;
19 | void loop() {
20 | // тикер - вызывать как можно чаще для каждого экземпляра
21 | myservo.tick();
22 |
23 | // двигаем туда сюда
24 | static uint32_t tmr;
25 | if (millis() - tmr >= 50) {
26 | tmr = millis();
27 | static int dir = 5;
28 | val += dir;
29 | if (val >= 180 || val <= 0) dir = -dir; // разворачиваем
30 | myservo.write(val);
31 | }
32 | }
--------------------------------------------------------------------------------
/keywords.txt:
--------------------------------------------------------------------------------
1 | #######################################
2 | # Syntax Coloring Map For SoftServo
3 | #######################################
4 |
5 | #######################################
6 | # Datatypes (KEYWORD1)
7 | #######################################
8 |
9 | SoftServo KEYWORD1
10 |
11 | #######################################
12 | # Methods and Functions (KEYWORD2)
13 | #######################################
14 |
15 | attach KEYWORD2
16 | detach KEYWORD2
17 | asyncMode KEYWORD2
18 | delayMode KEYWORD2
19 | tick KEYWORD2
20 | write KEYWORD2
21 | writeMicroseconds KEYWORD2
22 | read KEYWORD2
23 | readMicroseconds KEYWORD2
24 | attached KEYWORD2
25 |
26 | #######################################
27 | # Constants (LITERAL1)
28 | #######################################
29 |
--------------------------------------------------------------------------------
/library.properties:
--------------------------------------------------------------------------------
1 | name=SoftServo
2 | version=1.2
3 | author=AlexGyver
4 | maintainer=AlexGyver
5 | sentence=Library for software servo motor control (by system timer)
6 | paragraph=Library for software servo motor control (by system timer)
7 | category=Device Control
8 | url=https://github.com/GyverLibs/SoftServo
9 | architectures=*
--------------------------------------------------------------------------------
/src/SoftServo.h:
--------------------------------------------------------------------------------
1 | /*
2 | Библиотека для программного управления Servo (на базе millis/micros)
3 | Документация:
4 | GitHub: https://github.com/GyverLibs/SoftServo
5 | Возможности:
6 | - Не использует дополнительный аппаратный таймер
7 | - Работает на millis() и micros()
8 | - Синтаксис как у Servo.h
9 | - Режим работы асинхронный и с delay
10 | - Повышенная произвводительность для AVR
11 |
12 | AlexGyver, alex@alexgyver.ru
13 | https://alexgyver.ru/
14 | MIT License
15 |
16 | Версии:
17 | v1.0 - релиз
18 | v1.1 - переделан FastIO
19 | v1.1.1 - убран FastIO
20 | v1.2 - мелкие фиксы
21 | */
22 |
23 | #ifndef SoftServo_h
24 | #define SoftServo_h
25 | #include
26 |
27 | class SoftServo {
28 | public:
29 | // подключить с указанием мин и макс импульса
30 | void attach(int pin, int min = 500, int max = 2400) {
31 | _pin = pin;
32 | pinMode(_pin, OUTPUT);
33 | _attached = true;
34 | _min = min;
35 | _max = max;
36 | _tmr50 = millis();
37 | _tmrUs = micros();
38 | _flag = 0;
39 | }
40 |
41 | // отключить
42 | void detach() {
43 | _attached = false;
44 | }
45 |
46 | // переключить в асинхронный режим
47 | void asyncMode() {
48 | _mode = true;
49 | }
50 |
51 | // переключить в режим задержки (по умолч)
52 | void delayMode() {
53 | _mode = false;
54 | }
55 |
56 | // тикер, вызывать как можно чаще
57 | // в асинхронном режиме вернёт true во время отработки импульса
58 | bool tick() {
59 | if (_attached && millis() - _tmr50 >= 20) {
60 | if (_mode) {
61 | if (!_flag) {
62 | _tmrUs = micros();
63 | _flag = 1;
64 | fastWrite(_pin, 1);
65 | } else {
66 | if (micros() - _tmrUs >= _us) {
67 | fastWrite(_pin, 0);
68 | _flag = 0;
69 | _tmr50 = millis();
70 | } else return true;
71 | }
72 | } else {
73 | _tmr50 = millis();
74 | fastWrite(_pin, 1);
75 | delayMicroseconds(_us);
76 | fastWrite(_pin, 0);
77 | }
78 | }
79 | return false;
80 | }
81 |
82 | // поставить на угол
83 | void write(int value) {
84 | if (value < 200) value = map(value, 0, 180, _min, _max);
85 | writeMicroseconds(value);
86 | }
87 |
88 | // поставить на импульс
89 | void writeMicroseconds(int us) {
90 | _us = us;
91 | }
92 |
93 | // вернуть текущий угол
94 | int read() {
95 | return map(_us, _min, _max, 0, 180);
96 | }
97 |
98 | // вернуть текущий импульс
99 | int readMicroseconds() {
100 | return _us;
101 | }
102 |
103 | // true если серво подключена
104 | bool attached() {
105 | return _attached;
106 | }
107 |
108 | private:
109 | void fastWrite(const uint8_t pin, bool val) {
110 | #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
111 | if (pin < 8) bitWrite(PORTD, pin, val);
112 | else if (pin < 14) bitWrite(PORTB, (pin - 8), val);
113 | else if (pin < 20) bitWrite(PORTC, (pin - 14), val);
114 | #elif defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny13__)
115 | bitWrite(PORTB, pin, val);
116 | #else
117 | digitalWrite(pin, val);
118 | #endif
119 | }
120 | uint8_t _pin = 255;
121 | int _us = 700, _min, _max;
122 | bool _attached = 0, _mode = 0, _flag = 0;
123 | uint32_t _tmr50, _tmrUs;
124 | };
125 | #endif
--------------------------------------------------------------------------------