Home

Awesome

<div align = center>

PWMMotorControl

Arduino library to control brushed DC motors by PWM.<br/> It uses optional attached encoders to drive fixed distances.

Badge License: GPLv3     Badge Version     Badge Commits since latest     Badge Build Status     Badge Hit Counter <br/> <br/> Stand With Ukraine

Available as Arduino library "PWMMotorControl".<br/> Contains the RobotCarBlueDisplay example.

Button Install     Button API     Button Changelog

</div>

If you find this library useful, please give it a star.

🌎 Google Translate

<br/>

Features

The motor is mainly controlled by 2 dimensions:

  1. Direction / motor driver control. Can be FORWARD, BACKWARD, BRAKE (motor connections are shortened) or RELEASE (motor connections are high impedance).
  2. SpeedPWM which is ignored for BRAKE or RELEASE. Some functions allow a signed speedPWM parameter, which includes the direction as sign (positive -> FORWARD).
<br/>

API

Basic commands are:

Functions to go a specified distance:

Driving speed PWM (2.0 V) is the PWM value to use for driving a fixed distance. If it is set higher than RAMP_VALUE_OFFSET_SPEED_PWM (2.3 V), the software generates a ramp up from RAMP_VALUE_OFFSET_SPEED_PWM to requested driving speed PWM at the start of the movement and a ramp down to stop.

Functions for cars controlling 2 motors / motor sets from CarPWMMotorControl.hpp.

<br/>

Pictures

4WD car with IR receiver and Bluetooth module and 4 AA rechargeable batteries.Instructable
4 wheel carInstructable
<br/>

Full bridges

This library was tested with the bipolar full bridge IC L298 and the (recommended) MOSFET full bridge IC TB6612.

The L298 has a loss of around 2 volt, which is the reason for the attached heat sinkThe TB6612 has almost no loss
L298 boardTB6612 board
L298 voltages at both motor pins @7.5 VTB6612 effective motor voltage @7.6 V
L298 output voltagesTB6612 motor voltage
<br/>

PWM period

<br/>

Examples for this library

The examples are available at File > Examples > Examples from Custom Libraries / PWMMotorControl.<br/>

Start

One motor starts with DriveSpeedPWM / 2 for one second, then runs 1 second with DriveSpeedPWM. After stopping the motor, it tries to run for one full rotation (resulting in a 90 degree turn for a 2WD car). Then the other motor runs the same cycle. For the next loop, the direction is switched to backwards.

Square

4 times drive 40 cm and 90 degree left turn. After the square, the car is turned by 180 degree and the direction is switched to backwards. Then the square starts again.

PrintMotorDiagram

This example prints PWM, speed and distance / encoder-count diagram of an encoder motor. The encoder increment is inverted at falling PWM slope to show the quadratic kind of encoder graph. Timebase is 20 ms per plotted value.

Diagram for free running motor controlled by an MosFet bridge supplied by 7.0 voltDiagram for free running motor controlled by an L298 bridge supplied by 7.6 volt
7.0V MosFet free run7.6V L298 free run
Here you see that the speed is proportional to the PWM, but the minimal power to start the motor is 33/255 = 13% PWM or 0.9 volt.Due to losses and other effects in the L298, the start voltage is much higher.
MosFet bridge supplied by only 3.5 voltStart diagram for L298 with 6.2 volt
3.5V MosFet free run7.6V L298 free run
Here, the start voltage can be observed better.<br/>There is no stop at the same voltage, so the distance gets virtually negative.Higher start voltage and a non linear speed / PWM ratio here.

TestMotorWithIMU

Prints PWM, speed and distance diagram of the right (encoder) motor of a car equipped with a MPU6050 IMU. Encoder and IMU (MPU6050) data are printed simultaneously, to compare and to detect slipping.<br/> It does a start and stop car first with and second without ramp. It starts with DEFAULT_DRIVE_SPEED_PWM and doubles speed for next turn until MAX_SPEED_PWM.

Diagram for car controlled by an MosFet bridgeDiagram for car controlled by an L298 bridge
2WD Smart Car2WD Lafvin car

LineFollower

The code uses a TCRT 5000 3-channel sensor.

According to the 8 different states of the 3 sensor inputs, we perform the following actions: 0 - All sensors are dark or not connected -> stop or go forward after sharp turn 1 - Mid and right sensors are dark -> sharp right 2 - Left and right sensors are dark -> panic stop, because this is unexpected 3 - Only right sensor is dark -> right 4 - Mid and left sensors are dark -> sharp left 5 - Only mid sensor is dark -> forward 6 - Only left sensor is dark -> left 7 - All sensors are not dark -> stop or go backward after turn

YouTube video of LineFollower in action

Youtube video

RobotCarBasic

Template for your RobotCar control. Currently implemented is: Drive until distance too low, then stop, go backwards and turn random amount.

BasicIRControl

Implements basic car control by an IR remote. Mapping between keys of any IR remote sending NEC protocol (all the cheap china ones) and car commands can be done in IRCommandMapping.h.<br/> To support mapping, the received IR code is printed at the serial output if INFO is defined.

