5 years, 5 months ago.

Creating a motor controller class using PWM

I am trying to make a class that can control a motor, using 2 outputs on an mbed board. These outputs are connected to an H bridge. One output makes the motor go forward, the other output makes it go backwards. These can be PWM to change the speed.

The code below crashes and restarts the mbed every loop, when 'motorLeft.Forward()' or 'motorRightFoward()' are set to '1.0'. Weirdly it crashes less frequently the lower I set that value.

I think the problem is Motor's constructor. When I change it to have only one parameter 'Motor(PinName forwardPinInput) : forwardPin(forwardPinInput){}' , this fixes the issue. But I need the constructor to have two parameters.

Any ideas where this issue might be coming from?

include the mbed library with this snippet

    #include "mbed.h"

    class Motor
    {
    	public:
    		Motor(PinName forwardPinInput, PinName backwardPinInput) : forwardPin(forwardPinInput), backwardPin(backwardPinInput){}
    		PwmOut forwardPin;
    		PwmOut backwardPin;
    			
    		void Forward(float forwardInput)
    		{
    				forwardPin = forwardInput;
    				backwardPin = 0;
    		};	
    		
    		void Backward(float backwardInput)
    		{
    				forwardPin = 0;
    				backwardPin = backwardInput;
    		};	
    };
    
    Motor motorLeft(P0_9, P0_8);
    
    int main()
    {    
        while(1)
        {    		
    			//Set left motor to move forward at a speed
    			motorLeft.Forward(1.0);
    			wait(0.5);
    			
    			//Set left motor to move backward at a speed
    			motorLeft.Backward(0.5);
    			wait(0.5);
        }
    }

2 Answers

5 years, 5 months ago.

Fixed code, which takes no inputs like this, should either always crash or never crash if it is a software issue. Generally MCUs which reset when driving motors means there is an issue with the power supply: Preferably use a seperate power supply (with shorted grounds) for the mbed board and for the motors.

Accepted Answer
5 years, 5 months ago.

Stupid question (?)

does your code work when it is all in 'main.cpp'

Otherwise it is a power supply problem,

keep power cables Short. large PSU caps on driver PCB/Device, Noise suppression DIRECTLY across motor(s)

lots of decoupling caps .. 10n 100n 1uF 100+uF

Cheers

Ceri

Yep thanks, your guys were right. It was a power issue. Using a battery pack sorted it out .

posted by Magnus M 03 Mar 2015