Controlling Motors and Setting PWM


Major Functions for a Motor

Creating a Instance of a Motor Port

Connect a motor to a motor port of this board and create a instance of the port by using ExpansionDCMotor() function.

ExpansionDCMotor dcmotor(sid, port);

Setting a PWM period

Set a PWM period by using setPeriod() function.

dcmotor.setPeriod(period);

Controlling a Motor

Set a HIGH duration for controlling a motor by using setWidth() function.

dcmotor.setWidth(width);

The HIGH duration is the time during which the HIGH signal is output within one cycle of the PWM signal. Setting the HIGH duration determines the duty cycle of the PWM signal.

Duty Cycle(%) = HIGH duration / period * 100

PWM output starts simultaneously with this setting, so this function drives the motor.

Example

#include <PhpocExpansion.h>
#include <Phpoc.h>

byte spcId = 1;

ExpansionDCMotor dcmotor(spcId, 1);

int width = 3000;

void setup() {
    Serial.begin(9600);
    while(!Serial)
    ;

    Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
    Expansion.begin();

    Serial.println(dcmotor.getPID());
    Serial.println(dcmotor.getName());

    dcmotor.setPeriod(10000);
    dcmotor.setWidth(width);
}

void loop() {
    if(width > 0) {
        width -= 100;
        dcmotor.setWidth(width);
        delay(100);
    }
}

Other Functions

Setting a PWM Polarity

Set a PWM polarity by using setPolarity() function.

dcmotor.setPolarity(pol);

Setting a Direction of Rotation

Set a direction of rotation by using setDirection() function.

dcmotor.setDirection(dir);

※ Note : The direction of rotation is affected by both direction of rotation and PWM polarity.

PWM polarity value direction of rotation value actual direction of rotation
normal forward clockwise
normal reverse counterclockwise
reverse forward counterclockwise
reverse reverse clockwise

Setting Decay Mode

Set decay mode by using setDecay() function.

dcmotor.setDecay(decay)