> For the complete documentation index, see [llms.txt](https://voltbro.gitbook.io/upravlenie-elektrodvigatelem/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://voltbro.gitbook.io/upravlenie-elektrodvigatelem/kollektornyi-dvigatel/shim/praktika.-vrashenie-dvigatelem-s-raznoi-skorostyu.md).

# Практика. Вращение двигателем с разной скоростью

Для генерации ШИМ в Arduino есть готовая функция analogWrite(pin, duty):

* pin – **PWM** пин&#x20;
* duty – заполнение ШИМ сигнала (коэффициент D). По умолчанию имеет разрядность **8 бит**, то есть принимает значение **0.. 255.** То есть, D=35%, соответствует значение 90, 50%-128, 100%-255.

Напомним, что за вращение мотора у нас отвечали пины PA8 и PA9, что можно увидеть в [описании](/upravlenie-elektrodvigatelem/kollektornyi-dvigatel/praktika.-vbcores/dc-draiver-15a.md) DC драйвера. И пин PB3 необходимо перевести в режим HIGH.

```arduino
#include <VBCoreG4_arduino_system.h>

#define IN1 PA8
#define IN2 PA9
#define SLEEPn PB3
#define VREF PA4
#define USR_BTN PC13

int forward = HIGH; //по умолчанию мотор вращается вперед
int prev_btnSt;
int buttonState;
int velocity = 0; // начальная скорость 0
HardwareTimer *timer = new HardwareTimer(TIM3);

void setup() {
 
  pinMode(PB3, OUTPUT); 
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(VREF, OUTPUT);
  pinMode(USR_BTN, INPUT_PULLUP);
 
  digitalWrite(SLEEPn, HIGH);
  digitalWrite(VREF, HIGH);
  analogWrite(IN1, 0);
  analogWrite(IN2, 0);

  prev_btnSt = digitalRead(USR_BTN);

  Serial.begin(115200);

  timer->pause();
  timer->setOverflow(100, HERTZ_FORMAT); //будем вызывать функцию вращения мотором с частотой 100 Гц
  timer->attachInterrupt(move);
  timer->refresh();
  timer->resume();

  delay(1000);
}

void loop() {
  buttonState = digitalRead(USR_BTN); //читаем состояние кнопки
  if(buttonState == LOW && prev_btnSt == HIGH){ //если кнопку нажали, а предыдущее состояние - не нажата
    forward = !forward;                        // меняем направление вращения мотора
    prev_btnSt = buttonState;                  // предыдущее состояние кнопки меняем на текущее
    analogWrite(IN1, 0);                      // на оба вывода подаем 0
    analogWrite(IN2, 0);
    delay(1);
  }
  if(buttonState == HIGH) {prev_btnSt = buttonState;}
  if (Serial.available() > 0) {
    velocity = Serial.readString().toInt();    // читаем значение скорости в Serial
  }
}

void move(){ // на оба вывода при нажатии кнопки подается 0, 
            // поэтому подаем аналоговый сигнал только на один вывод, 
            // в зависимости от направления вращения мотора
  if (forward == HIGH) {
      analogWrite(IN1, velocity); 
    }
  if (forward == LOW) {
    analogWrite(IN2, velocity);
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://voltbro.gitbook.io/upravlenie-elektrodvigatelem/kollektornyi-dvigatel/shim/praktika.-vrashenie-dvigatelem-s-raznoi-skorostyu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
