0
# Arduino Flashing
1
2
Core functionality for uploading compiled sketch files (.hex files) to Arduino boards with automatic board detection, protocol selection, and error handling.
3
4
## Capabilities
5
6
### AvrgirlArduino Constructor
7
8
Creates a new Arduino flashing instance with the specified configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new Arduino flashing instance
13
* @param {object} options - Configuration options
14
*/
15
function AvrgirlArduino(options);
16
17
interface AvrgirlArduinoOptions {
18
board: string | BoardConfig; // Board type name or custom board configuration
19
port?: string; // Serial port path (auto-detected if omitted)
20
debug?: boolean | function; // Debug logging: true, false, or custom function
21
megaDebug?: boolean; // Enhanced protocol-level debugging for detailed analysis
22
manualReset?: boolean; // Manual reset configuration for AVR109 boards
23
disableVerify?: boolean; // Skip verification after flash for AVR109 boards
24
}
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
const Avrgirl = require('avrgirl-arduino');
31
32
// Basic usage with board type
33
const avrgirl = new Avrgirl({
34
board: 'uno'
35
});
36
37
// With custom port and debugging
38
const avrgirlCustom = new Avrgirl({
39
board: 'leonardo',
40
port: '/dev/ttyACM0',
41
debug: true
42
});
43
44
// With custom debug function
45
const avrgirlWithLogger = new Avrgirl({
46
board: 'mega',
47
debug: function(message) {
48
console.log('[AVRGIRL]', new Date().toISOString(), message);
49
}
50
});
51
52
// With enhanced protocol debugging
53
const avrgirlMegaDebug = new Avrgirl({
54
board: 'leonardo',
55
megaDebug: true // Enhanced protocol-level debugging
56
});
57
58
// Using custom board configuration
59
const customBoard = {
60
name: 'my-custom-board',
61
baud: 115200,
62
signature: Buffer.from([0x1e, 0x95, 0x0f]),
63
pageSize: 128,
64
numPages: 256,
65
timeout: 400,
66
productId: ['0x0043'],
67
protocol: 'stk500v1'
68
};
69
70
const avrgirlCustomBoard = new Avrgirl({
71
board: customBoard
72
});
73
```
74
75
### Flash Method
76
77
Uploads a hex file to the connected Arduino board with automatic protocol handling.
78
79
```javascript { .api }
80
/**
81
* Flash a hex file to the Arduino board
82
* @param {string|Buffer} file - Path to hex file or Buffer containing hex data
83
* @param {function} callback - Completion callback function(error)
84
*/
85
flash(file: string | Buffer, callback: (error?: Error) => void): void;
86
```
87
88
**Usage Examples:**
89
90
```javascript
91
const Avrgirl = require('avrgirl-arduino');
92
const fs = require('fs');
93
94
const avrgirl = new Avrgirl({ board: 'uno' });
95
96
// Flash from file path
97
avrgirl.flash('/path/to/sketch.hex', function(error) {
98
if (error) {
99
console.error('Flash failed:', error.message);
100
} else {
101
console.log('Flash completed successfully!');
102
}
103
});
104
105
// Flash from Buffer (useful for in-memory hex data)
106
const hexData = fs.readFileSync('/path/to/sketch.hex');
107
avrgirl.flash(hexData, function(error) {
108
if (error) {
109
console.error('Flash failed:', error.message);
110
} else {
111
console.log('Flash completed successfully!');
112
}
113
});
114
115
// Flash from Buffer with hex string data
116
const hexBuffer = Buffer.from(':100000000C9434000C9446000C9446000C944600A2\n:00000001FF', 'ascii');
117
avrgirl.flash(hexBuffer, function(error) {
118
if (error) {
119
console.error('Flash from hex buffer failed:', error.message);
120
} else {
121
console.log('Hex buffer flashed successfully!');
122
}
123
});
124
125
// Flash with error handling
126
avrgirl.flash('sketch.hex', function(error) {
127
if (error) {
128
if (error.message.includes('not a supported board type')) {
129
console.error('Unsupported board type specified');
130
} else if (error.message.includes('no Arduino')) {
131
console.error('Arduino board not found. Check connection.');
132
} else if (error.message.includes('port')) {
133
console.error('Port communication error:', error.message);
134
} else {
135
console.error('Unknown error:', error.message);
136
}
137
return;
138
}
139
console.log('Successfully flashed Arduino!');
140
});
141
```
142
143
### Board Validation
144
145
Internal method that validates board configuration before attempting to flash.
146
147
```javascript { .api }
148
/**
149
* Validates the board properties and configuration
150
* @param {function} callback - Validation callback function(error)
151
*/
152
_validateBoard(callback: (error?: Error) => void): void;
153
```
154
155
This method checks:
156
- Board type is recognized and supported
157
- Protocol is available for the board type
158
- Required port is specified for boards that need it (e.g., pro-mini)
159
- Board configuration is valid
160
161
### Hex Parsing Tools
162
163
The AvrgirlArduino instance provides access to hex file parsing utilities through the `tools` property.
164
165
```javascript { .api }
166
/**
167
* Hex file parsing and utility functions
168
*/
169
interface Tools {
170
_parseHex(file: string | Buffer): Buffer | Error; // Parse Intel HEX format to binary
171
_hexStringToByte(str: string): Buffer; // Convert hex string to Buffer
172
}
173
```
174
175
**Usage Examples:**
176
177
```javascript
178
const avrgirl = new Avrgirl({ board: 'uno' });
179
180
// Parse hex file to binary data
181
const hexPath = 'sketch.hex';
182
const binaryData = avrgirl.tools._parseHex(hexPath);
183
if (binaryData instanceof Error) {
184
console.error('Hex parsing failed:', binaryData.message);
185
} else {
186
console.log('Parsed hex file, binary size:', binaryData.length);
187
}
188
189
// Convert hex string to Buffer
190
const hexString = '1E950F'; // Example device signature
191
const buffer = avrgirl.tools._hexStringToByte(hexString);
192
console.log('Hex to buffer:', buffer); // <Buffer 1e 95 0f>
193
```
194
195
### Event Handling
196
197
The AvrgirlArduino class extends EventEmitter, allowing you to listen for events during the flashing process.
198
199
```javascript { .api }
200
interface AvrgirlArduino extends EventEmitter {
201
// EventEmitter methods available
202
on(event: string, listener: Function): this;
203
emit(event: string, ...args: any[]): boolean;
204
removeListener(event: string, listener: Function): this;
205
removeAllListeners(event?: string): this;
206
}
207
```
208
209
**Usage Examples:**
210
211
```javascript
212
const avrgirl = new Avrgirl({ board: 'uno', debug: true });
213
214
// Listen for internal events (implementation-dependent)
215
avrgirl.on('error', (error) => {
216
console.error('Internal error:', error);
217
});
218
219
// Flash with event handling
220
avrgirl.flash('sketch.hex', (error) => {
221
// Main callback
222
});
223
```
224
225
## Flash Process Flow
226
227
The flashing process follows these steps:
228
229
1. **Board Validation**: Verify board configuration and protocol availability
230
2. **Port Detection**: Auto-detect Arduino port if not specified, or validate specified port
231
3. **Connection Setup**: Initialize serial port communication with board-specific settings
232
4. **Hex File Processing**: Parse and validate the hex file format
233
5. **Protocol Selection**: Choose appropriate protocol (STK500v1, STK500v2, or AVR109)
234
6. **Board Reset**: Reset the Arduino board to enter bootloader mode
235
7. **Firmware Upload**: Upload hex data using the selected protocol
236
8. **Verification**: Verify successful upload (unless disabled)
237
9. **Cleanup**: Close serial connection and complete the process
238
239
## Error Types
240
241
Common errors that may occur during flashing:
242
243
```javascript
244
// Board configuration errors
245
"\"unknown-board\" is not a supported board type."
246
"not a supported programming protocol: unknown-protocol"
247
"using a pro-mini, please specify the port in your options."
248
249
// Connection errors
250
"no Arduino 'uno' found."
251
"an unexpected error happened when connecting to board: [details]"
252
253
// File errors
254
"ENOENT: no such file or directory, open 'missing-file.hex'"
255
"Invalid hex file format"
256
257
// Protocol errors
258
"Communication timeout"
259
"Upload failed"
260
"Verification failed"
261
```
262
263
## Hex File Support
264
265
The library supports Intel HEX format files with the following characteristics:
266
267
- **File Extensions**: `.hex` files (standard Intel HEX format)
268
- **Input Types**: String file paths or Buffer objects containing hex data
269
- **Parsing**: Automatic hex file parsing and validation
270
- **Memory Layout**: Supports standard Arduino memory layout and addressing
271
- **Size Limits**: Respects board-specific flash memory constraints
272
273
## Protocol Support
274
275
### STK500v1 Protocol
276
- **Boards**: Arduino Uno, Mega, Nano, Duemilanove, Pro Mini, etc.
277
- **Features**: Page-based programming, signature verification, auto-reset via DTR
278
- **Baud Rates**: Typically 115200 or 57600 bps
279
280
### STK500v2 Protocol
281
- **Boards**: Specialized boards like Pinoccio Scout
282
- **Features**: Enhanced protocol with improved error handling
283
- **Baud Rates**: Board-specific configuration
284
285
### AVR109 Protocol
286
- **Boards**: Arduino Leonardo, Micro, Yun, Esplora, etc.
287
- **Features**: Native USB communication, different reset mechanism
288
- **Baud Rates**: Typically 57600 bps