{"id":146332,"date":"2024-05-22T16:59:29","date_gmt":"2024-05-22T16:59:29","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=146332"},"modified":"2024-05-23T13:47:06","modified_gmt":"2024-05-23T13:47:06","slug":"raspberry-pi-pico-stepper-motor-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-stepper-motor-micropython\/","title":{"rendered":"Raspberry Pi Pico: Control a Stepper Motor with MicroPython"},"content":{"rendered":"\n<p>In this guide, you\u2019ll learn how to control a stepper motor with the Raspberry Pi Pico. We\u2019ll use the 28BYJ-48 unipolar stepper motor with the ULN2003 motor driver. You&#8217;ll learn how to wire it to the Raspberry Pi Pico and how to control it using a MicroPython module.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Control a Stepper Motor MicroPython 28BYJ-48 unipolar ULN2003 motor driver\" class=\"wp-image-155676\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclblue\"><strong>New to the Raspberry Pi Pico?<\/strong>&nbsp;Read the following guide:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\">Getting Started with Raspberry Pi Pico (and Pico W)<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<p>Throughout this tutorial, we\u2019ll cover the following contents:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#introducing-stepper-motors\" title=\"\">Introducing Stepper Motors<\/a>\n<ul class=\"wp-block-list\">\n<li><a href=\"#28BYJ-48-Stepper-Motor\" title=\"\">28BYJ-48 Stepper Motor<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><a href=\"#ULN2003-Motor-Driver\" title=\"\">ULN2003 Motor Driver<\/a><\/li>\n\n\n\n<li><a href=\"#Wiring-the-Stepper-Motor-to-the-Raspberry-Pi-Pico\" title=\"\">Wiring the Stepper Motor to the Raspberry Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"#stepper-motor-library-micropython\" title=\"\">MicroPython Library for the Stepper Motor<\/a><\/li>\n\n\n\n<li><a href=\"#control-stepper-motor-micropython-code\" title=\"\">Controlling the Stepper Motor \u2013 MicroPython Code<\/a><\/li>\n<\/ul>\n\n\n\n<p class=\"rntbox rntclgreen\"><strong>Our Raspberry Pi Pico eBook<\/strong>:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\">Learn Raspberry Pi Pico\/Pico W with MicroPython<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing, make sure you follow the next prerequisites.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"prerequisites\">MicroPython Firmware<\/h3>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"250\" height=\"250\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?resize=250%2C250&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"micorpython logo\" class=\"wp-image-148797\" style=\"width:151px;height:auto\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?w=250&amp;quality=100&amp;strip=all&amp;ssl=1 250w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?resize=150%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 150w\" sizes=\"(max-width: 250px) 100vw, 250px\" \/><\/figure><\/div>\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\" title=\"\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<p>Alternatively, if you like programming using VS Code, you can start with the following tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-vs-code-micropython\/\">Programming Raspberry Pi Pico with VS Code and MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>You&#8217;ll also need the following parts:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-With-Stepper-Motor.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Stepper Motor ULN2003\" class=\"wp-image-146334\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-With-Stepper-Motor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-With-Stepper-Motor.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/28byj-48-stepper-motor-uln2003\/\" target=\"_blank\" rel=\"noreferrer noopener\">28BYJ-48 Stepper Motor + ULN2003 Motor Driver<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/4x-aa-battery-holder\/\" target=\"_blank\" rel=\"noopener\" title=\"\">4xAA battery pack or any other power source (between 5V to 12V)<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"introducing-stepper-motors\">Introducing Stepper Motors<\/h2>\n\n\n\n<p>A stepper motor is a brushless DC electric motor that divides a full rotation into a number of steps. It moves one step at a time, and each step is the same size. This allows us to rotate the motor at a precise angle to a precise position. The stepper motor can rotate clockwise or counterclockwise.<\/p>\n\n\n\n<p>The following picture shows two 28BYJ-48 stepper motors.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-Stepper-Motors.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"28BYJ-48 Stepper Motors\" class=\"wp-image-105431\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-Stepper-Motors.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-Stepper-Motors.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Stepper motors are made of internal coils that make the motor shaft move in steps in one direction or the other when current is applied to the coils in a specific way. There are two types of stepper motors: unipolar and bipolar stepper motors. We won\u2019t go into detail how the stepper motors are made or how they work internally.<\/p>\n\n\n\n<p>To learn in more detail how they work and the differences between each type of stepper motor, we recommend reading this article by the&nbsp;<a href=\"https:\/\/dronebotworkshop.com\/stepper-motors-with-arduino\/\" target=\"_blank\" rel=\"noreferrer noopener\">DroneBotWorkshop blog<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"28BYJ-48-Stepper-Motor\">28BYJ-48 Stepper Motor<\/h2>\n\n\n\n<p>There are several stepper motors with different specifications. We\u2019ll use the used&nbsp;28BYJ-48 unipolar stepper motor&nbsp;with the&nbsp;ULN2003 motor driver, which is a combination widely used by DIY and electronics hobbyists.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-connected-to-ULN2003-Motor-Driver-01-module.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"28BYJ-48 connected to ULN2003 Motor Driver 01 module\" class=\"wp-image-105430\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-connected-to-ULN2003-Motor-Driver-01-module.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-connected-to-ULN2003-Motor-Driver-01-module.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">28BYJ-48 Stepper Motor Features<\/h3>\n\n\n\n<p>Features of the stepper motor (for more details, consult the datasheet):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Rated voltage: 5V DC<\/li>\n\n\n\n<li>Number of phases: 4<\/li>\n\n\n\n<li>Speed variation ratio: 1\/64<\/li>\n\n\n\n<li>Stride angle: 5.625\u00ba\/64<\/li>\n\n\n\n<li>Frequency: 100Hz<\/li>\n<\/ul>\n\n\n\n<p>The 28BYJ-48 stepper motor has a total of four coils. One end of the coils is connected to 5V, which corresponds to the motor\u2019s red wire. The other end of the coils corresponds to the wires with blue, pink, yellow, and orange colors. Energizing the coils in a logical sequence makes the motor move one step in one direction or the other.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"704\" height=\"434\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-stepper-motor-coils.png?resize=704%2C434&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"28BYJ-48 stepper motor coils\" class=\"wp-image-105372\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-stepper-motor-coils.png?w=704&amp;quality=100&amp;strip=all&amp;ssl=1 704w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/28BYJ-48-stepper-motor-coils.png?resize=300%2C185&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 704px) 100vw, 704px\" \/><\/figure><\/div>\n\n\n<p>The 28BYJ-48 Stepper Motor has a stride angle of 5.625\u00b0\/64 in half-step mode. This means that the motor has a step angle of 5.625\u00ba\u2014so it needs 360\u00ba\/5.625\u00ba = 64 steps in half-step mode. In full-step mode: 64\/2 = 32 steps to complete one rotation.<\/p>\n\n\n\n<p>However, the output shaft is driven via a 64:1 gear ratio. This means that the shaft (visible outside the motor) will complete a rotation if the motor inside rotates 64 times. This means that the motor will have to move 32\u00d764 = 2048 steps for the shaft to complete one full rotation. This means that you\u2019ll have a precision of 360\u00ba\/2048 steps = 0.18\u00ba\/step.<\/p>\n\n\n\n<p>So, in summary:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Total steps per revolution = 2048 steps<\/li>\n\n\n\n<li>Step angle = 0.18\u00ba\/step<\/li>\n<\/ul>\n\n\n\n<p>If you\u2019re using a different stepper motor, please consult the datasheet.<\/p>\n\n\n\n<p>Don\u2019t worry if this seems confusing. There are libraries that make programming easier without having to worry about those numbers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ULN2003-Motor-Driver\">ULN2003 Motor Driver<\/h2>\n\n\n\n<p>To interface the stepper motor with the Raspberry Pi Pico, we\u2019ll use the ULN2003 motor driver, as shown in the figure below. The 28BYJ-48 stepper motor is many times sold together with the ULN2003 motor driver as a bundle.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01-module-board.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ULN2003 Motor Driver 01 module board\" class=\"wp-image-105429\" style=\"width:750px;height:auto\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01-module-board.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01-module-board.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>The module comes with a connector that makes it easy and simple to connect the motor to the module. It has four input pins to control the coils that make the stepper motor move. The four LEDs provide a visual interface of the coils\u2019 state.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"429\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01.png?resize=750%2C429&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ULN2003 Motor Driver Labels\" class=\"wp-image-105359\" style=\"width:752px;height:auto\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/07\/ULN2003-Motor-Driver-01.png?resize=300%2C172&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">ULN2003 Motor Driver Pinout<\/h3>\n\n\n\n<p>The following table shows the module pinout:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>IN1<\/strong><\/td><td>Control the motor: connect to a Pico digital pin<\/td><\/tr><tr><td><strong>IN2<\/strong><\/td><td>Control the motor: connect to a Pico digital pin<\/td><\/tr><tr><td><strong>IN3<\/strong><\/td><td>Control the motor: connect to a Pico digital pin<\/td><\/tr><tr><td><strong>IN4<\/strong><\/td><td>Control the motor: connect to a Pico digital pin<\/td><\/tr><tr><td><strong>VCC<\/strong><\/td><td>Powers the motor<\/td><\/tr><tr><td><strong>GND<\/strong><\/td><td>Common GND<\/td><\/tr><tr><td><strong>Motor connector<\/strong><\/td><td>Connect the motor connector wire<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"Wiring-the-Stepper-Motor-to-the-Raspberry-Pi-Pico\">Wiring the Stepper Motor to the Raspberry Pi Pico<\/h2>\n\n\n\n<p>Let\u2019s connect the stepper motor to the Raspberry Pi Pico via the ULN2003 motor driver. We\u2019ll connect IN1, IN2, IN3, and IN4 to GPIOs <strong>28<\/strong>, <strong>27<\/strong>, <strong>26<\/strong>, and <strong>22<\/strong>, respectively. You can use any other digital pins as long as you indicate the pins you\u2019re using on the code.<\/p>\n\n\n\n<p class=\"rntbox rntclblue\"><strong>Recommended reading<\/strong>: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" title=\"\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a>.<\/p>\n\n\n\n<p>You can follow the next schematic diagram. Or use the table below as a reference.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"1249\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Wiring-Raspberry-Pi-Pico-Stepper-Motor.png?resize=1200%2C1249&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Wiring the Stepper Motor to the Raspberry Pi Pico\" class=\"wp-image-146333\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Wiring-Raspberry-Pi-Pico-Stepper-Motor.png?w=1215&amp;quality=100&amp;strip=all&amp;ssl=1 1215w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Wiring-Raspberry-Pi-Pico-Stepper-Motor.png?resize=288%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 288w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Wiring-Raspberry-Pi-Pico-Stepper-Motor.png?resize=984%2C1024&amp;quality=100&amp;strip=all&amp;ssl=1 984w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Wiring-Raspberry-Pi-Pico-Stepper-Motor.png?resize=768%2C800&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p><strong>Note:&nbsp;you should power the motor driver using an external power supply between 5 to 12V. We\u2019re using 6.5V provided by a battery pack.<\/strong><\/p>\n\n\n\n<p><strong>The GND pin of the battery pack should also be connected to one GND pin of the Raspberry Pi Pico.<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Motor Driver ULN2003<\/strong><\/td><td><strong>Raspberry Pi Pico<\/strong><\/td><\/tr><tr><td>IN1<\/td><td>GPIO 28<\/td><\/tr><tr><td>IN2<\/td><td>GPIO 27<\/td><\/tr><tr><td>IN3<\/td><td>GPIO 26<\/td><\/tr><tr><td>IN4<\/td><td>GPIO 22<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"stepper-motor-library-micropython\">MicroPython Library for the Stepper Motor<\/h2>\n\n\n\n<p>There are several ways to control a stepper motor using a library. We\u2019ll use one that was done specifically for the 28BYJ-48 stepper motor controlled with the ULN2003 motor driver.<\/p>\n\n\n\n<p>Follow the next steps to upload the library to the Raspberry Pi Pico. <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a new file in Thonny IDE and copy the library code. The library code can be found below (or you <a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/stepper.py\" target=\"_blank\" rel=\"noopener\" title=\"\">can click on this link<\/a>).<\/li>\n\n\n\n<li>Go to&nbsp;<strong>File<\/strong>&nbsp;&gt;&nbsp;<strong>Save&nbsp;as<\/strong> and select&nbsp;<strong>Raspberry Pi Pico<\/strong>.<\/li>\n\n\n\n<li>Name the file&nbsp;<em>stepper.py<\/em>&nbsp;and click&nbsp;<strong>OK<\/strong>&nbsp;to save the file on the Raspberry Pi Pico.<\/li>\n<\/ol>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-stepper-motor-micropython\/\r\n# Forked from: https:\/\/github.com\/larsks\/micropython-stepper-motor\/blob\/master\/motor.py\r\n\r\nimport machine\r\nimport time\r\n\r\nclass Motor:\r\n    stepms = 10\r\n\r\n    # Do be defined by subclasses\r\n    maxpos = 0\r\n    states = []\r\n\r\n    def __init__(self, p1, p2, p3, p4, stepms=None):\r\n        self.pins = [p1, p2, p3, p4]\r\n\r\n        if stepms is not None:\r\n            self.stepms = stepms\r\n\r\n        self._state = 0\r\n        self._pos = 0\r\n\r\n    def __repr__(self):\r\n        return '&lt;{} @ {}&gt;'.format(\r\n            self.__class__.__name__,\r\n            self.pos,\r\n        )\r\n\r\n    @property\r\n    def pos(self):\r\n        return self._pos\r\n\r\n    @classmethod\r\n    def frompins(cls, *pins, **kwargs):\r\n        return cls(*[machine.Pin(pin, machine.Pin.OUT) for pin in pins],\r\n                   **kwargs)\r\n\r\n    def reset(self):\r\n        self._pos = 0\r\n\r\n    def _step(self, dir):\r\n        state = self.states[self._state]\r\n\r\n        for i, val in enumerate(state):\r\n            self.pins[i].value(val)\r\n\r\n        self._state = (self._state + dir) % len(self.states)\r\n        self._pos = (self._pos + dir) % self.maxpos\r\n\r\n    def step(self, steps):\r\n        dir = 1 if steps &gt;= 0 else -1\r\n        steps = abs(steps)\r\n\r\n        for _ in range(steps):\r\n            t_start = time.ticks_ms()\r\n\r\n            self._step(dir)\r\n\r\n            t_end = time.ticks_ms()\r\n            t_delta = time.ticks_diff(t_end, t_start)\r\n            time.sleep_ms(self.stepms - t_delta)\r\n\r\n    def step_until(self, target, dir=None):\r\n        if target &lt; 0 or target &gt; self.maxpos:\r\n            raise ValueError(target)\r\n\r\n        if dir is None:\r\n            dir = 1 if target &gt; self._pos else -1\r\n            if abs(target - self._pos) &gt; self.maxpos\/2:\r\n                dir = -dir\r\n\r\n        while True:\r\n            if self._pos == target:\r\n                break\r\n            self.step(dir)\r\n\r\n    def step_until_angle(self, angle, dir=None):\r\n        if angle &lt; 0 or angle &gt; 360:\r\n            raise ValueError(angle)\r\n\r\n        target = int(angle \/ 360 * self.maxpos)\r\n        self.step_until(target, dir=dir)\r\n        \r\n    def step_degrees(self, degrees):\r\n        if degrees &lt; 0 or degrees &gt; 360:\r\n            raise ValueError(&quot;Degrees should be between 0 and 360&quot;)\r\n\r\n        steps_to_take = int(degrees \/ 360 * self.maxpos)\r\n\r\n        self.zero()  # Ignore the current position, start from zero\r\n        self.step(steps_to_take)\r\n\r\nclass FullStepMotor(Motor):\r\n    stepms = 5\r\n    maxpos = 2048\r\n    states = [\r\n        [1, 1, 0, 0],\r\n        [0, 1, 1, 0],\r\n        [0, 0, 1, 1],\r\n        [1, 0, 0, 1],\r\n    ]\r\n\r\n\r\nclass HalfStepMotor(Motor):\r\n    stepms = 3\r\n    maxpos = 4096\r\n    states = [\r\n        [1, 0, 0, 0],\r\n        [1, 1, 0, 0],\r\n        [0, 1, 0, 0],\r\n        [0, 1, 1, 0],\r\n        [0, 0, 1, 0],\r\n        [0, 0, 1, 1],\r\n        [0, 0, 0, 1],\r\n        [1, 0, 0, 1],\r\n    ]<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/stepper.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>And that\u2019s it. The library was uploaded to your board. Now, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"control-stepper-motor-micropython-code\">Controlling the Stepper Motor &#8211; MicroPython Code<\/h2>\n\n\n\n<p>The library we\u2019re using is very intuitive to use. The following code illustrates the different available methods.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-stepper-motor-micropython\/\r\n\r\nimport stepper\r\nfrom time import sleep\r\n\r\n# Define the stepper motor pins\r\nIN1 = 28\r\nIN2 = 27\r\nIN3 = 26\r\nIN4 = 22\r\n\r\n# Initialize the stepper motor\r\nstepper_motor = stepper.HalfStepMotor.frompins(IN1, IN2, IN3, IN4)\r\n\r\n# Set the current position as position 0\r\nstepper_motor.reset()\r\n\r\ntry:\r\n    while True:\r\n        #Move 500 steps in clockwise direction\r\n        stepper_motor.step(500)\r\n        sleep(0.5) # stop for a while\r\n        \r\n        # Move 500 steps in counterclockwise direction\r\n        stepper_motor.step(-500)\r\n        sleep(0.5) # stop for a while\r\n        \r\n        # Go to a specific position (in steps)\r\n        stepper_motor.step_until(2000)\r\n        sleep(0.5) # stop for a while\r\n        \r\n        # Force a direction using the dir paramter\r\n        stepper_motor.step_until(2000, dir=-1)\r\n        sleep(0.5) # stop for a while        \r\n        \r\n        # Go to a specific position (angle, maximum is 359, otherwise it will spin indefinetely)\r\n        stepper_motor.step_until_angle(359)\r\n        sleep(0.5) # stop for a while\r\n    \r\nexcept KeyboardInterrupt:\r\n    print('Keyboard interrupt')<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/Control_Stepper_Motor.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Let\u2019s take a quick look at how the code works to see the different methods provided by the library to control stepper motors.<\/p>\n\n\n\n<p>First, you need the <span class=\"rnthl rntliteral\">stepper<\/span> library you\u2019ve just uploaded to the Raspberry Pi Pico.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import stepper<\/code><\/pre>\n\n\n\n<p>Then, define the pins you\u2019re using to control the stepper motor via the ULN2003 motor driver. If you&#8217;re using different pins, modify the following lines:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Define the stepper motor pins\nIN1 = 28\nIN2 = 27\nIN3 = 26\nIN4 = 22<\/code><\/pre>\n\n\n\n<p>Then, initialize the stepper motor as follows (we\u2019re using a half-step motor, as explained previously).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Initialize the stepper motor\nstepper_motor = stepper.HalfStepMotor.frompins(IN1, IN2, IN3, IN4)<\/code><\/pre>\n\n\n\n<p>Before start moving the motor, we use the <span class=\"rnthl rntliteral\">reset()<\/span> method to tell the code that the stepper&#8217;s current position is position 0.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Set the current position as position 0\nstepper_motor.reset()<\/code><\/pre>\n\n\n\n<p>Then, we have a while loop where we move the motor using different methods.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    while True:<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">step()<\/span> method moves the motor by a number of steps in a clockwise direction. Pass as an argument the number of steps you want to move.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#Move 500 steps in clockwise direction\nstepper_motor.step(500)<\/code><\/pre>\n\n\n\n<p>You can also pass a negative number to move counterclockwise.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Move 500 steps in counterclockwise direction\nstepper_motor.step(-500)<\/code><\/pre>\n\n\n\n<p>If you want the motor to go to a specific position (counting from the position defined as zero), you can use the <span class=\"rnthl rntliteral\">step_until()<\/span> method and pass as an argument the step number.&nbsp;This method will find the shortest way to move the motor to a specific position.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Go to a specific position (in steps)\nstepper_motor.step_until(2000)<\/code><\/pre>\n\n\n\n<p>At any time during your code, you can call the <span class=\"rnthl rntliteral\">reset()<\/span> method to define a new reference point (position 0).<\/p>\n\n\n\n<p>You can pass an extra parameter to the <span class=\"rnthl rntliteral\">step_until()<\/span> method, the <span class=\"rnthl rntliteral\">dir<\/span> parameter. It can be <span class=\"rnthl rntliteral\">1<\/span> to force the motor to move in a clockwise direction, or <span class=\"rnthl rntliteral\">-1<\/span> to force the motor to go in a counterclockwise direction.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Force a direction using the dir parameter\nstepper_motor.step_until(2000, dir=-1)\nsleep(0.5) # stop for a while<\/code><\/pre>\n\n\n\n<p>Similarly, there\u2019s a method that does the same thing, but you can pass the position in degrees. <strong>Don&#8217;t pass 360<\/strong> as an argument, otherwise, the motor won&#8217;t stop moving.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>stepper_motor.step_until_angle(359)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the Code<\/h2>\n\n\n\n<p>Upload the previous code to your Raspberry Pi Pico and see the motor moving to different positions every half a second. Experiment with the different methods and pass different arguments to see how the motor behaves.<\/p>\n\n\n\n<div class=\"wp-block-jetpack-tiled-gallery aligncenter is-style-rectangular\"><div class=\"\"><div class=\"tiled-gallery__gallery\"><div class=\"tiled-gallery__row\"><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-control-stepper.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-control-stepper.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"\" data-height=\"422\" data-id=\"146340\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=146340#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-control-stepper.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-control-stepper.jpg?ssl=1\" data-amp-layout=\"responsive\"\/><\/figure><\/div><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-Control-Stepper-2.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-Control-Stepper-2.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"\" data-height=\"422\" data-id=\"146341\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=146341#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-Control-Stepper-2.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/Raspberry-Pi-Pico-Control-Stepper-2.jpg?ssl=1\" data-amp-layout=\"responsive\"\/><\/figure><\/div><\/div><\/div><\/div><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you&#8217;ve learned how to control a stepper motor with the Raspberry Pi Pico programmed with MicroPython. One of the most popular motors to use in DIY hobbyists&#8217; projects is the 28BYJ-48 unipolar stepper motor with the ULN2003 motor driver.<\/p>\n\n\n\n<p>If you want to interface other motors with the Raspberry Pi Pico, check the tutorials below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-dc-motor-micropython\/\">Raspberry Pi Pico: Control DC Motor with L298N Motor Driver (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-servo-motor-micropython\/\">Raspberry Pi Pico: Control a Servo Motor (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p><strong>Would you like to learn more about the Raspberry Pi Pico?<\/strong> Make sure you take a look at our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\"><strong>Learn Raspberry Pi Pico with MicroPython (eBook)<\/strong><\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\" title=\"\">Raspberry Pi Pico Tutorials and Guides<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you\u2019ll learn how to control a stepper motor with the Raspberry Pi Pico. We\u2019ll use the 28BYJ-48 unipolar stepper motor with the ULN2003 motor driver. You&#8217;ll learn &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: Control a Stepper Motor with MicroPython\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-stepper-motor-micropython\/#more-146332\" aria-label=\"Read more about Raspberry Pi Pico: Control a Stepper Motor with MicroPython\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":155676,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[324,326],"tags":[],"class_list":["post-146332","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/05\/Raspberry-Pi-Pico-Control-Stepper-Motor-Micropython.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/146332","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=146332"}],"version-history":[{"count":10,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/146332\/revisions"}],"predecessor-version":[{"id":155786,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/146332\/revisions\/155786"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/155676"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=146332"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=146332"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=146332"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}