Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d35a093

Browse files
committedOct 31, 2024
Update analog-io.md
1 parent b040193 commit d35a093

File tree

1 file changed

+112
-37
lines changed
  • content/micropython/03.micropython/01.basics/01. analog-io

1 file changed

+112
-37
lines changed
 
Lines changed: 112 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,95 @@
11
---
2-
3-
featured: micropython-101
4-
title: '2. Micropython Basics - Analog I/O'
5-
description: 'Learn the fundamentals of analog I/O with MicroPython for smooth signal interactions.'
6-
author: 'Pedro Lima'
7-
hero_image: "./hero-banner.png"
8-
2+
title: 'Analog I/O'
3+
description: 'A guide to analog inputs (ADC) and outputs (PWM) using MicroPython.'
4+
author: 'Pedro Lima'
5+
tags: [MicroPython, Analog I/O]
96
---
107

11-
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:
8+
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:
129

1310
- Read analog values, such as a light sensor or potentiometer.
14-
- Generate analog outputs, like controlling LED brightness or motor speed.
11+
- Generate analog outputs, like controlling LED brightness or the speed of a motor.
1512

1613
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.
1714

18-
## Analog Inputs
15+
## Requirements
1916

20-
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.
21-
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.
22-
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.
17+
Before we start, let's check the requirements:
2318

24-
## PWM - Pulse Width Modulation
19+
### MicroPython Compatible Arduino Boards
2520

26-
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.
21+
MicroPython is officially supported on several Arduino boards. Here’s a list of the compatible boards:
2722

