DEV Community

Cover image for Using pyboard to control two DC motors
Halldor Stefansson
Halldor Stefansson

Posted on • Originally published at halldorstefans.com

Using pyboard to control two DC motors

This is part three in my series of building a small robot car. You can find the previous articles below:

Part One: First Steps Creating a Robot with MicroPython and Pyboard

Part Two: My First Arduino Built Robot Car

I ended the last part wondering whether I should add some sensors to my robot, or replace the Arduino controller for a pyboard controller.

Because my initial idea for this project was to use the pyboard, I decided I would start by replacing the controller and then later I could add some sensors.

Updating pyboard firmware

I've owned the pyboard for a few years now, but I've never really done much with it. I, therefore, suspected that the firmware might be out of date. So, the first item on the list was to update the firmware.

The documentation for this is excellent, but I did run into a minor problem because I kept downloading the firmware for pyboard v1.0, but I had v1.1. Once I figured that out, it was quick and easy.

Running one motor

Once the pyboard was up to date, it was time to find out how to control one of the DC motors with it.

After a bit of research, I found this article. Using that and the offical documentation for PWM, my initial code in micropython looked like this:

from pyb import Pin, Timer

p1 = Pin('X1')
tim2 = Timer(2, freq=1000)
ch1 = tim2.channel(1, Timer.PWM, pin=p1)
ch1.pulse_width_percent(50)
Enter fullscreen mode Exit fullscreen mode

And this is how I connected it together, with the Maker Drive:

Maker-Drive and pyboard layout

And this worked perfectly!

Adding the second motor

Based on the fact that I was using the X1 and X2 pins to run the first motor, and the layout, I reckoned I could use the X3 and X4 pins for the second motor.

So after adding the second motor, I made some changes to the code:

from pyb import Pin, Timer

p1 = Pin('X1')
tim2 = Timer(2, freq=1000)
ch1 = tim2.channel(1, Timer.PWM, pin=p1)
ch1.pulse_width_percent(50)

p3 = Pin('X3')
ch3 = tim2.channel(1, Timer.PWM, pin=p3)
ch3.pulse_width_percent(50)
Enter fullscreen mode Exit fullscreen mode

And voila! Both motors were running. What a beauty!

Final touches

Once everything was working correctly, I put it together with the chassis and updated the code a bit to make it drive into a kind of a circle :D

You can see the current code and setup on my GitHub.

I'm really pleased how well this went and honestly thought it would take longer.

I'm going to put this project on to the side for a bit now. But the next item on the agenda for this project is to add some sensors to it and make them influence the driving.


Thank you for reading. For weekly updates from me, you can sign up to my newsletter.

Top comments (0)