For loops are one of the two types of loops we can use in MicroPython, and are designed to be looped a set and known amount of times, executing the code placed inside of them on every loop. In this video we will be learning how to use the loop function in conjunction with the range function to loop over a range of numbers, and lists to loop over a custom range of numbers or strings.

Transcript

In this video we'll go over using For Loops and Lists with the Raspberry Pi Pico. This is part of a larger Raspberry Pi Pico Workshop where we learn how to use the Pico, from zero to hero.

Loops control the flow of code and there are only two types of loops, while loops which we'll learn next video and for loops which we will look at now. Both of these loops behave very similarly, but there is a slight yet important difference in how they do so.

A for loop runs code that we place inside of it over and over, and we typically use them when we know how many times we want that loop to run. That's the important distinction there on the end. They usually run for a known and predetermined amount of times.

For example, let's say we wanted to flash an LED off and on five times. Here I have the code to flash it on and off once, and then here is a for loop that will execute the code inside of it five times and our LED will flash five times.

So we have the for keyword followed by a variable that we will use to count through the loops, the in keyword, which is part of this for structure, followed by range five, which creates a sequence of five numbers in a row. And the result of this is that the loop will execute the code five times here.

To help see what's going on here, I've created this loop that just prints the variable I as it goes through each iteration of its loop. And as you can see, it prints off 10 numbers counting up. This might not behave exactly as you think because this is zero indexed, meaning that it will start counting at zero and not one. So keep an eye out for that. It's just how the range function works. And computers and code and software like this kind of like starting at zero when we in the real world like to start counting at one.

So we can create a simple loop that runs the code inside of it for the amount of times we put in the brackets. But that variable inside of the brackets is changing each loop, and we can use that to perform tasks iteratively.

Before we dive into that, we're going to learn how to more finely use that range function. Besides just choosing how many times it loops, we could also specify a number to start counting it by placing it at the start of the brackets like so. So here it's going to start counting at one and end at nine. And we do have an issue here relating to the zero indexing. The reason it doesn't print to 10, even though we've got it in the brackets here, is because this range function generates the numbers up to, but not including the number on the end. So if we wanted to count from one to 10, we would need to specify one and 11. This can be a little annoying sometimes, but it's just something we got to get used to with MicroPython.

We can also choose how much we want the loop to increase by, by placing it on the end of the brackets there. For example, this code starts at zero, ends at 100 or 99 technically, and counts by eight every single loop.

Now we're equipped to use loops in a bread and butter application called a servo sweep. Let's say we wanted to use a servo and we set it to zero degrees and then 180-degrees. When we do this, the servo will rotate as fast as it can between those two positions. But what if we wanted to control how fast it rotates, or maybe try and make that motion a little bit smoother? Well, that's what we're going to do by changing the angle of the servo bit by bit with a for loop.

Here's the sample code for that, and it can be found on our course page on our website, link in the description for our YouTube audience. We will be using the MicroPython servo library, so you will need that installed if you haven't already done so. And you'll need to connect your nine gram servo to your Pico with the signal wire in GPIO zero and powering it off of Vbus.

So here we are using a for loop with a bit of a modified range. We're going to start at zero degrees and go all the way to 180-degrees, taking steps of five, so zero, five, 10, 15. Then in the for loop, we're going to set the angle of the servo to the variable I, and then we're going to wait 0.1 seconds before we go to the next iteration of the loop. This will make the servo sweep smoothly from zero to 180-degrees.In the code snippet, we use the variable, which we called angle, and use it to set the angle on the servo. Then, we have a quick sleep every cycle to help control the speed of the rotation. Once the loop has finished counting to 180, another loop starts at 180 and goes to zero in steps of negative five. It's the exact same process, but in reverse. When the servo is rotated, it sweeps from one side to the other in a somewhat controlled fashion. However, it could be smoother by reducing the step size and adjusting the sleep time.

It's important to note that the range function can only take a whole integer, meaning numbers with decimal points cannot be used. Creating smooth motions with for loops is a powerful tool, especially for anything PWM related. For example, an RGB LED uses for loops to cycle through all of its colours smoothly.

Lists are a crucial data structure that allows the storage of a collection of variables. They are zero-indexed, meaning the first element in the list is accessed using index zero. Changing an element in a list follows a similar process. Lists pair well with for loops, as they can be cycled through to access and manipulate each element.

Key takeaways from the discussion are: for loops typically run for a known or predetermined amount of times, the range function can control the number of loops or specify the start, end point, and step size, and lists can be used to store a collection of variables and manually iterate through them in a for loop.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.