diff --git a/content/micropython/03.micropython/01.basics/00. digital-io/digital-io.md b/content/micropython/03.micropython/01.basics/00. digital-io/digital-io.md index 97c833af67..c805563be2 100644 --- a/content/micropython/03.micropython/01.basics/00. digital-io/digital-io.md +++ b/content/micropython/03.micropython/01.basics/00. digital-io/digital-io.md @@ -1,14 +1,11 @@ --- - -featured: micropython-101 -title: '2. Micropython Basics - Digital I/O' -description: 'Learn the basics for loops on MicroPython.' +title: 'Digital I/O' +description: 'A guide to digital inputs and outputs using MicroPython.' author: 'Pedro Lima' -hero_image: "./hero-banner.png" - +tags: [MicroPython, Digital I/O] --- -Digital pins are fundamental for interacting with the physical world using your Arduino board. In this chapter, we'll explore how to use digital pins in MicroPython to: +Digital pins are fundamental for interacting with the physical world using your Arduino board. With them, you can: - Control outputs, such as turning an LED on and off. - Read inputs, like detecting the state of a button. @@ -20,29 +17,77 @@ Digital signals have two distinct values: Although they can only represent two states, digital signals are highly useful. Being binary in nature, they directly interface with microcontrollers and processors, making them ideal for tasks requiring fast, on/off communication, such as reading sensors or controlling simple outputs. Their simplicity also gives them a natural resilience to electrical noise, as noise only disrupts digital signals when it is strong enough to cross the threshold between HIGH and LOW states. This makes them reliable for clear, consistent communication in various environments. +In this chapter, we'll explore how to use digital pins in MicroPython. + +## Requirements + +Before we start, let's check the requirements: + +### MicroPython Compatible Arduino Boards + +MicroPython is officially supported on several Arduino boards. Here’s a list of the compatible boards: + +- [Portenta C33](https://store.arduino.cc/products/portenta-c33) +- [Arduino GIGA R1 WiFi](https://store.arduino.cc/products/arduino-giga-r1-wifi) +- [Portenta H7](https://store.arduino.cc/products/portenta-h7) +- [Portenta H7 Lite](https://store.arduino.cc/products/portenta-h7-lite) +- [Portenta H7 Lite Connected](https://store.arduino.cc/products/portenta-h7-lite-connected) +- [Opta](https://store.arduino.cc/products/opta) +- [Opta Wifi](https://store.arduino.cc/products/opta-wifi) +- [Opta RS485](https://store.arduino.cc/products/opta-rs485) +- [Arduino Nano RP2040 Connect](https://store.arduino.cc/products/arduino-nano-rp2040-connect) +- [Nicla Vision](https://store.arduino.cc/products/nicla-vision) +- [Arduino Nano 33 BLE](https://store.arduino.cc/products/arduino-nano-33-ble) +- [Arduino Nano 33 BLE Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-rev2) +- [Arduino Nano 33 BLE Sense](https://store.arduino.cc/products/arduino-nano-33-ble-sense) +- [Arduino Nano 33 BLE Sense Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-sense-rev2) +- [Arduino Nano ESP32](https://store.arduino.cc/products/arduino-nano-esp32) + +### Hardware Components + +In this guide, we will be using some additional electronic components: +- LEDs (optional if using the onboard LED) +- Current-limiting resistor (e.g. 220Ω) if using an external LED +- Jumper wires +- Pushbutton +- Breadboard + +### Software Requirements + +- [Arduino Lab for Micropython](https://labs.arduino.cc/en/labs/micropython) - Arduino Lab for MicroPython is an editor where we can create and run MicroPython scripts on our Arduino board. + +***Note that the editor is also available online, at [Arduino Cloud - Arduino Labs for MicroPython](https://lab-micropython.arduino.cc/)*** + +## Board and Editor Setup + +1. Open the [Arduino Lab for MicroPython]() application. +2. Plug the Arduino board into the computer using a USB cable. + ![Connect board to computer.]() +3. Press the connection button on the top left corner of the window. + ![Connect the editor to the board.]() +4. The connected Arduino board should appear, and we can click it: + ![Select board.]() + +***Need help installing MicroPython on your board? Visit the [MicroPython installation guide]().*** + ## Digital Outputs To control digital outputs in MicroPython, we use the `Pin` class from the `machine` module. Setting a pin as an output allows you to control devices like LEDs, relays, or other actuators. -### Code Example: Blinking an LED - Let's create the classic "Blink" example, where we turn an LED on and off at regular intervals. -**Components Needed:** +### Circuit Diagram -- Arduino board compatible with MicroPython -- LED (optional if using the onboard LED) -- Current-limiting resistor (e.g., 220Ω) if using an external LED -- Jumper wires +Connect an LED to the Arduino board, following the circuit diagram below: + +- Connect the anode (+) of the LED to a digital output pin. +- Connect the cathode (-) of the LED through a resistor to `GND`. -**Circuit Diagram:** +![LED circuit.]() -- **Onboard LED**: Many Arduino boards have an onboard LED connected to a specific pin. -- **External LED**: - - Connect the anode (+) of the LED to a digital output pin. - - Connect the cathode (-) of the LED through a resistor to `GND`. +***You can also use the built-in LED on your board, if you do not have an external LED.*** -**MicroPython Code:** +After completing the circuit diagram, copy the following code into your editor, and run the script. ```python from machine import Pin @@ -61,15 +106,15 @@ while True: time.sleep(1) # Wait for 1 second ``` -**Explanation:** +Let's take a look at what's included in this code example: - **Import Modules**: We import `Pin` from `machine` and `time` for delays. -- **Initialize LED Pin**: Create a `Pin` object, setting the pin number and direction (`Pin.OUT`). +- **Initialize LED Pin**: with the `Pin` object, we set the pin number and direction (`Pin.OUT`). - **Main Loop**: - - `led.value(1)`: Sets the pin to HIGH, turning the LED on. - - `time.sleep(1)`: Pauses the program for 1 second. - - `led.value(0)`: Sets the pin to LOW, turning the LED off. - - The loop repeats indefinitely, causing the LED to blink. + - `led.value(1)` - Sets the pin to HIGH, turning the LED on. + - `time.sleep(1)` - Pauses the program for 1 second. + - `led.value(0)` - Sets the pin to LOW, turning the LED off. + - `while True:` - The loop repeats indefinitely, causing the LED to blink. @@ -77,6 +122,8 @@ while True: Reading digital inputs allows your program to respond to external events, like button presses or sensor signals. In MicroPython, we use the `Pin` class to set up pins as inputs, and we can specify pull modes to stabilize the input readings. +In this section, we will explain the different pull modes, and then try them out, by connecting a **pushbutton** to the Arduino. + ### Understanding Pull Modes When a digital input pin is not connected to a definite HIGH or LOW voltage, it is said to be "floating," which can result in unreliable readings due to electrical noise. To prevent this, we use internal pull-up or pull-down resistors, activated by specifying the pull mode in the `Pin` constructor. @@ -88,40 +135,16 @@ These internal resistors are built into the microcontroller and can be enabled i ![We can create a image here to explain that]() - - -### Pull-Up Mode +### Example: Pull-Up Mode In pull-up mode, the input pin is internally connected to a HIGH voltage level. When the input device (like a button) is activated and connects the pin to GND, the pin reads LOW (`0`). -**Circuit Diagram for Pull-Up Mode:** - - Connect one side of the button to **GND**. - Connect the other side to a digital input pin. -![Demo]() TODO: Show Schematic - -### Pull-Down Mode - -In pull-down mode, the input pin is internally connected to GND. When the input device is activated and connects the pin to a HIGH voltage level (e.g., 3.3V), the pin reads HIGH (`1`). - -**Circuit Diagram for Pull-Down Mode:** - -- Connect one side of the button to **3.3V** (or **5V**, depending on your board's logic level). -- Connect the other side to a digital input pin. - -![Demo]() TODO: Show Schematic - +![Pull-up mode circuit.]() -### Code Example: Reading a Button with Pull-Up Mode - -**Components Needed:** - -- Arduino board compatible with MicroPython -- Push-button switch -- Jumper wires - -**MicroPython Code:** +After completing the circuit diagram, copy the following code into your editor, and run the script. ```python from machine import Pin @@ -139,7 +162,7 @@ while True: time.sleep(0.1) ``` -**Explanation:** +Let's take a look at what's included in this code example: - **Initialize Button Pin**: - We set up the pin as an input with a pull-up mode (`Pin.PULL_UP`), enabling the internal pull-up resistor. @@ -151,17 +174,16 @@ while True: - Reads the button state and prints a message accordingly. - A short delay helps debounce the button. +### Example: Pull-Down Mode +In pull-down mode, the input pin is internally connected to GND. When the input device is activated and connects the pin to a HIGH voltage level (e.g., 3.3V), the pin reads HIGH (`1`). -### Code Example: Reading a Button with Pull-Down Mode - -**Components Needed:** +- Connect one side of the button to **3.3V** (or **5V**, depending on your board's logic level). +- Connect the other side to a digital input pin. -- Arduino board compatible with MicroPython -- Push-button switch -- Jumper wires +![Pull-down mode circuit.]() -**MicroPython Code:** +After completing the circuit diagram, copy the following code into your editor, and run the script. ```python from machine import Pin @@ -179,7 +201,7 @@ while True: time.sleep(0.1) ``` -**Explanation:** +Let's take a look at what's included in this code example: - **Initialize Button Pin**: - We set up the pin as an input with a pull-down mode (`Pin.PULL_DOWN`), enabling the internal pull-down resistor. @@ -191,3 +213,9 @@ while True: - Reads the button state and prints a message accordingly. - A short delay helps debounce the button. +## Summary + +In this guide, we have looked at different ways of interacting with digital pins on an Arduino, using MicroPython: +- How to use digital outputs (turning on/off an LED) +- How the different pull modes work (`PULL_DOWN`, `PULL_UP`) +- How to read a button press using either pull modes. \ No newline at end of file diff --git a/content/micropython/03.micropython/01.basics/01. analog-io/analog-io.md b/content/micropython/03.micropython/01.basics/01. analog-io/analog-io.md index 35e2d889df..1de1aeca36 100644 --- a/content/micropython/03.micropython/01.basics/01. analog-io/analog-io.md +++ b/content/micropython/03.micropython/01.basics/01. analog-io/analog-io.md @@ -1,54 +1,95 @@ --- - -featured: micropython-101 -title: '2. Micropython Basics - Analog I/O' -description: 'Learn the fundamentals of analog I/O with MicroPython for smooth signal interactions.' -author: 'Pedro Lima' -hero_image: "./hero-banner.png" - +title: 'Analog I/O' +description: 'A guide to analog inputs (ADC) and outputs (PWM) using MicroPython.' +author: 'Pedro Lima' +tags: [MicroPython, Analog I/O] --- -Analog inputs and outputs are essential for handling a range of values rather than simple on/off states, allowing for more nuanced control over devices and inputs in your projects. In this chapter, we’ll cover how to work with analog I/O using MicroPython, focusing on how to: +Analog inputs and outputs (I/O) are essential for handling a range of values rather than simple on/off states, allowing for more nuanced control over devices and inputs in your projects. In this chapter, we’ll cover how to work with analog I/O using MicroPython, focusing on how to: - Read analog values, such as a light sensor or potentiometer. -- Generate analog outputs, like controlling LED brightness or motor speed. +- Generate analog outputs, like controlling LED brightness or the speed of a motor. Analog signals differ from digital signals in that they represent a continuous range of values. This flexibility enables more refined interactions with the physical world, making analog I/O indispensable for many types of sensors and actuators. -## Analog Inputs +## Requirements -To read analog values as microcontrollers work on a binary system, we typically use the `ADC` (Analog-to-Digital Converter) class. Analog inputs measure voltage levels that range continuously between two values, often 0V (LOW) and the board's operating voltage, like 3.3V or 5V. -Analog signals allow you to interact with the world more fluidly by capturing gradual changes rather than absolute states. This flexibility is ideal for applications like environmental sensing, variable speed control, and responsive lighting. -Analog sensors output a range of voltages to reflect changes in physical conditions. By converting these values into digital numbers, your Arduino board can interpret real-world signals, such as light intensity or temperature. +Before we start, let's check the requirements: -## PWM - Pulse Width Modulation +### MicroPython Compatible Arduino Boards -In microcontrollers, **Pulse Width Modulation (PWM)** is essential for creating the appearance of analog output. True analog signals involve a continuous voltage range, but since microcontrollers primarily handle digital signals (on or off), PWM bridges the gap by rapidly switching the signal between HIGH and LOW. By adjusting the time the signal remains in the HIGH state (known as the "duty cycle"), PWM simulates varying voltage levels. +MicroPython is officially supported on several Arduino boards. Here’s a list of the compatible boards: -PWM is especially useful in applications where true analog output is not possible but smooth transitions are necessary. Common scenarios include: +- [Portenta C33](https://store.arduino.cc/products/portenta-c33) +- [Arduino GIGA R1 WiFi](https://store.arduino.cc/products/arduino-giga-r1-wifi) +- [Portenta H7](https://store.arduino.cc/products/portenta-h7) +- [Portenta H7 Lite](https://store.arduino.cc/products/portenta-h7-lite) +- [Portenta H7 Lite Connected](https://store.arduino.cc/products/portenta-h7-lite-connected) +- [Opta](https://store.arduino.cc/products/opta) +- [Opta Wifi](https://store.arduino.cc/products/opta-wifi) +- [Opta RS485](https://store.arduino.cc/products/opta-rs485) +- [Arduino Nano RP2040 Connect](https://store.arduino.cc/products/arduino-nano-rp2040-connect) +- [Nicla Vision](https://store.arduino.cc/products/nicla-vision) +- [Arduino Nano 33 BLE](https://store.arduino.cc/products/arduino-nano-33-ble) +- [Arduino Nano 33 BLE Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-rev2) +- [Arduino Nano 33 BLE Sense](https://store.arduino.cc/products/arduino-nano-33-ble-sense) +- [Arduino Nano 33 BLE Sense Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-sense-rev2) +- [Arduino Nano ESP32](https://store.arduino.cc/products/arduino-nano-esp32) -- **LED Dimming**: PWM allows for adjusting brightness levels by controlling how long the LED is ON versus OFF within a given time frame. -- **Motor Control**: By modifying the duty cycle, PWM can control the speed of motors for robotics or other mechanical devices, as the motor responds to the average power supplied over time. -- **Audio Signals**: Some sound applications also use PWM to generate varying sound frequencies or control speaker volume. +### Hardware Components -The main advantage of PWM is that it allows you to control analog-like behavior using digital pins, adding versatility to your projects while keeping power consumption efficient. +In this guide, we will be using some additional electronic components: +- LEDs +- Current-limiting resistor (e.g. 220Ω) if using an external LED +- Jumper wires +- Breadboard + +### Software Requirements + +- [Arduino Lab for Micropython](https://labs.arduino.cc/en/labs/micropython) - Arduino Lab for MicroPython is an editor where we can create and run MicroPython scripts on our Arduino board. + +***Note that the editor is also available online, at [Arduino Cloud - Arduino Labs for MicroPython](https://lab-micropython.arduino.cc/)*** + +## Board and Editor Setup + +1. Open the [Arduino Lab for MicroPython]() application. +2. Plug the Arduino board into the computer using a USB cable. + ![Connect board to computer.]() +3. Press the connection button on the top left corner of the window. + ![Connect the editor to the board.]() +4. The connected Arduino board should appear, and we can click it: + ![Select board.]() + +***Need help installing MicroPython on your board? Visit the [MicroPython installation guide]().*** + +## Analog Inputs + +Analog input signals allow you to interact with the world more fluidly by capturing gradual changes rather than absolute states. Analog sensors output a range of voltages to reflect changes in physical conditions. By converting these values into digital numbers, your Arduino board can interpret real-world signals, and convert them into known properties, such as light intensity or temperature. + +### Analog-to-Digital Converter (ADC) + +To read analog values, we use an Analog-to-Digital Converter (ADC). This takes an input voltage, and converts it to a digital value, that can then be used by the Arduino. Analog inputs measure voltage levels that range continuously between two values, often 0V (LOW) and the board's operating voltage, like 3.3V or 5V. -TODO: ILLUSTRATE THIS PWM MAGIC +Using MicroPython, we use a specific method to access the ADC: `read_u16()`. The "16" indicates a 16-bit resolution, which means we can capture a range between 0-65535\*. + +***\*What does a 16-bit resolution mean? Find out at the [end of this article](#analog-resolution).*** ### Code Example: Reading a Light Sensor -**Components Needed:** +We will now try an example, where we will read the light intensity of a photoresistor. + +For this example, we will need the following external components: -- Arduino board compatible with MicroPython -- Analog light sensor (e.g., photoresistor) +- Breadboard +- Photo resistor - Jumper wires +- 10k Ω resistor -**Circuit Diagram:** +Connect the photoresistor to the Arduino board, following the circuit diagram below: -1. Connect one leg of the photoresistor to the analog input pin (e.g., `A0`) and the other leg to `GND`. -2. Optionally, add a pull-up resistor to the sensor if needed. +![Photoresistor circuit.]() -**MicroPython Code:** +After completing the circuit diagram, copy the following code into your editor, and run the script. ```python from machine import ADC @@ -63,7 +104,7 @@ while True: time.sleep(1) ``` -**Explanation:** +Let's take a look at what's included in this code example: - **ADC Initialization**: We initialize the `ADC` class, passing the analog channel as an argument. - **Reading Values**: `read_u16()` reads a 16-bit integer (0-65535), where `0` represents 0V and `65535` represents the board's maximum operating voltage. @@ -73,23 +114,36 @@ while True: Unlike analog input, analog output on microcontrollers doesn’t provide a truly continuous range of voltages. Instead, we use **Pulse Width Modulation** (PWM) to simulate varying voltage levels. PWM rapidly switches a digital output between HIGH and LOW at a specified duty cycle, creating the illusion of analog output by controlling the amount of time the signal stays HIGH. +### Pulse Width Modulation (PWM) + +True analog signals involve a continuous voltage range, but since microcontrollers primarily handle digital signals (on or off), PWM bridges the gap by rapidly switching the signal between HIGH and LOW. By adjusting the time the signal remains in the HIGH state (known as the "duty cycle"), PWM simulates varying voltage levels. + +PWM is especially useful in applications where true analog output is not possible but smooth transitions are necessary. Common scenarios include: + +- **LED Dimming**: PWM allows for adjusting brightness levels by controlling how long the LED is ON versus OFF within a given time frame. +- **Motor Control**: By modifying the duty cycle, PWM can control the speed of motors for robotics or other mechanical devices, as the motor responds to the average power supplied over time. +- **Audio Signals**: Some sound applications also use PWM to generate varying sound frequencies or control speaker volume. + +The main advantage of PWM is that it allows you to control analog-like behavior using digital pins, adding versatility to your projects while keeping power consumption efficient. + +![How PWM works.]() + ### Code Example: Dimming an LED with PWM -PWM is commonly used for tasks such as dimming LEDs or controlling motor speeds. +We will now try an example, where we will dim an LED using PWM. -**Components Needed:** +For this example, we will need the following external components: -- Arduino board compatible with MicroPython +- Breadboard - LED - Current-limiting resistor (e.g., 220Ω) - Jumper wires -**Circuit Diagram:** +Connect the LED to the Arduino board, following the circuit diagram below: -1. Connect the anode (+) of the LED to the PWM-capable output pin (e.g., `D5`). -2. Connect the cathode (-) through a resistor to `GND`. +![Photoresistor circuit.]() -**MicroPython Code:** +After completing the circuit diagram, copy the following code into your editor, and run the script. ```python from machine import Pin, PWM @@ -109,10 +163,31 @@ while True: time.sleep(0.01) ``` -**Explanation:** +Let's take a look at what's included in this code example: - **PWM Initialization**: We create a `PWM` object and set the frequency to 1 kHz, which works well for LEDs. - **Duty Cycle**: `duty_u16()` takes a value between 0 and 65535. The higher the value, the longer the signal stays HIGH, making the LED brighter. - **Loop**: The brightness gradually increases and decreases by adjusting the duty cycle in small steps, causing the LED to fade in and out. +## Analog Resolution + +The resolution of an ADC can simply be explained as how detailed it is. When using MicroPython, the default is **16-bits**, while using the Arduino programming language it is **10-bits**. So what is the difference? + +When we read something in 16-bit resolution, we receive a range of 0-65355. Let's say the voltage range is 0-3.3V, as is standard in most modern boards. If we were to read 3.3V, it means "max" or "65355". If we read half of that voltage (1.65V), it would be 65355/2 = 32677. + +Now let's say we have an analog sensor reading temperature. If the temperature is at its very max for that component, and it outputs 3.3V, we will read 65355. If it is not outputting any voltage (which is unlikely), we would read 0. + +If we are using a different resolution, such as **10-bits**, the range would instead be **0-1023**. The voltage remains the same, but the value we read is different. + +Why does it work this way? See, bits are used to represent information. A single bit can hold only two values: 0 or 1, while 2 bits can be between 0-3, 3 bits between 0-8 and so on. See below: +- 1-bit = 0-1 +- 2-bits = 0-3 +- 4-bits = 0-8 +- 8-bits = 0-255 +- 10-bits = 0-1023 +- 16-bits = 0-65355 +- 32-bits = 0-4,294,967,295 + +## Summary +In this guide we have learned about analog inputs, outputs & resolution. We have also gone through a number of fundamental examples to understand how it works in practice. \ No newline at end of file diff --git a/content/micropython/03.micropython/01.basics/02. loops/loops.md b/content/micropython/03.micropython/01.basics/02. loops/loops.md index 1329968fa2..f186da8e00 100644 --- a/content/micropython/03.micropython/01.basics/02. loops/loops.md +++ b/content/micropython/03.micropython/01.basics/02. loops/loops.md @@ -1,42 +1,77 @@ --- - -featured: micropython-101 -title: '3. Micropython Basics - Loops' -description: 'Learn the basics for loops on MicroPython.' +title: 'Loops' +description: 'Learn how to use different loops with MicroPython.' author: 'Pedro Lima' -hero_image: "./hero-banner.png" - +tags: [MicroPython, Loops] --- -Loops are fundamental constructs in programming that allow you to execute a block of code multiple times. In MicroPython, loops help you perform repetitive tasks efficiently and are an awesome tool to keep in your coder's toolbox. In this article, we will explore the different loop structures available. +Loops are fundamental constructs in all programming languages, that allow you to execute a block of code multiple times. In MicroPython, loops help you perform repetitive tasks efficiently and are an awesome tool to keep in your coder's toolbox. -## Loop Structures in MicroPython +In this guide, we will explore the different loop structures available. -MicroPython supports two primary loop structures, each with a specific purpose: +## Requirements -- **`for` loops**: These loops iterate over a predefined sequence, such as a list, tuple, or string. The loop automatically retrieves each item in the sequence, one at a time, and performs actions until every item has been handled. +Before we start, let's check the requirements: -- **`while` loops**: These loops continue executing as long as a specified condition is true. Unlike `for` loops, which depend on a sequence, `while` loops rely on a conditional expression that determines when the loop should stop. +### MicroPython Compatible Arduino Boards -To better understand these loops, let’s imagine them as tasks at the supermarket: +MicroPython is officially supported on several Arduino boards. Here’s a list of the compatible boards: + +- [Portenta C33](https://store.arduino.cc/products/portenta-c33) +- [Arduino GIGA R1 WiFi](https://store.arduino.cc/products/arduino-giga-r1-wifi) +- [Portenta H7](https://store.arduino.cc/products/portenta-h7) +- [Portenta H7 Lite](https://store.arduino.cc/products/portenta-h7-lite) +- [Portenta H7 Lite Connected](https://store.arduino.cc/products/portenta-h7-lite-connected) +- [Opta](https://store.arduino.cc/products/opta) +- [Opta Wifi](https://store.arduino.cc/products/opta-wifi) +- [Opta RS485](https://store.arduino.cc/products/opta-rs485) +- [Arduino Nano RP2040 Connect](https://store.arduino.cc/products/arduino-nano-rp2040-connect) +- [Nicla Vision](https://store.arduino.cc/products/nicla-vision) +- [Arduino Nano 33 BLE](https://store.arduino.cc/products/arduino-nano-33-ble) +- [Arduino Nano 33 BLE Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-rev2) +- [Arduino Nano 33 BLE Sense](https://store.arduino.cc/products/arduino-nano-33-ble-sense) +- [Arduino Nano 33 BLE Sense Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-sense-rev2) +- [Arduino Nano ESP32](https://store.arduino.cc/products/arduino-nano-esp32) -- **`for` loops**: Imagine walking down a supermarket aisle with a shopping list that specifies exactly how many items to pick up, one by one, in order. Once you’ve gathered all the items on your list, your task is complete. This is like a `for` loop iterating over a sequence, handling each specified item one at a time. +### Software Requirements -TODO:!(FOR ILLUSTRATION)[] +- [Arduino Lab for Micropython](https://labs.arduino.cc/en/labs/micropython) - Arduino Lab for MicroPython is an editor where we can create and run MicroPython scripts on our Arduino board. -- **`while` loops**: Imagine going to the supermarket to buy a certain product that’s on sale, as long as it stays in stock. You keep coming back, day after day, until the sale ends or the stock runs out. In a `while` loop, you keep “coming back” as long as a condition (like the sale continuing) remains true. +***Note that the editor is also available online, at [Arduino Cloud - Arduino Labs for MicroPython](https://lab-micropython.arduino.cc/)*** -TODO:!(WHILE ILLUSTRATION)[] +## Board and Editor Setup -Let's jump into each of these with examples. +1. Open the [Arduino Lab for MicroPython]() application. +2. Plug the Arduino board into the computer using a USB cable. + ![Connect board to computer.]() +3. Press the connection button on the top left corner of the window. + ![Connect the editor to the board.]() +4. The connected Arduino board should appear, and we can click it: + ![Select board.]() +***Need help installing MicroPython on your board? Visit the [MicroPython installation guide]().*** +## Loop Structures in MicroPython -## Using a `for` Loop +MicroPython supports two primary loop structures, each with a specific purpose: -The `for` loop is used for iterating over a sequence. It automatically retrieves each item in the sequence one after another. +- **`for` loops**: for loops iterate over a predefined sequence, such as a list, tuple, or string. The loop automatically retrieves each item in the sequence, one at a time, and performs actions until every item has been handled. + +- **`while` loops**: while loops continue executing as long as a specified condition is true. Unlike `for` loops, which depend on a sequence, `while` loops rely on a conditional expression that determines when the loop should stop. + +To better understand these loops, let’s imagine them as tasks at the supermarket: -### Syntax +- **for loops** - imagine walking down a supermarket aisle with a shopping list that specifies exactly how many items to pick up, one by one, in order. Once you’ve gathered all the items on your list, your task is complete. This is like a `for` loop iterating over a sequence, handling each specified item one at a time. + +![How for loops work.]() + +- **while loops** - imagine going to the supermarket to buy a certain product that’s on sale, as long as it stays in stock. You keep coming back, day after day, until the sale ends or the stock runs out. In a `while` loop, you keep “coming back” as long as a condition (like the sale continuing) remains true. + +![How while loops work.]() + +## For Loops + +The `for` loop is used for iterating over a sequence. It automatically retrieves each item in the sequence one after another. ```python for variable in sequence: @@ -49,35 +84,31 @@ for variable in sequence: - **`sequence`**: The collection (like a list, tuple, or string) over which the loop iterates. - **Code block**: The indented block of code that runs on each iteration. -### Example: Iterating Over "Arduino" with a `for` Loop +### Example Code -```python -import time +Let's try out making a for loop. In this example, we set `i` which stands for *iteration*, in a range of 5. -cycle = 1 -for letter in "Arduino": - print(f"{cycle} - {letter} - printed with for loop") - cycle += 1 - time.sleep(3) +```python +for i in range(5): + print(i) ``` -**Explanation:** - -- **Import `time` Module**: We import the `time` module to use the `sleep()` function for delays. -- **Initialize `cycle` Variable**: We start a `cycle` counter at 1. -- **`for letter in "Arduino"`**: The loop iterates over each character in the string `"Arduino"`, assigning each character to the variable `letter`. -- **Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `for` loop. -- **Increment `cycle`**: Increases the cycle counter by 1 after each iteration. -- **`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration. +Running this script will result in printing `i` for five times. Each time the loop is run, `i` is increased, so in the REPL, we should see: +``` +0 +1 +2 +3 +4 +``` +This is because we start counting from 0. So the first time the loop runs, we print `0`, the second time it runs `1` and so on. -## Using a `while` Loop +## While Loops A `while` loop continues to execute as long as a specified condition is true. -### Syntax of a `while` Loop - ```python while condition: # Code block to execute @@ -87,44 +118,92 @@ while condition: - **`condition`**: A boolean expression evaluated before each iteration; if `True`, the loop continues. - **Code block**: The indented block of code that runs on each iteration. -### Example: Iterating Over "Arduino" with a `while` Loop +### Example Code + +Let's try making a while loop! In the example below, we have a counter, which we print to the REPL. This is to track how many times the loop has run. We pause between each print using the `time.sleep(1)` function, so that it is easier to read in the REPL. ```python import time +counter = 0 + +while True: + counter += 1 + print('Number of iterations: ' + str(counter)) + time.sleep(1) +``` + +In this example, we used: + +- `while True:` - this keeps a while loop running forever. +- `print('Number of iterations: ' + str(counter))`, to print out the current iteration. +- because we cannot mix numeric values with strings when using the `print()` function, we need to use `str(counter)` when printing to the REPL. + +The result will be an infinite loop, that will print the current iteration: + +```python +Number of iterations: 10 +Number of iterations: 11 +Number of iterations: 12 +..... +Number of iterations: 99999 # this loop has been running for a long time.. +``` -word = "Arduino" -index = 0 -cycle = 1 +## Control Statements -while index < len(word): - letter = word[index] - print(f"{cycle} - {letter} - printed with while loop") - index += 1 - cycle += 1 - time.sleep(3) +While inside a loop, we can control how it should behave using control statements: **continue** and **break** + +### Continue + +The `continue` statement can be used to skip past an iteration. For example, if we for some reason want to skip every fifth iteration, we could use the following code: + +```python +for i in range(10) + if i == 5: + continue + print(i) ``` -**Explanation:** +Running this script will result in: -- **Initialize Variables**: - - `word`: The string we're iterating over. - - `index`: Starts at 0, used to access each character in `word`. - - `cycle`: Counts the number of iterations. -- **`while index < len(word)`**: The loop continues as long as `index` is less than the length of `word`. -- **Retrieve Letter**: `letter = word[index]` gets the character at the current index. -- **Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `while` loop. -- **Increment Counters**: Increases `index` and `cycle` by 1. -- **`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration. +```python +0 +1 +2 +3 +4 +6 # we skip the 5th iteration +7 +8 +9 +10 +``` +### Break +The `break` statement can be used to break out of a loop before it finishes all iterations. This can be useful to for example cancel a process if something unexpected happens. +```python +for i in range(10) + if i == 5: + break + print(i) +``` + +Running this script will result in: +```python +0 +1 +2 +3 +4 +``` ## Conclusion -Loops are essential for automating repetitive tasks in MicroPython. Understanding how to use different loop structures allows you to write more efficient and effective code. In these examples, we've demonstrated how to iterate over the string "Arduino" using various loop methods, printing each letter with a delay to observe the output in real time. +Loops are essential for automating repetitive tasks in MicroPython. Understanding how to use different loop structures allows you to write more efficient and effective code. -**Try Modifying the Examples** +In these examples, we've demonstrated how to create loops that can: +- Run *for* a specific amount of iterations (for loops) +- Loops that can run *while* a condition is met (while loops) -- **Different Strings**: Replace `"Arduino"` with another word to see how the loops handle different sequences. -- **Additional Information**: Include more details in the print statement, such as the ASCII value of each letter. \ No newline at end of file