The 3 supported IR remotesBack view of 2 IR remotes
IR front viewIR front view

SmartCarFollowerSimple

The car tries to hold a distance between 30 and 40 cm to an obstacle. Only forward and back movement, no turn! The measured distance range is converted to a pitch as an acoustic feedback.

SmartCarFollower

The car tries to hold a distance between 22 and 30 cm to an target. If the target vanishes, the distance sensor rotates and scans up to 60 cm to get the vanished (or a new) target.

IR commands

If an IR Receiver is attached, the following IR commands are available:

Calibrating speed and rotation

Motor speed depends from motor supply voltage at a given PWM value.

First measure the motor supply voltage under normal load, i.e the fixed DEFAULT_DRIVE_SPEED_PWM, while turning in place and adjust PWM according to this voltage.

Second calibrate rotation.<br/>

  1. Start a 2 * 360 degree turn (4 * 360 for 2 wheel cars, which turn faster) to be sure to reach 360 degree.
  2. The user should press the stop button when 360 degree is reached.
  3. Then compute the internal MillimeterPer256Degreee value used for rotations.
  4. Move 90 degree left and right using the new computed values.

The steps 1 to 4 are first executed with turn in place, then with turn forward, since the values for both are different, so you must press the stop button twice for a complete calibration.

RobotCarBlueDisplay

Requires the Arduino library BlueDisplay.

Enables autonomous driving of a 2 or 4 wheel car with an Arduino.<br/> To avoid obstacles a HC-SR04 Ultrasonic sensor mounted on a SG90 Servo continuously scans the environment. Manual control is implemented by a GUI using a Bluetooth HC-05 Module and the BlueDisplay library.

<br/>

Compile options / macros for this library

To customize the library to different requirements, there are some compile options / macros available.<br/> These macros must be defined in your program before the line #include <CarPWMMotorControl.hpp>, #include <EncoderMotor.hpp> or #include <PWMDcMotor.hpp>to take effect.<br/> Modify them by enabling / disabling them, or change the values if applicable.

NameDefault valueDescription
USE_ENCODER_MOTOR_CONTROLdisabledUse slot-type photo interrupter and an attached encoder disc to enable motor distance and speed sensing for closed loop control.
USE_MPU6050_IMUdisabledUse GY-521 MPU6050 breakout board connected by I2C for support of precise turning and speed / distance calibration. Connectors point to the rear. Requires up to 2850 bytes program memory if USE_SOFT_I2C_MASTER defined and 3756 bytes if USE_SOFT_I2C_MASTER is not defined.
USE_ACCELERATOR_Y_FOR_SPEEDdisabledThe y axis of the GY-521 MPU6050 breakout board points forward / backward, i.e. connectors are at the left / right side.
USE_NEGATIVE_ACCELERATION_FOR_SPEEDdisabledThe speed axis of the GY-521 MPU6050 breakout board points backward, i.e. connectors are at the front or right side.
USE_ADAFRUIT_MOTOR_SHIELDdisabledUse Adafruit Motor Shield v2 connected by I2C instead of simple TB6612 or L298 breakout board.<br/>This requires only 2 I2C/TWI pins in contrast to the 6 pins used for the full bridge.<br/>For full bridge, the millis() timer0 is used for analogWrite since we use pin 5 & 6.
USE_STANDARD_LIBRARY_<br/>ADAFRUIT_MOTOR_SHIELDdisabledEnabling requires additionally 694 bytes program memory.
DO_NOT_SUPPORT_RAMPdisabledEnabling saves 378 bytes program memory.
DO_NOT_SUPPORT_AVERAGE_SPEEDdisabledEnabling disables the function getAverageSpeed() and saves 44 bytes RAM per motor and 156 bytes program memory.
USE_SOFT_I2C_MASTERdisabledSaves up to 2110 bytes program memory and 200 bytes RAM for I2C communication to Adafruit motor shield and MPU6050 IMU compared with Arduino Wire.
ENABLE_MOTOR_LIST_FUNCTIONSdisabledEnables the convenience functions *AllMotors*() and *forAll(). Requires up to additional 80 bytes program space and 7 bytes RAM.

Default car geometry dependent values used in this library

These values are for a standard 2 WD car as can be seen on the pictures below.

NameDefault valueDescription
CAR_HAS_4_WHEELSdisabledUse modified formula for turning the car.
CAR_HAS_4_MECANUM_WHEELSdisabledUse different setDirection() and modified values for going fixed distances.
DEFAULT_CIRCUMFERENCE_MILLIMETER220At a circumference of around 220 mm this gives 11 mm per count.
ENCODER_COUNTS_PER_FULL_ROTATION20This value is for 20 slot encoder discs, giving 20 on and 20 off counts per full rotation.
MILLIMETER_PER_DEGREE_DEFAULT2.2777 for 2 wheel drive cars, 4.1 for 4 WD cars and 2.2 for mecanum wheel cars.Reflects the geometry of the standard 2 WD car or mecanum cars sets. The 4 WD car value is estimated for slip on smooth surfaces.

Other default values for this library

These values are used by functions and some can be overwritten by set* functions.

