官术网_书友最值得收藏!

DC motor control in Python

In this section, we will discuss motor control using the Raspberry Pi Zero. Why discuss motor control? As we progress through different topics in this book, we will culminate in building a mobile robot. Hence, we need to discuss writing code in Python to control a motor using a Raspberry Pi.

In order to control a motor, we need an H-bridge motor driver (Discussing H-bridge is beyond our scope. There are several resources for H-bridge motor drivers: http://www.mcmanis.com/chuck/robotics/tutorial/h-bridge/). There are several motor driver kits designed for the Raspberry Pi. In this section, we will make use of the following kit: https://www.pololu.com/product/2753.

The Pololu product page also provides instructions on how to connect the motor. Let's get to writing some Python code to operate the motor:

from gpiozero import Motor 
from gpiozero import OutputDevice
import time

motor_1_direction = OutputDevice(13)
motor_2_direction = OutputDevice(12)

motor = Motor(5, 6)

motor_1_direction.on()
motor_2_direction.on()

motor.forward()

time.sleep(10)

motor.stop()

motor_1_direction.off()
motor_2_direction.off()

Raspberry Pi based motor control

In order to control the motor, let's declare the pins, the motor's speed pins and direction pins. As per the motor driver's documentation, the motors are controlled by GPIO pins 12, 13 and 5, 6, respectively.

from gpiozero import Motor 
from gpiozero import OutputDevice
import time

motor_1_direction = OutputDevice(13)
motor_2_direction = OutputDevice(12)

motor = Motor(5, 6)

Controlling the motor is as simple as turning on the motor using the on() method and moving the motor in the forward direction using the forward() method:

motor.forward()

Similarly, reversing the motor direction could be done by calling the reverse() method. Stopping the motor could be done by:

motor.stop()
主站蜘蛛池模板: 上饶县| 新绛县| 福贡县| 萨嘎县| 喜德县| 武鸣县| 乌兰浩特市| 扎兰屯市| 丹东市| 合作市| 泸水县| 巴彦淖尔市| 久治县| 中牟县| 彭阳县| 贵港市| 法库县| 商洛市| 平阴县| 克拉玛依市| 靖西县| 安远县| 工布江达县| 明溪县| 城口县| 宁蒗| 诸城市| 洛南县| 乌鲁木齐市| 庆元县| 东安县| 贵定县| 吉隆县| 水富县| 永寿县| 同仁县| 蓬莱市| 龙泉市| 磴口县| 吉木乃县| 双江|