Skip to content

Commit 5964719

Browse files
Added articles
1 parent c0983d3 commit 5964719

File tree

3 files changed

+431
-0
lines changed

3 files changed

+431
-0
lines changed
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
---
2+
3+
featured: micropython-101
4+
title: '2. Micropython Basics - Loops'
5+
description: 'Learn the basics for loops on MicroPython.'
6+
author: 'Pedro Lima'
7+
hero_image: "./hero-banner.png"
8+
9+
---
10+
11+
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:
12+
13+
- Control outputs, such as turning an LED on and off.
14+
- Read inputs, like detecting the state of a button.
15+
16+
Digital signals have two distinct values:
17+
18+
- **HIGH (1)**: Represents a voltage level close to the board's operating voltage (e.g., 3.3V or 5V).
19+
- **LOW (0)**: Represents a voltage level close to 0V (ground).
20+
21+
Understanding how to use digital pins allows you to create interactive projects that respond to external stimuli or control external devices.
22+
23+
## Digital Outputs
24+
25+
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.
26+
27+
### Code Example: Blinking an LED
28+
29+
Let's create the classic "Blink" example, where we turn an LED on and off at regular intervals.
30+
31+
**Components Needed:**
32+
33+
- Arduino board compatible with MicroPython
34+
- LED (optional if using the onboard LED)
35+
- Current-limiting resistor (e.g., 220Ω) if using an external LED
36+
- Jumper wires
37+
38+
**Circuit Diagram:**
39+
40+
- **Onboard LED**: Many Arduino boards have an onboard LED connected to a specific pin.
41+
- **External LED**:
42+
- Connect the anode (+) of the LED to a digital output pin.
43+
- Connect the cathode (-) of the LED through a resistor to `GND`.
44+
45+
**MicroPython Code:**
46+
47+
```python
48+
from machine import Pin
49+
import time
50+
51+
# Initialize the LED pin
52+
# Uncomment the line that matches your board
53+
led = Pin(25, Pin.OUT) # For Arduino Nano RP2040 Connect
54+
# led = Pin(13, Pin.OUT) # For Arduino Nano 33 BLE / Sense (built-in LED)
55+
# led = Pin(2, Pin.OUT) # For Arduino Portenta H7
56+
57+
while True:
58+
led.value(1) # Turn LED on
59+
time.sleep(1) # Wait for 1 second
60+
led.value(0) # Turn LED off
61+
time.sleep(1) # Wait for 1 second
62+
```
63+
64+
**Explanation:**
65+
66+
- **Import Modules**: We import `Pin` from `machine` and `time` for delays.
67+
- **Initialize LED Pin**: Create a `Pin` object, setting the pin number and direction (`Pin.OUT`).
68+
- **Main Loop**:
69+
- `led.value(1)`: Sets the pin to HIGH, turning the LED on.
70+
- `time.sleep(1)`: Pauses the program for 1 second.
71+
- `led.value(0)`: Sets the pin to LOW, turning the LED off.
72+
- The loop repeats indefinitely, causing the LED to blink.
73+
74+
75+
76+
## Digital Inputs
77+
78+
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.
79+
80+
### Understanding Pull Modes
81+
82+
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.
83+
84+
- **Pull-Up Mode (`Pin.PULL_UP`)**: Connects the input pin internally to a HIGH voltage level, ensuring the pin reads HIGH when not connected to anything else.
85+
- **Pull-Down Mode (`Pin.PULL_DOWN`)**: Connects the input pin internally to GND, ensuring the pin reads LOW when not connected to anything else.
86+
87+
These internal resistors are built into the microcontroller and can be enabled in your code, eliminating the need for external resistors.
88+
89+
![We can create a image here to explain that]()
90+
91+
92+
93+
### Pull-Up Mode
94+
95+
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`).
96+
97+
**Circuit Diagram for Pull-Up Mode:**
98+
99+
- Connect one side of the button to **GND**.
100+
- Connect the other side to a digital input pin.
101+
102+
![Demo]()
103+
104+
### Pull-Down Mode
105+
106+
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`).
107+
108+
**Circuit Diagram for Pull-Down Mode:**
109+
110+
- Connect one side of the button to **3.3V** (or **5V**, depending on your board's logic level).
111+
- Connect the other side to a digital input pin.
112+
113+
![Demo]()
114+
115+
116+
### Code Example: Reading a Button with Pull-Up Mode
117+
118+
**Components Needed:**
119+
120+
- Arduino board compatible with MicroPython
121+
- Push-button switch
122+
- Jumper wires
123+
124+
**MicroPython Code:**
125+
126+
```python
127+
from machine import Pin
128+
import time
129+
130+
# Initialize the button pin with internal pull-up resistor
131+
button = Pin(14, Pin.IN, Pin.PULL_UP) # Replace 14 with your input pin number
132+
133+
while True:
134+
button_state = button.value()
135+
if button_state == 0:
136+
print("Button Pressed")
137+
else:
138+
print("Button Released")
139+
time.sleep(0.1)
140+
```
141+
142+
**Explanation:**
143+
144+
- **Initialize Button Pin**:
145+
- We set up the pin as an input with a pull-up mode (`Pin.PULL_UP`), enabling the internal pull-up resistor.
146+
- This means the pin reads HIGH (`1`) when the button is not pressed.
147+
- **Reading the Pin**:
148+
- When the button is **not pressed**, the pin is pulled HIGH internally (`button.value()` returns `1`).
149+
- When the button is **pressed**, it connects the pin to GND, making `button.value()` return `0`.
150+
- **Main Loop**:
151+
- Reads the button state and prints a message accordingly.
152+
- A short delay helps debounce the button.
153+
154+
155+
156+
### Code Example: Reading a Button with Pull-Down Mode
157+
158+
**Components Needed:**
159+
160+
- Arduino board compatible with MicroPython
161+
- Push-button switch
162+
- Jumper wires
163+
164+
**MicroPython Code:**
165+
166+
```python
167+
from machine import Pin
168+
import time
169+
170+
# Initialize the button pin with internal pull-down resistor
171+
button = Pin(14, Pin.IN, Pin.PULL_DOWN) # Replace 14 with your input pin number
172+
173+
while True:
174+
button_state = button.value()
175+
if button_state == 1:
176+
print("Button Pressed")
177+
else:
178+
print("Button Released")
179+
time.sleep(0.1)
180+
```
181+
182+
**Explanation:**
183+
184+
- **Initialize Button Pin**:
185+
- We set up the pin as an input with a pull-down mode (`Pin.PULL_DOWN`), enabling the internal pull-down resistor.
186+
- This means the pin reads LOW (`0`) when the button is not pressed.
187+
- **Reading the Pin**:
188+
- When the button is **not pressed**, the pin is pulled LOW internally (`button.value()` returns `0`).
189+
- When the button is **pressed**, it connects the pin to HIGH voltage, making `button.value()` return `1`.
190+
- **Main Loop**:
191+
- Reads the button state and prints a message accordingly.
192+
- A short delay helps debounce the button.
193+
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
---
2+
3+
featured: micropython-101
4+
title: '2. Micropython - Digital I/O'
5+
description: 'Learn the basics for digital IO ports on MicroPython.'
6+
author: 'Pedro Lima'
7+
hero_image: "./hero-banner.png"
8+
9+
---
10+
11+
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.
12+
13+
## Loop Structures in MicroPython
14+
15+
MicroPython supports two primary loop structures:
16+
17+
- **`for` loops**: Iterate over a sequence (like a list, tuple, or string).
18+
- **`while` loops**: Continue executing as long as a condition is true.
19+
20+
Let's delve into each of these with examples.
21+
22+
23+
24+
## Using a `for` Loop
25+
26+
The `for` loop is used for iterating over a sequence. It automatically retrieves each item in the sequence one after another.
27+
28+
### Syntax
29+
30+
```python
31+
for variable in sequence:
32+
# Code block to execute
33+
```
34+
35+
- **`for`**: Keyword that starts the loop.
36+
- **`variable`**: Takes the value of each item in the sequence during iteration this is where you will get the value for each iteration of a collection.
37+
- **`in`**: Keyword used to specify the sequence to iterate over.
38+
- **`sequence`**: The collection (like a list, tuple, or string) over which the loop iterates.
39+
- **Code block**: The indented block of code that runs on each iteration.
40+
41+
### Example: Iterating Over "Arduino" with a `for` Loop
42+
43+
```python
44+
import time
45+
46+
cycle = 1
47+
for letter in "Arduino":
48+
print(f"{cycle} - {letter} - printed with for loop")
49+
cycle += 1
50+
time.sleep(3)
51+
```
52+
53+
**Explanation:**
54+
55+
- **Import `time` Module**: We import the `time` module to use the `sleep()` function for delays.
56+
- **Initialize `cycle` Variable**: We start a `cycle` counter at 1.
57+
- **`for letter in "Arduino"`**: The loop iterates over each character in the string `"Arduino"`, assigning each character to the variable `letter`.
58+
- **Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `for` loop.
59+
- **Increment `cycle`**: Increases the cycle counter by 1 after each iteration.
60+
- **`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration.
61+
62+
63+
64+
## Using a `while` Loop
65+
66+
A `while` loop continues to execute as long as a specified condition is true.
67+
68+
### Syntax of a `while` Loop
69+
70+
```python
71+
while condition:
72+
# Code block to execute
73+
```
74+
75+
- **`while`**: Keyword that starts the loop.
76+
- **`condition`**: A boolean expression evaluated before each iteration; if `True`, the loop continues.
77+
- **Code block**: The indented block of code that runs on each iteration.
78+
79+
### Example: Iterating Over "Arduino" with a `while` Loop
80+
81+
```python
82+
import time
83+
84+
word = "Arduino"
85+
index = 0
86+
cycle = 1
87+
88+
while index < len(word):
89+
letter = word[index]
90+
print(f"{cycle} - {letter} - printed with while loop")
91+
index += 1
92+
cycle += 1
93+
time.sleep(3)
94+
```
95+
96+
**Explanation:**
97+
98+
- **Initialize Variables**:
99+
- `word`: The string we're iterating over.
100+
- `index`: Starts at 0, used to access each character in `word`.
101+
- `cycle`: Counts the number of iterations.
102+
- **`while index < len(word)`**: The loop continues as long as `index` is less than the length of `word`.
103+
- **Retrieve Letter**: `letter = word[index]` gets the character at the current index.
104+
- **Print Statement**: Outputs the cycle number, the current letter, and mentions that it's printed with a `while` loop.
105+
- **Increment Counters**: Increases `index` and `cycle` by 1.
106+
- **`time.sleep(3)`**: Pauses the program for 3 seconds before the next iteration.
107+
108+
109+
110+
111+
112+
## Conclusion
113+
114+
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.
115+
116+
**Try Modifying the Examples**
117+
118+
- **Different Strings**: Replace `"Arduino"` with another word to see how the loops handle different sequences.
119+
- **Additional Information**: Include more details in the print statement, such as the ASCII value of each letter.

0 commit comments

Comments
 (0)