NameDefault valueDescription
VIN_2_Li-ionundefinedIf defined sets FULL_BRIDGE_INPUT_MILLIVOLT to 7400.
VIN_1_Li-ionundefinedIf defined sets FULL_BRIDGE_INPUT_MILLIVOLT to 3700.
FULL_BRIDGE_INPUT_<br/>MILLIVOLT6000 or 7400 if VIN_2_Li-ion is definedThe supply voltage used for the full bridge.
USE_L298_BRIDGE undefinedIf defined, sets FULL_BRIDGE_LOSS_MILLIVOLT to 2.0 volt.
FULL_BRIDGE_LOSS_<br/>MILLIVOLT0 or 2000 if USE_L298_BRIDGE is definedThe internal voltage loss of the full bridge used, typically 0 volt for mosfet and 2 volt for bipolar bridges like the L298.
FULL_BRIDGE_OUTPUT_<br/>MILLIVOLT(FULL_BRIDGE_INPUT_MILLIVOLT - FULL_BRIDGE_LOSS_MILLIVOLT)The effective voltage available for the motor.
DEFAULT_START_<br/>MILLIVOLT1100The DC Voltage at which the motor start to move / dead band voltage.
DEFAULT_DRIVE_<br/>MILLIVOLT2000The derived DEFAULT_DRIVE_SPEED_PWM is the speed PWM value used for fixed distance driving.
DEFAULT_MILLIMETER_<br/>PER_SECOND320Value at DEFAULT_DRIVE_MILLIVOLT motor supply. A factor used to convert distance to motor on time in milliseconds using the formula:<br/>MillisForDistance = 20 + (RequestedDistanceMillimeter * MillisPerMillimeter * DriveSpeedPWM / DEFAULT_DRIVE_SPEED_PWM)

Compile options / macros for RobotCarBlueDisplay example

To customize the software to different car configurations, there are some compile options / macros available.<br/>

NameDefault valueDescription
CAR_HAS_VIN_VOLTAGE_DIVIDERundefinedVIN/11 at A2, e.g. 1 MΩ to VIN, 100 kΩ to ground. Required to show and monitor (for undervoltage) VIN voltage.
VIN_VOLTAGE_CORRECTIONundefined or 0.8 for UnoVoltage to be subtracted from VIN voltage for voltage monitoring. E.g. if there is a series diode between Li-ion and VIN as on the Uno boards, set it to 0.8.
DISTANCE_SERVO_IS_MOUNTED_HEAD_DOWNdisabledDistance.h
CAR_HAS_US_DISTANCE_SENSORdisabledA HC-SR04 ultrasonic distance sensor is mounted (default for most China smart cars).
US_SENSOR_SUPPORTS_1_PIN_MODEdisabledUse modified HC-SR04 modules or HY-SRF05 ones.</br>Modify HC-SR04 by connecting 10 kΩ between echo and trigger and then use only trigger pin.
CAR_HAS_IR_DISTANCE_SENSORdisabledUse Sharp GP2Y0A21YK / 1080 IR distance sensor.
CAR_HAS_TOF_DISTANCE_SENSORdisabledUse VL53L1X TimeOfFlight distance sensor.
CAR_HAS_DISTANCE_SERVOdisabledDistance sensor is mounted on a pan servo (default for most China smart cars).
CAR_HAS_PAN_SERVOdisabledEnables the pan slider for the PanServo at the PAN_SERVO_PIN pin.
CAR_HAS_TILT_SERVOdisabledEnables the tilt slider for the TiltServo at the TILT_SERVO_PIN pin.
CAR_HAS_CAMERAdisabledEnables the Camera button for the CAMERA_SUPPLY_CONTROL_PIN pin.
CAR_HAS_LASERdisabledEnables the Laser button for the LASER_OUT_PIN / LED_BUILTIN pin.
ENABLE_RTTTL_FOR_CARundefinedPlays melody after initial timeout has reached. Enables the Melody button, which plays a random melody.
MONITOR_VIN_VOLTAGEdisabledShows VIN voltage and monitors it for undervoltage. VIN/11 at A2, 1 MΩ to VIN, 100 kΩ to ground.
ENABLE_EEPROM_STORAGEdisabledActivates the buttons to store compensation and drive speed.
<br/>

Pictures

Connection schematic of the L298 board for the examples. If motor drives in opposite direction, you must flip the motor to L298 connections. L298 connections

2 wheel car from LAVFIN with battery case for two 18650 Li-ion batteries, and IR receiver, with power wires in original length.<br/> 2 wheel car

Connections on the Arduino and on the L298 board.<br/> Sensor shield connections L298 connections

2 wheel car with encoders, slot-type photo interrupter, 2 Li-ion batteries, Adafruit Motor Shield V2, HC-05 Bluetooth module, and servo mounted head down. 2 wheel car 4 wheel car with servo mounted head up. 4 wheel car Encoder slot-type photo interrupter sensor Encoder slot-type photo interrupter sensor Servo mounted head down Servo mounting VIN sensing VIN sensing

<br/>

Revision History

Version 2.1.1

Version 2.1.0

Version 2.0.0

Version 1.9.0 - a 2.0.0 pre release

Version 1.0.0