You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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]
9
6
---
10
7
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:
12
9
13
10
- 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.
15
12
16
13
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.
17
14
18
-
## Analog Inputs
15
+
## Requirements
19
16
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:
23
18
24
-
##PWM - Pulse Width Modulation
19
+
### MicroPython Compatible Arduino Boards
25
20
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:
27
22
28
-
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.
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
33
40
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.
35
72
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).***
37
76
38
77
### Code Example: Reading a Light Sensor
39
78
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:
41
82
42
-
-Arduino board compatible with MicroPython
43
-
-Analog light sensor (e.g., photoresistor)
83
+
-Breadboard
84
+
-Photo resistor
44
85
- Jumper wires
86
+
- 10k Ω resistor
45
87
46
-
**Circuit Diagram:**
88
+
Connect the photoresistor to the Arduino board, following the circuit diagram below:
47
89
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.]()
50
91
51
-
**MicroPython Code:**
92
+
After completing the circuit diagram, copy the following code into your editor, and run the script.
52
93
53
94
```python
54
95
from machine importADC
@@ -63,7 +104,7 @@ while True:
63
104
time.sleep(1)
64
105
```
65
106
66
-
**Explanation:**
107
+
Let's take a look at what's included in this code example:
67
108
68
109
-**ADC Initialization**: We initialize the `ADC` class, passing the analog channel as an argument.
69
110
-**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:
73
114
74
115
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.
75
116
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
+
76
131
### Code Example: Dimming an LED with PWM
77
132
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.
79
134
80
-
**Components Needed:**
135
+
For this example, we will need the following external components:
81
136
82
-
-Arduino board compatible with MicroPython
137
+
-Breadboard
83
138
- LED
84
139
- Current-limiting resistor (e.g., 220Ω)
85
140
- Jumper wires
86
141
87
-
**Circuit Diagram:**
142
+
Connect the LED to the Arduino board, following the circuit diagram below:
88
143
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.]()
91
145
92
-
**MicroPython Code:**
146
+
After completing the circuit diagram, copy the following code into your editor, and run the script.
93
147
94
148
```python
95
149
from machine import Pin, PWM
@@ -109,10 +163,31 @@ while True:
109
163
time.sleep(0.01)
110
164
```
111
165
112
-
**Explanation:**
166
+
Let's take a look at what's included in this code example:
113
167
114
168
-**PWM Initialization**: We create a `PWM` object and set the frequency to 1 kHz, which works well for LEDs.
115
169
-**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.
116
170
-**Loop**: The brightness gradually increases and decreases by adjusting the duty cycle in small steps, causing the LED to fade in and out.
117
171
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
118
192
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