28-
PWM is especially useful in applications where true analog output is not possible but smooth transitions are necessary. Common scenarios include:
23+
- [Portenta C33](https://store.arduino.cc/products/portenta-c33)
24+
- [Arduino GIGA R1 WiFi](https://store.arduino.cc/products/arduino-giga-r1-wifi)
25+
- [Portenta H7](https://store.arduino.cc/products/portenta-h7)
26+
- [Portenta H7 Lite](https://store.arduino.cc/products/portenta-h7-lite)
27+
- [Portenta H7 Lite Connected](https://store.arduino.cc/products/portenta-h7-lite-connected)
28+
- [Opta](https://store.arduino.cc/products/opta)
29+
- [Opta Wifi](https://store.arduino.cc/products/opta-wifi)
30+
- [Opta RS485](https://store.arduino.cc/products/opta-rs485)
31+
- [Arduino Nano RP2040 Connect](https://store.arduino.cc/products/arduino-nano-rp2040-connect)
32+
- [Nicla Vision](https://store.arduino.cc/products/nicla-vision)
33+
- [Arduino Nano 33 BLE](https://store.arduino.cc/products/arduino-nano-33-ble)
34+
- [Arduino Nano 33 BLE Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-rev2)
35+
- [Arduino Nano 33 BLE Sense](https://store.arduino.cc/products/arduino-nano-33-ble-sense)
36+
- [Arduino Nano 33 BLE Sense Rev2](https://store.arduino.cc/products/arduino-nano-33-ble-sense-rev2)
37+
- [Arduino Nano ESP32](https://store.arduino.cc/products/arduino-nano-esp32)
2938

30-
- **LED Dimming**: PWM allows for adjusting brightness levels by controlling how long the LED is ON versus OFF within a given time frame.
31-
- **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.
32-
- **Audio Signals**: Some sound applications also use PWM to generate varying sound frequencies or control speaker volume.
39+
### Hardware Components
3340

34-
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.
41+
In this guide, we will be using some additional electronic components:
42+
- LEDs
43+
- Current-limiting resistor (e.g. 220Ω) if using an external LED
44+
- Jumper wires
45+
- Breadboard
46+
47+
### Software Requirements
48+
49+
- [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.
50+
51+
***Note that the editor is also available online, at [Arduino Cloud - Arduino Labs for MicroPython](https://lab-micropython.arduino.cc/)***
52+
53+
## Board and Editor Setup
54+
55+
1. Open the [Arduino Lab for MicroPython]() application.
56+
2. Plug the Arduino board into the computer using a USB cable.
57+
![Connect board to computer.]()
58+
3. Press the connection button on the top left corner of the window.
59+
![Connect the editor to the board.]()
60+
4. The connected Arduino board should appear, and we can click it:
61+
![Select board.]()
62+
63+
***Need help installing MicroPython on your board? Visit the [MicroPython installation guide]().***
64+
65+
## Analog Inputs
66+
67+
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.
68+
69+
### Analog-to-Digital Converter (ADC)
70+
71+
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.
3572

36-
TODO: ILLUSTRATE THIS PWM MAGIC
73+
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\*.
74+
75+
***\*What does a 16-bit resolution mean? Find out at the [end of this article](#analog-resolution).***
3776

3877
### Code Example: Reading a Light Sensor
3978

40-
**Components Needed:**
79+
We will now try an example, where we will read the light intensity of a photoresistor.
80+
81+
For this example, we will need the following external components:
4182

42-
- Arduino board compatible with MicroPython
43-
- Analog light sensor (e.g., photoresistor)
83+
- Breadboard
84+
- Photo resistor
4485
- Jumper wires
86+
- 10k Ω resistor
4587

46-
**Circuit Diagram:**
88+
Connect the photoresistor to the Arduino board, following the circuit diagram below:
4789

48-
1. Connect one leg of the photoresistor to the analog input pin (e.g., `A0`) and the other leg to `GND`.
49-
2. Optionally, add a pull-up resistor to the sensor if needed.
90+
![Photoresistor circuit.]()
5091

51-
**MicroPython Code:**
92+
After completing the circuit diagram, copy the following code into your editor, and run the script.
5293

5394
```python
5495
from machine import ADC
@@ -63,7 +104,7 @@ while True:
63104
time.sleep(1)
64105
```
65106

66-
**Explanation:**
107+
Let's take a look at what's included in this code example:
67108

68109
- **ADC Initialization**: We initialize the `ADC` class, passing the analog channel as an argument.
69110
- **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:
73114

74115
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.
75116

117+
### Pulse Width Modulation (PWM)
118+
119+
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.
120+
121+
PWM is especially useful in applications where true analog output is not possible but smooth transitions are necessary. Common scenarios include:
122+
123+
- **LED Dimming**: PWM allows for adjusting brightness levels by controlling how long the LED is ON versus OFF within a given time frame.
124+
- **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.
125+
- **Audio Signals**: Some sound applications also use PWM to generate varying sound frequencies or control speaker volume.
126+
127+
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.
128+
129+
![How PWM works.]()
130+
76131
### Code Example: Dimming an LED with PWM
77132

78-
PWM is commonly used for tasks such as dimming LEDs or controlling motor speeds.
133+
We will now try an example, where we will dim an LED using PWM.
79134

80-
**Components Needed:**
135+
For this example, we will need the following external components:
81136

82-
- Arduino board compatible with MicroPython
137+
- Breadboard
83138
- LED
84139
- Current-limiting resistor (e.g., 220Ω)
85140
- Jumper wires
86141

87-
**Circuit Diagram:**
142+
Connect the LED to the Arduino board, following the circuit diagram below:
88143

89-
1. Connect the anode (+) of the LED to the PWM-capable output pin (e.g., `D5`).
90-
2. Connect the cathode (-) through a resistor to `GND`.
144+
![Photoresistor circuit.]()
91145

92-
**MicroPython Code:**
146+
After completing the circuit diagram, copy the following code into your editor, and run the script.
93147

94148
```python
95149
from machine import Pin, PWM
@@ -109,10 +163,31 @@ while True:
109163
time.sleep(0.01)
110164
```
111165

112-
**Explanation:**
166+
Let's take a look at what's included in this code example:
113167

114168
- **PWM Initialization**: We create a `PWM` object and set the frequency to 1 kHz, which works well for LEDs.
115169
- **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.
116170
- **Loop**: The brightness gradually increases and decreases by adjusting the duty cycle in small steps, causing the LED to fade in and out.
117171

172+
## Analog Resolution
173+
174+
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?
175+
176+
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.
177+
178+
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.
179+
180+
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.
181+
182+
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:
183+
- 1-bit = 0-1
184+
- 2-bits = 0-3
185+
- 4-bits = 0-8
186+
- 8-bits = 0-255
187+
- 10-bits = 0-1023
188+
- 16-bits = 0-65355
189+
- 32-bits = 0-4,294,967,295
190+
191+
## Summary
118192

193+
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.

0 commit comments

Comments
 (0)
Please sign in to comment.