0
# Analog I/O and PWM
1
2
Analog input reading and PWM output control for interfacing with sensors, controlling motor speeds, LED brightness, and other analog devices.
3
4
## Capabilities
5
6
### Analog Output (PWM)
7
8
Generate PWM (Pulse Width Modulation) signals for controlling analog devices like LEDs, motors, and servo positions.
9
10
```javascript { .api }
11
/**
12
* Write analog value to a PWM-capable pin
13
* Automatically configures pin for PWM output
14
* @param pin - PWM-capable pin number (typically 3, 5, 6, 9, 10, 11 on Arduino UNO)
15
* @param value - PWM value from 0 (0% duty cycle) to 255 (100% duty cycle)
16
* @param callback - Optional callback function called when value is written
17
*/
18
analogWrite(pin: number, value: number, callback?: Function): void;
19
```
20
21
**PWM Value Range:**
22
- `0` - 0% duty cycle (always LOW, equivalent to digitalWrite(pin, false))
23
- `127-128` - ~50% duty cycle (half power)
24
- `255` - 100% duty cycle (always HIGH, equivalent to digitalWrite(pin, true))
25
26
**Usage Examples:**
27
28
```javascript
29
// Set LED to half brightness
30
arduino.analogWrite(9, 127);
31
32
// Fade LED in and out
33
let brightness = 0;
34
let direction = 1;
35
36
setInterval(function() {
37
arduino.analogWrite(9, brightness);
38
39
brightness += direction * 5;
40
if (brightness >= 255 || brightness <= 0) {
41
direction = -direction;
42
}
43
}, 50);
44
45
// Control motor speed (0 = stopped, 255 = full speed)
46
arduino.analogWrite(6, 200); // ~78% speed
47
48
// With callback
49
arduino.analogWrite(9, 100, function() {
50
console.log('PWM value set to 100');
51
});
52
```
53
54
### Analog Input
55
56
Read analog voltage values from Arduino analog input pins for sensor data collection.
57
58
```javascript { .api }
59
/**
60
* Read current analog value from an analog input pin
61
* @param pin - Analog pin number (0-5 on Arduino UNO, corresponds to A0-A5)
62
* @returns Current analog reading as integer from 0 to 1023
63
*/
64
analogRead(pin: number): number;
65
```
66
67
**Value Range:**
68
- `0` - 0V input voltage
69
- `512` - ~2.5V input voltage (half of 5V reference)
70
- `1023` - 5V input voltage (or reference voltage)
71
72
**Usage Examples:**
73
74
```javascript
75
// Read potentiometer on analog pin 0
76
const potValue = arduino.analogRead(0);
77
console.log(`Potentiometer reading: ${potValue} (${(potValue/1023*100).toFixed(1)}%)`);
78
79
// Read multiple analog sensors
80
for (let pin = 0; pin < 6; pin++) {
81
const reading = arduino.analogRead(pin);
82
const voltage = (reading / 1023) * 5.0; // Convert to voltage
83
console.log(`A${pin}: ${reading} (${voltage.toFixed(2)}V)`);
84
}
85
86
// Convert reading to percentage
87
const lightLevel = arduino.analogRead(1);
88
const lightPercentage = Math.round((lightLevel / 1023) * 100);
89
console.log(`Light sensor: ${lightPercentage}%`);
90
```
91
92
### Real-time Analog Change Monitoring
93
94
Monitor analog pin value changes in real-time using events.
95
96
```javascript { .api }
97
// Event: analogChange
98
// Fired when an analog pin value changes
99
// Event object properties:
100
interface AnalogChangeEvent {
101
pin: number; // Analog pin number that changed (0-5)
102
value: number; // New analog reading (0-1023)
103
old_value: number; // Previous analog reading
104
}
105
```
106
107
**Usage Example:**
108
109
```javascript
110
arduino.on('analogChange', function(event) {
111
console.log(`Analog pin A${event.pin} changed from ${event.old_value} to ${event.value}`);
112
113
// Example: Light sensor trigger
114
if (event.pin === 1 && event.value > 800 && event.old_value <= 800) {
115
console.log('Bright light detected!');
116
arduino.analogWrite(9, 255); // Turn on LED at full brightness
117
}
118
119
// Example: Potentiometer controlling LED brightness
120
if (event.pin === 0) {
121
const brightness = Math.round((event.value / 1023) * 255);
122
arduino.analogWrite(9, brightness);
123
console.log(`LED brightness set to ${brightness}/255`);
124
}
125
});
126
```
127
128
### Complete Analog I/O Example
129
130
```javascript
131
const ArduinoFirmata = require('arduino-firmata');
132
const arduino = new ArduinoFirmata();
133
134
arduino.connect();
135
136
arduino.on('connect', function() {
137
console.log('Arduino connected - Analog I/O ready');
138
139
// Read analog sensors periodically
140
setInterval(function() {
141
const pot = arduino.analogRead(0); // Potentiometer
142
const light = arduino.analogRead(1); // Light sensor
143
const temp = arduino.analogRead(2); // Temperature sensor
144
145
console.log(`Sensors - Pot: ${pot}, Light: ${light}, Temp: ${temp}`);
146
147
// Use potentiometer to control LED brightness
148
const brightness = Math.round((pot / 1023) * 255);
149
arduino.analogWrite(9, brightness);
150
151
}, 1000);
152
153
// Real-time analog monitoring for immediate responses
154
arduino.on('analogChange', function(event) {
155
// Quick response to light sensor changes
156
if (event.pin === 1) {
157
if (event.value < 300) { // Dark environment
158
arduino.analogWrite(10, 200); // Turn on status LED
159
} else { // Bright environment
160
arduino.analogWrite(10, 50); // Dim status LED
161
}
162
}
163
});
164
});
165
```
166
167
### PWM Frequency and Resolution
168
169
Arduino PWM operates at approximately 490 Hz (pins 5 and 6) or 980 Hz (other pins) with 8-bit resolution:
170
171
- **Resolution**: 8-bit (256 discrete levels: 0-255)
172
- **Frequency**: ~490 Hz or ~980 Hz depending on pin
173
- **Pins**: PWM-capable pins vary by Arduino model (typically 3, 5, 6, 9, 10, 11 on UNO)
174
175
### Analog Reference Voltage
176
177
Arduino analog readings are relative to the reference voltage:
178
179
- **Default**: 5V on 5V Arduino boards, 3.3V on 3.3V boards
180
- **Resolution**: 10-bit ADC provides 1024 discrete levels (0-1023)
181
- **Precision**: ~4.9mV per step on 5V boards (5V / 1024)
182
183
## Constants
184
185
```javascript { .api }
186
// Pin modes for analog operations
187
ArduinoFirmata.ANALOG = 2; // Analog input mode
188
ArduinoFirmata.PWM = 3; // PWM output mode
189
```
190
191
## Pin Mapping
192
193
### PWM Output Pins (Arduino UNO)
194
- **Pin 3**: PWM output (~980 Hz)
195
- **Pin 5**: PWM output (~490 Hz)
196
- **Pin 6**: PWM output (~490 Hz)
197
- **Pin 9**: PWM output (~980 Hz)
198
- **Pin 10**: PWM output (~980 Hz)
199
- **Pin 11**: PWM output (~980 Hz)
200
201
### Analog Input Pins (Arduino UNO)
202
- **A0 (pin 14)**: Analog input pin 0
203
- **A1 (pin 15)**: Analog input pin 1
204
- **A2 (pin 16)**: Analog input pin 2
205
- **A3 (pin 17)**: Analog input pin 3
206
- **A4 (pin 18)**: Analog input pin 4
207
- **A5 (pin 19)**: Analog input pin 5
208
209
**Note**: Analog pins can also be used as digital pins by referencing their digital pin numbers (14-19).
210
211
## Common Applications
212
213
### Sensor Reading
214
```javascript
215
// Temperature sensor (LM35) - converts reading to Celsius
216
const tempReading = arduino.analogRead(0);
217
const voltage = (tempReading * 5.0) / 1024;
218
const temperature = voltage * 100; // LM35 outputs 10mV per degree C
219
console.log(`Temperature: ${temperature.toFixed(1)}°C`);
220
```
221
222
### Motor Speed Control
223
```javascript
224
// Control DC motor speed with potentiometer
225
const speedControl = arduino.analogRead(0);
226
const motorSpeed = Math.round((speedControl / 1023) * 255);
227
arduino.analogWrite(9, motorSpeed); // Motor connected to pin 9
228
```
229
230
### LED Dimming
231
```javascript
232
// Smooth LED fade effect
233
let brightness = 0;
234
let fadeDirection = 1;
235
236
setInterval(function() {
237
arduino.analogWrite(9, brightness);
238
brightness += fadeDirection * 2;
239
240
if (brightness >= 255) {
241
fadeDirection = -1;
242
} else if (brightness <= 0) {
243
fadeDirection = 1;
244
}
245
}, 10);
246
```
247
248
## Event System Integration
249
250
Analog I/O operations integrate with the event system for real-time monitoring. See [Event System](./events.md) for complete event documentation including analog change events.