PyRaspBeta

← All practice problems

Raspberry Pi practice problem · Motors & actuators

Gentle reverse

HardBudget $16Python · gpiozero

A DC motor on an L298N (IN1 GPIO5, IN2 GPIO6, ENA GPIO12) and a push button on GPIO27 (to ground, Pi pull-up). Slamming a geared motor straight into reverse strips gears, so change direction gently.

The motor starts forwards at full speed. Each press reverses it:

  1. ramp down linearly from full speed to 0 over 1 s;
  2. coast for 0.5 s with both IN pins low;
  3. ramp up the other way over 1 s, from 50 % to full (below about 50 % it can't start from rest — see the note).

Feed the driver's +12V and +5V terminals from the Pi's 5 V and join the grounds. On 5 V the bridge leaves the motor about 3 V: roughly 100 rpm at full speed, proportional to the PWM duty.

The test presses at 2 s and 6 s. It checks full speed before each press, about half speed (40–80 rpm) half-way down the ramp, GPIO5 and GPIO6 low in the coast, −35 to −80 rpm half-way up the reverse ramp, full reverse (< −90 rpm) from 4.8 s, and full forwards again from 8.8 s. It must never turn backwards before the first coast.

More in Motors & actuators