# 控制馬達正反轉基礎

使用樹莓派配合L298N橋式晶片來控制馬達正轉（前進）或是反轉（後退）是很容易的一件事，雖然容易，但卻是後續巡跡、避障等的基礎，讓我們來學學如何控制馬達運轉吧！

{% embed url="<https://youtu.be/dg1tcc6pNIA>" %}

```python
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

ENA = 13
IN1 = 19
IN2 = 16
ENB = 20
IN3 = 21
IN4 = 26

GPIO.setup(ENA, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(ENB, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN1, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN2, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN3, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN4, GPIO.OUT, initial=GPIO.LOW)

def Motor_Forward():
    print('motor forward')
    GPIO.output(ENA, True)
    GPIO.output(ENB, True)
    GPIO.output(IN1, True)
    GPIO.output(IN2, False)
    GPIO.output(IN3, True)
    GPIO.output(IN4, False)

def Motor_Stop():
    print('motor stop')
    GPIO.output(ENA, True)
    GPIO.output(ENB, True)
    GPIO.output(IN1, False)
    GPIO.output(IN2, False)
    GPIO.output(IN3, False)
    GPIO.output(IN4, False)

while True:
    GPIO.setwarnings(False)
    Motor_Forward()
    time.sleep(3)
    Motor_Stop()
    time.sleep(3)
```


---

# Agent Instructions: 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://s761111.gitbook.io/raspi-sensor/shu-mei-pai-yu-zi-zou-che/kong-zhi-ma-da-zheng-fan-zhuan-ji-chu.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.
